Fix the legalization of ExtLoad on ARM. ExpandUnalignedLoad did not properly
[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/Analysis/AliasAnalysis.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 using namespace llvm;
39
40 STATISTIC(NodesCombined   , "Number of dag nodes combined");
41 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
42 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
43 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
44 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
45
46 namespace {
47   static cl::opt<bool>
48     CombinerAA("combiner-alias-analysis", cl::Hidden,
49                cl::desc("Turn on alias analysis during testing"));
50
51   static cl::opt<bool>
52     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53                cl::desc("Include global information in alias analysis"));
54
55 //------------------------------ DAGCombiner ---------------------------------//
56
57   class DAGCombiner {
58     SelectionDAG &DAG;
59     const TargetLowering &TLI;
60     CombineLevel Level;
61     CodeGenOpt::Level OptLevel;
62     bool LegalOperations;
63     bool LegalTypes;
64
65     // Worklist of all of the nodes that need to be simplified.
66     //
67     // This has the semantics that when adding to the worklist,
68     // the item added must be next to be processed. It should
69     // also only appear once. The naive approach to this takes
70     // linear time.
71     //
72     // To reduce the insert/remove time to logarithmic, we use
73     // a set and a vector to maintain our worklist.
74     //
75     // The set contains the items on the worklist, but does not
76     // maintain the order they should be visited.
77     //
78     // The vector maintains the order nodes should be visited, but may
79     // contain duplicate or removed nodes. When choosing a node to
80     // visit, we pop off the order stack until we find an item that is
81     // also in the contents set. All operations are O(log N).
82     SmallPtrSet<SDNode*, 64> WorkListContents;
83     SmallVector<SDNode*, 64> WorkListOrder;
84
85     // AA - Used for DAG load/store alias analysis.
86     AliasAnalysis &AA;
87
88     /// AddUsersToWorkList - When an instruction is simplified, add all users of
89     /// the instruction to the work lists because they might get more simplified
90     /// now.
91     ///
92     void AddUsersToWorkList(SDNode *N) {
93       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
94            UI != UE; ++UI)
95         AddToWorkList(*UI);
96     }
97
98     /// visit - call the node-specific routine that knows how to fold each
99     /// particular type of node.
100     SDValue visit(SDNode *N);
101
102   public:
103     /// AddToWorkList - Add to the work list making sure its instance is at the
104     /// back (next to be processed.)
105     void AddToWorkList(SDNode *N) {
106       WorkListContents.insert(N);
107       WorkListOrder.push_back(N);
108     }
109
110     /// removeFromWorkList - remove all instances of N from the worklist.
111     ///
112     void removeFromWorkList(SDNode *N) {
113       WorkListContents.erase(N);
114     }
115
116     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
117                       bool AddTo = true);
118
119     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
120       return CombineTo(N, &Res, 1, AddTo);
121     }
122
123     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
124                       bool AddTo = true) {
125       SDValue To[] = { Res0, Res1 };
126       return CombineTo(N, To, 2, AddTo);
127     }
128
129     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
130
131   private:
132
133     /// SimplifyDemandedBits - Check the specified integer node value to see if
134     /// it can be simplified or if things it uses can be simplified by bit
135     /// propagation.  If so, return true.
136     bool SimplifyDemandedBits(SDValue Op) {
137       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
138       APInt Demanded = APInt::getAllOnesValue(BitWidth);
139       return SimplifyDemandedBits(Op, Demanded);
140     }
141
142     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
143
144     bool CombineToPreIndexedLoadStore(SDNode *N);
145     bool CombineToPostIndexedLoadStore(SDNode *N);
146
147     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
148     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
149     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
150     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
151     SDValue PromoteIntBinOp(SDValue Op);
152     SDValue PromoteIntShiftOp(SDValue Op);
153     SDValue PromoteExtend(SDValue Op);
154     bool PromoteLoad(SDValue Op);
155
156     void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
157                          SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
158                          ISD::NodeType ExtType);
159
160     /// combine - call the node-specific routine that knows how to fold each
161     /// particular type of node. If that doesn't do anything, try the
162     /// target-specific DAG combines.
163     SDValue combine(SDNode *N);
164
165     // Visitation implementation - Implement dag node combining for different
166     // node types.  The semantics are as follows:
167     // Return Value:
168     //   SDValue.getNode() == 0 - No change was made
169     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
170     //   otherwise              - N should be replaced by the returned Operand.
171     //
172     SDValue visitTokenFactor(SDNode *N);
173     SDValue visitMERGE_VALUES(SDNode *N);
174     SDValue visitADD(SDNode *N);
175     SDValue visitSUB(SDNode *N);
176     SDValue visitADDC(SDNode *N);
177     SDValue visitSUBC(SDNode *N);
178     SDValue visitADDE(SDNode *N);
179     SDValue visitSUBE(SDNode *N);
180     SDValue visitMUL(SDNode *N);
181     SDValue visitSDIV(SDNode *N);
182     SDValue visitUDIV(SDNode *N);
183     SDValue visitSREM(SDNode *N);
184     SDValue visitUREM(SDNode *N);
185     SDValue visitMULHU(SDNode *N);
186     SDValue visitMULHS(SDNode *N);
187     SDValue visitSMUL_LOHI(SDNode *N);
188     SDValue visitUMUL_LOHI(SDNode *N);
189     SDValue visitSMULO(SDNode *N);
190     SDValue visitUMULO(SDNode *N);
191     SDValue visitSDIVREM(SDNode *N);
192     SDValue visitUDIVREM(SDNode *N);
193     SDValue visitAND(SDNode *N);
194     SDValue visitOR(SDNode *N);
195     SDValue visitXOR(SDNode *N);
196     SDValue SimplifyVBinOp(SDNode *N);
197     SDValue visitSHL(SDNode *N);
198     SDValue visitSRA(SDNode *N);
199     SDValue visitSRL(SDNode *N);
200     SDValue visitCTLZ(SDNode *N);
201     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
202     SDValue visitCTTZ(SDNode *N);
203     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
204     SDValue visitCTPOP(SDNode *N);
205     SDValue visitSELECT(SDNode *N);
206     SDValue visitSELECT_CC(SDNode *N);
207     SDValue visitSETCC(SDNode *N);
208     SDValue visitSIGN_EXTEND(SDNode *N);
209     SDValue visitZERO_EXTEND(SDNode *N);
210     SDValue visitANY_EXTEND(SDNode *N);
211     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
212     SDValue visitTRUNCATE(SDNode *N);
213     SDValue visitBITCAST(SDNode *N);
214     SDValue visitBUILD_PAIR(SDNode *N);
215     SDValue visitFADD(SDNode *N);
216     SDValue visitFSUB(SDNode *N);
217     SDValue visitFMUL(SDNode *N);
218     SDValue visitFMA(SDNode *N);
219     SDValue visitFDIV(SDNode *N);
220     SDValue visitFREM(SDNode *N);
221     SDValue visitFCOPYSIGN(SDNode *N);
222     SDValue visitSINT_TO_FP(SDNode *N);
223     SDValue visitUINT_TO_FP(SDNode *N);
224     SDValue visitFP_TO_SINT(SDNode *N);
225     SDValue visitFP_TO_UINT(SDNode *N);
226     SDValue visitFP_ROUND(SDNode *N);
227     SDValue visitFP_ROUND_INREG(SDNode *N);
228     SDValue visitFP_EXTEND(SDNode *N);
229     SDValue visitFNEG(SDNode *N);
230     SDValue visitFABS(SDNode *N);
231     SDValue visitBRCOND(SDNode *N);
232     SDValue visitBR_CC(SDNode *N);
233     SDValue visitLOAD(SDNode *N);
234     SDValue visitSTORE(SDNode *N);
235     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
236     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
237     SDValue visitBUILD_VECTOR(SDNode *N);
238     SDValue visitCONCAT_VECTORS(SDNode *N);
239     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
240     SDValue visitVECTOR_SHUFFLE(SDNode *N);
241     SDValue visitMEMBARRIER(SDNode *N);
242
243     SDValue XformToShuffleWithZero(SDNode *N);
244     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
245
246     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
247
248     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
249     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
250     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
251     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
252                              SDValue N3, ISD::CondCode CC,
253                              bool NotExtCompare = false);
254     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
255                           DebugLoc DL, bool foldBooleans = true);
256     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
257                                          unsigned HiOp);
258     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
259     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
260     SDValue BuildSDIV(SDNode *N);
261     SDValue BuildUDIV(SDNode *N);
262     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
263                                bool DemandHighBits = true);
264     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
265     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
266     SDValue ReduceLoadWidth(SDNode *N);
267     SDValue ReduceLoadOpStoreWidth(SDNode *N);
268     SDValue TransformFPLoadStorePair(SDNode *N);
269
270     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
271
272     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
273     /// looking for aliasing nodes and adding them to the Aliases vector.
274     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
275                           SmallVector<SDValue, 8> &Aliases);
276
277     /// isAlias - Return true if there is any possibility that the two addresses
278     /// overlap.
279     bool isAlias(SDValue Ptr1, int64_t Size1,
280                  const Value *SrcValue1, int SrcValueOffset1,
281                  unsigned SrcValueAlign1,
282                  const MDNode *TBAAInfo1,
283                  SDValue Ptr2, int64_t Size2,
284                  const Value *SrcValue2, int SrcValueOffset2,
285                  unsigned SrcValueAlign2,
286                  const MDNode *TBAAInfo2) const;
287
288     /// FindAliasInfo - Extracts the relevant alias information from the memory
289     /// node.  Returns true if the operand was a load.
290     bool FindAliasInfo(SDNode *N,
291                        SDValue &Ptr, int64_t &Size,
292                        const Value *&SrcValue, int &SrcValueOffset,
293                        unsigned &SrcValueAlignment,
294                        const MDNode *&TBAAInfo) const;
295
296     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
297     /// looking for a better chain (aliasing node.)
298     SDValue FindBetterChain(SDNode *N, SDValue Chain);
299
300   public:
301     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
302       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
303         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
304
305     /// Run - runs the dag combiner on all nodes in the work list
306     void Run(CombineLevel AtLevel);
307
308     SelectionDAG &getDAG() const { return DAG; }
309
310     /// getShiftAmountTy - Returns a type large enough to hold any valid
311     /// shift amount - before type legalization these can be huge.
312     EVT getShiftAmountTy(EVT LHSTy) {
313       return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
314     }
315
316     /// isTypeLegal - This method returns true if we are running before type
317     /// legalization or if the specified VT is legal.
318     bool isTypeLegal(const EVT &VT) {
319       if (!LegalTypes) return true;
320       return TLI.isTypeLegal(VT);
321     }
322   };
323 }
324
325
326 namespace {
327 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
328 /// nodes from the worklist.
329 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
330   DAGCombiner &DC;
331 public:
332   explicit WorkListRemover(DAGCombiner &dc)
333     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
334
335   virtual void NodeDeleted(SDNode *N, SDNode *E) {
336     DC.removeFromWorkList(N);
337   }
338 };
339 }
340
341 //===----------------------------------------------------------------------===//
342 //  TargetLowering::DAGCombinerInfo implementation
343 //===----------------------------------------------------------------------===//
344
345 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
346   ((DAGCombiner*)DC)->AddToWorkList(N);
347 }
348
349 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
350   ((DAGCombiner*)DC)->removeFromWorkList(N);
351 }
352
353 SDValue TargetLowering::DAGCombinerInfo::
354 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
355   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
356 }
357
358 SDValue TargetLowering::DAGCombinerInfo::
359 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
360   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
361 }
362
363
364 SDValue TargetLowering::DAGCombinerInfo::
365 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
366   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
367 }
368
369 void TargetLowering::DAGCombinerInfo::
370 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
371   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
372 }
373
374 //===----------------------------------------------------------------------===//
375 // Helper Functions
376 //===----------------------------------------------------------------------===//
377
378 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
379 /// specified expression for the same cost as the expression itself, or 2 if we
380 /// can compute the negated form more cheaply than the expression itself.
381 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
382                                const TargetLowering &TLI,
383                                const TargetOptions *Options,
384                                unsigned Depth = 0) {
385   // No compile time optimizations on this type.
386   if (Op.getValueType() == MVT::ppcf128)
387     return 0;
388
389   // fneg is removable even if it has multiple uses.
390   if (Op.getOpcode() == ISD::FNEG) return 2;
391
392   // Don't allow anything with multiple uses.
393   if (!Op.hasOneUse()) return 0;
394
395   // Don't recurse exponentially.
396   if (Depth > 6) return 0;
397
398   switch (Op.getOpcode()) {
399   default: return false;
400   case ISD::ConstantFP:
401     // Don't invert constant FP values after legalize.  The negated constant
402     // isn't necessarily legal.
403     return LegalOperations ? 0 : 1;
404   case ISD::FADD:
405     // FIXME: determine better conditions for this xform.
406     if (!Options->UnsafeFPMath) return 0;
407
408     // After operation legalization, it might not be legal to create new FSUBs.
409     if (LegalOperations &&
410         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
411       return 0;
412
413     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
414     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
415                                     Options, Depth + 1))
416       return V;
417     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
418     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
419                               Depth + 1);
420   case ISD::FSUB:
421     // We can't turn -(A-B) into B-A when we honor signed zeros.
422     if (!Options->UnsafeFPMath) return 0;
423
424     // fold (fneg (fsub A, B)) -> (fsub B, A)
425     return 1;
426
427   case ISD::FMUL:
428   case ISD::FDIV:
429     if (Options->HonorSignDependentRoundingFPMath()) return 0;
430
431     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
432     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
433                                     Options, Depth + 1))
434       return V;
435
436     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
437                               Depth + 1);
438
439   case ISD::FP_EXTEND:
440   case ISD::FP_ROUND:
441   case ISD::FSIN:
442     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
443                               Depth + 1);
444   }
445 }
446
447 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
448 /// returns the newly negated expression.
449 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
450                                     bool LegalOperations, unsigned Depth = 0) {
451   // fneg is removable even if it has multiple uses.
452   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
453
454   // Don't allow anything with multiple uses.
455   assert(Op.hasOneUse() && "Unknown reuse!");
456
457   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
458   switch (Op.getOpcode()) {
459   default: llvm_unreachable("Unknown code");
460   case ISD::ConstantFP: {
461     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
462     V.changeSign();
463     return DAG.getConstantFP(V, Op.getValueType());
464   }
465   case ISD::FADD:
466     // FIXME: determine better conditions for this xform.
467     assert(DAG.getTarget().Options.UnsafeFPMath);
468
469     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
470     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
471                            DAG.getTargetLoweringInfo(),
472                            &DAG.getTarget().Options, Depth+1))
473       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
474                          GetNegatedExpression(Op.getOperand(0), DAG,
475                                               LegalOperations, Depth+1),
476                          Op.getOperand(1));
477     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
478     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
479                        GetNegatedExpression(Op.getOperand(1), DAG,
480                                             LegalOperations, Depth+1),
481                        Op.getOperand(0));
482   case ISD::FSUB:
483     // We can't turn -(A-B) into B-A when we honor signed zeros.
484     assert(DAG.getTarget().Options.UnsafeFPMath);
485
486     // fold (fneg (fsub 0, B)) -> B
487     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
488       if (N0CFP->getValueAPF().isZero())
489         return Op.getOperand(1);
490
491     // fold (fneg (fsub A, B)) -> (fsub B, A)
492     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
493                        Op.getOperand(1), Op.getOperand(0));
494
495   case ISD::FMUL:
496   case ISD::FDIV:
497     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
498
499     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
500     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
501                            DAG.getTargetLoweringInfo(),
502                            &DAG.getTarget().Options, Depth+1))
503       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
504                          GetNegatedExpression(Op.getOperand(0), DAG,
505                                               LegalOperations, Depth+1),
506                          Op.getOperand(1));
507
508     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
509     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
510                        Op.getOperand(0),
511                        GetNegatedExpression(Op.getOperand(1), DAG,
512                                             LegalOperations, Depth+1));
513
514   case ISD::FP_EXTEND:
515   case ISD::FSIN:
516     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
517                        GetNegatedExpression(Op.getOperand(0), DAG,
518                                             LegalOperations, Depth+1));
519   case ISD::FP_ROUND:
520       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
521                          GetNegatedExpression(Op.getOperand(0), DAG,
522                                               LegalOperations, Depth+1),
523                          Op.getOperand(1));
524   }
525 }
526
527
528 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
529 // that selects between the values 1 and 0, making it equivalent to a setcc.
530 // Also, set the incoming LHS, RHS, and CC references to the appropriate
531 // nodes based on the type of node we are checking.  This simplifies life a
532 // bit for the callers.
533 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
534                               SDValue &CC) {
535   if (N.getOpcode() == ISD::SETCC) {
536     LHS = N.getOperand(0);
537     RHS = N.getOperand(1);
538     CC  = N.getOperand(2);
539     return true;
540   }
541   if (N.getOpcode() == ISD::SELECT_CC &&
542       N.getOperand(2).getOpcode() == ISD::Constant &&
543       N.getOperand(3).getOpcode() == ISD::Constant &&
544       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
545       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
546     LHS = N.getOperand(0);
547     RHS = N.getOperand(1);
548     CC  = N.getOperand(4);
549     return true;
550   }
551   return false;
552 }
553
554 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
555 // one use.  If this is true, it allows the users to invert the operation for
556 // free when it is profitable to do so.
557 static bool isOneUseSetCC(SDValue N) {
558   SDValue N0, N1, N2;
559   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
560     return true;
561   return false;
562 }
563
564 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
565                                     SDValue N0, SDValue N1) {
566   EVT VT = N0.getValueType();
567   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
568     if (isa<ConstantSDNode>(N1)) {
569       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
570       SDValue OpNode =
571         DAG.FoldConstantArithmetic(Opc, VT,
572                                    cast<ConstantSDNode>(N0.getOperand(1)),
573                                    cast<ConstantSDNode>(N1));
574       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
575     }
576     if (N0.hasOneUse()) {
577       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
578       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
579                                    N0.getOperand(0), N1);
580       AddToWorkList(OpNode.getNode());
581       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
582     }
583   }
584
585   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
586     if (isa<ConstantSDNode>(N0)) {
587       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
588       SDValue OpNode =
589         DAG.FoldConstantArithmetic(Opc, VT,
590                                    cast<ConstantSDNode>(N1.getOperand(1)),
591                                    cast<ConstantSDNode>(N0));
592       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
593     }
594     if (N1.hasOneUse()) {
595       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
596       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
597                                    N1.getOperand(0), N0);
598       AddToWorkList(OpNode.getNode());
599       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
600     }
601   }
602
603   return SDValue();
604 }
605
606 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
607                                bool AddTo) {
608   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
609   ++NodesCombined;
610   DEBUG(dbgs() << "\nReplacing.1 ";
611         N->dump(&DAG);
612         dbgs() << "\nWith: ";
613         To[0].getNode()->dump(&DAG);
614         dbgs() << " and " << NumTo-1 << " other values\n";
615         for (unsigned i = 0, e = NumTo; i != e; ++i)
616           assert((!To[i].getNode() ||
617                   N->getValueType(i) == To[i].getValueType()) &&
618                  "Cannot combine value to value of different type!"));
619   WorkListRemover DeadNodes(*this);
620   DAG.ReplaceAllUsesWith(N, To);
621   if (AddTo) {
622     // Push the new nodes and any users onto the worklist
623     for (unsigned i = 0, e = NumTo; i != e; ++i) {
624       if (To[i].getNode()) {
625         AddToWorkList(To[i].getNode());
626         AddUsersToWorkList(To[i].getNode());
627       }
628     }
629   }
630
631   // Finally, if the node is now dead, remove it from the graph.  The node
632   // may not be dead if the replacement process recursively simplified to
633   // something else needing this node.
634   if (N->use_empty()) {
635     // Nodes can be reintroduced into the worklist.  Make sure we do not
636     // process a node that has been replaced.
637     removeFromWorkList(N);
638
639     // Finally, since the node is now dead, remove it from the graph.
640     DAG.DeleteNode(N);
641   }
642   return SDValue(N, 0);
643 }
644
645 void DAGCombiner::
646 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
647   // Replace all uses.  If any nodes become isomorphic to other nodes and
648   // are deleted, make sure to remove them from our worklist.
649   WorkListRemover DeadNodes(*this);
650   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
651
652   // Push the new node and any (possibly new) users onto the worklist.
653   AddToWorkList(TLO.New.getNode());
654   AddUsersToWorkList(TLO.New.getNode());
655
656   // Finally, if the node is now dead, remove it from the graph.  The node
657   // may not be dead if the replacement process recursively simplified to
658   // something else needing this node.
659   if (TLO.Old.getNode()->use_empty()) {
660     removeFromWorkList(TLO.Old.getNode());
661
662     // If the operands of this node are only used by the node, they will now
663     // be dead.  Make sure to visit them first to delete dead nodes early.
664     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
665       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
666         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
667
668     DAG.DeleteNode(TLO.Old.getNode());
669   }
670 }
671
672 /// SimplifyDemandedBits - Check the specified integer node value to see if
673 /// it can be simplified or if things it uses can be simplified by bit
674 /// propagation.  If so, return true.
675 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
676   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
677   APInt KnownZero, KnownOne;
678   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
679     return false;
680
681   // Revisit the node.
682   AddToWorkList(Op.getNode());
683
684   // Replace the old value with the new one.
685   ++NodesCombined;
686   DEBUG(dbgs() << "\nReplacing.2 ";
687         TLO.Old.getNode()->dump(&DAG);
688         dbgs() << "\nWith: ";
689         TLO.New.getNode()->dump(&DAG);
690         dbgs() << '\n');
691
692   CommitTargetLoweringOpt(TLO);
693   return true;
694 }
695
696 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
697   DebugLoc dl = Load->getDebugLoc();
698   EVT VT = Load->getValueType(0);
699   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
700
701   DEBUG(dbgs() << "\nReplacing.9 ";
702         Load->dump(&DAG);
703         dbgs() << "\nWith: ";
704         Trunc.getNode()->dump(&DAG);
705         dbgs() << '\n');
706   WorkListRemover DeadNodes(*this);
707   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
708   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
709   removeFromWorkList(Load);
710   DAG.DeleteNode(Load);
711   AddToWorkList(Trunc.getNode());
712 }
713
714 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
715   Replace = false;
716   DebugLoc dl = Op.getDebugLoc();
717   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
718     EVT MemVT = LD->getMemoryVT();
719     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
720       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
721                                                   : ISD::EXTLOAD)
722       : LD->getExtensionType();
723     Replace = true;
724     return DAG.getExtLoad(ExtType, dl, PVT,
725                           LD->getChain(), LD->getBasePtr(),
726                           LD->getPointerInfo(),
727                           MemVT, LD->isVolatile(),
728                           LD->isNonTemporal(), LD->getAlignment());
729   }
730
731   unsigned Opc = Op.getOpcode();
732   switch (Opc) {
733   default: break;
734   case ISD::AssertSext:
735     return DAG.getNode(ISD::AssertSext, dl, PVT,
736                        SExtPromoteOperand(Op.getOperand(0), PVT),
737                        Op.getOperand(1));
738   case ISD::AssertZext:
739     return DAG.getNode(ISD::AssertZext, dl, PVT,
740                        ZExtPromoteOperand(Op.getOperand(0), PVT),
741                        Op.getOperand(1));
742   case ISD::Constant: {
743     unsigned ExtOpc =
744       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
745     return DAG.getNode(ExtOpc, dl, PVT, Op);
746   }
747   }
748
749   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
750     return SDValue();
751   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
752 }
753
754 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
755   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
756     return SDValue();
757   EVT OldVT = Op.getValueType();
758   DebugLoc dl = Op.getDebugLoc();
759   bool Replace = false;
760   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
761   if (NewOp.getNode() == 0)
762     return SDValue();
763   AddToWorkList(NewOp.getNode());
764
765   if (Replace)
766     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
767   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
768                      DAG.getValueType(OldVT));
769 }
770
771 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
772   EVT OldVT = Op.getValueType();
773   DebugLoc dl = Op.getDebugLoc();
774   bool Replace = false;
775   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
776   if (NewOp.getNode() == 0)
777     return SDValue();
778   AddToWorkList(NewOp.getNode());
779
780   if (Replace)
781     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
782   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
783 }
784
785 /// PromoteIntBinOp - Promote the specified integer binary operation if the
786 /// target indicates it is beneficial. e.g. On x86, it's usually better to
787 /// promote i16 operations to i32 since i16 instructions are longer.
788 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
789   if (!LegalOperations)
790     return SDValue();
791
792   EVT VT = Op.getValueType();
793   if (VT.isVector() || !VT.isInteger())
794     return SDValue();
795
796   // If operation type is 'undesirable', e.g. i16 on x86, consider
797   // promoting it.
798   unsigned Opc = Op.getOpcode();
799   if (TLI.isTypeDesirableForOp(Opc, VT))
800     return SDValue();
801
802   EVT PVT = VT;
803   // Consult target whether it is a good idea to promote this operation and
804   // what's the right type to promote it to.
805   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
806     assert(PVT != VT && "Don't know what type to promote to!");
807
808     bool Replace0 = false;
809     SDValue N0 = Op.getOperand(0);
810     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
811     if (NN0.getNode() == 0)
812       return SDValue();
813
814     bool Replace1 = false;
815     SDValue N1 = Op.getOperand(1);
816     SDValue NN1;
817     if (N0 == N1)
818       NN1 = NN0;
819     else {
820       NN1 = PromoteOperand(N1, PVT, Replace1);
821       if (NN1.getNode() == 0)
822         return SDValue();
823     }
824
825     AddToWorkList(NN0.getNode());
826     if (NN1.getNode())
827       AddToWorkList(NN1.getNode());
828
829     if (Replace0)
830       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
831     if (Replace1)
832       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.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, NN0, NN1));
839   }
840   return SDValue();
841 }
842
843 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
844 /// target indicates it is beneficial. e.g. On x86, it's usually better to
845 /// promote i16 operations to i32 since i16 instructions are longer.
846 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
847   if (!LegalOperations)
848     return SDValue();
849
850   EVT VT = Op.getValueType();
851   if (VT.isVector() || !VT.isInteger())
852     return SDValue();
853
854   // If operation type is 'undesirable', e.g. i16 on x86, consider
855   // promoting it.
856   unsigned Opc = Op.getOpcode();
857   if (TLI.isTypeDesirableForOp(Opc, VT))
858     return SDValue();
859
860   EVT PVT = VT;
861   // Consult target whether it is a good idea to promote this operation and
862   // what's the right type to promote it to.
863   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
864     assert(PVT != VT && "Don't know what type to promote to!");
865
866     bool Replace = false;
867     SDValue N0 = Op.getOperand(0);
868     if (Opc == ISD::SRA)
869       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
870     else if (Opc == ISD::SRL)
871       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
872     else
873       N0 = PromoteOperand(N0, PVT, Replace);
874     if (N0.getNode() == 0)
875       return SDValue();
876
877     AddToWorkList(N0.getNode());
878     if (Replace)
879       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
880
881     DEBUG(dbgs() << "\nPromoting ";
882           Op.getNode()->dump(&DAG));
883     DebugLoc dl = Op.getDebugLoc();
884     return DAG.getNode(ISD::TRUNCATE, dl, VT,
885                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
886   }
887   return SDValue();
888 }
889
890 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
891   if (!LegalOperations)
892     return SDValue();
893
894   EVT VT = Op.getValueType();
895   if (VT.isVector() || !VT.isInteger())
896     return SDValue();
897
898   // If operation type is 'undesirable', e.g. i16 on x86, consider
899   // promoting it.
900   unsigned Opc = Op.getOpcode();
901   if (TLI.isTypeDesirableForOp(Opc, VT))
902     return SDValue();
903
904   EVT PVT = VT;
905   // Consult target whether it is a good idea to promote this operation and
906   // what's the right type to promote it to.
907   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908     assert(PVT != VT && "Don't know what type to promote to!");
909     // fold (aext (aext x)) -> (aext x)
910     // fold (aext (zext x)) -> (zext x)
911     // fold (aext (sext x)) -> (sext x)
912     DEBUG(dbgs() << "\nPromoting ";
913           Op.getNode()->dump(&DAG));
914     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
915   }
916   return SDValue();
917 }
918
919 bool DAGCombiner::PromoteLoad(SDValue Op) {
920   if (!LegalOperations)
921     return false;
922
923   EVT VT = Op.getValueType();
924   if (VT.isVector() || !VT.isInteger())
925     return false;
926
927   // If operation type is 'undesirable', e.g. i16 on x86, consider
928   // promoting it.
929   unsigned Opc = Op.getOpcode();
930   if (TLI.isTypeDesirableForOp(Opc, VT))
931     return false;
932
933   EVT PVT = VT;
934   // Consult target whether it is a good idea to promote this operation and
935   // what's the right type to promote it to.
936   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
937     assert(PVT != VT && "Don't know what type to promote to!");
938
939     DebugLoc dl = Op.getDebugLoc();
940     SDNode *N = Op.getNode();
941     LoadSDNode *LD = cast<LoadSDNode>(N);
942     EVT MemVT = LD->getMemoryVT();
943     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
944       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
945                                                   : ISD::EXTLOAD)
946       : LD->getExtensionType();
947     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
948                                    LD->getChain(), LD->getBasePtr(),
949                                    LD->getPointerInfo(),
950                                    MemVT, LD->isVolatile(),
951                                    LD->isNonTemporal(), LD->getAlignment());
952     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
953
954     DEBUG(dbgs() << "\nPromoting ";
955           N->dump(&DAG);
956           dbgs() << "\nTo: ";
957           Result.getNode()->dump(&DAG);
958           dbgs() << '\n');
959     WorkListRemover DeadNodes(*this);
960     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
961     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
962     removeFromWorkList(N);
963     DAG.DeleteNode(N);
964     AddToWorkList(Result.getNode());
965     return true;
966   }
967   return false;
968 }
969
970
971 //===----------------------------------------------------------------------===//
972 //  Main DAG Combiner implementation
973 //===----------------------------------------------------------------------===//
974
975 void DAGCombiner::Run(CombineLevel AtLevel) {
976   // set the instance variables, so that the various visit routines may use it.
977   Level = AtLevel;
978   LegalOperations = Level >= AfterLegalizeVectorOps;
979   LegalTypes = Level >= AfterLegalizeTypes;
980
981   // Add all the dag nodes to the worklist.
982   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
983        E = DAG.allnodes_end(); I != E; ++I)
984     AddToWorkList(I);
985
986   // Create a dummy node (which is not added to allnodes), that adds a reference
987   // to the root node, preventing it from being deleted, and tracking any
988   // changes of the root.
989   HandleSDNode Dummy(DAG.getRoot());
990
991   // The root of the dag may dangle to deleted nodes until the dag combiner is
992   // done.  Set it to null to avoid confusion.
993   DAG.setRoot(SDValue());
994
995   // while the worklist isn't empty, find a node and
996   // try and combine it.
997   while (!WorkListContents.empty()) {
998     SDNode *N;
999     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1000     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1001     // worklist *should* contain, and check the node we want to visit is should
1002     // actually be visited.
1003     do {
1004       N = WorkListOrder.pop_back_val();
1005     } while (!WorkListContents.erase(N));
1006
1007     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1008     // N is deleted from the DAG, since they too may now be dead or may have a
1009     // reduced number of uses, allowing other xforms.
1010     if (N->use_empty() && N != &Dummy) {
1011       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1012         AddToWorkList(N->getOperand(i).getNode());
1013
1014       DAG.DeleteNode(N);
1015       continue;
1016     }
1017
1018     SDValue RV = combine(N);
1019
1020     if (RV.getNode() == 0)
1021       continue;
1022
1023     ++NodesCombined;
1024
1025     // If we get back the same node we passed in, rather than a new node or
1026     // zero, we know that the node must have defined multiple values and
1027     // CombineTo was used.  Since CombineTo takes care of the worklist
1028     // mechanics for us, we have no work to do in this case.
1029     if (RV.getNode() == N)
1030       continue;
1031
1032     assert(N->getOpcode() != ISD::DELETED_NODE &&
1033            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1034            "Node was deleted but visit returned new node!");
1035
1036     DEBUG(dbgs() << "\nReplacing.3 ";
1037           N->dump(&DAG);
1038           dbgs() << "\nWith: ";
1039           RV.getNode()->dump(&DAG);
1040           dbgs() << '\n');
1041
1042     // Transfer debug value.
1043     DAG.TransferDbgValues(SDValue(N, 0), RV);
1044     WorkListRemover DeadNodes(*this);
1045     if (N->getNumValues() == RV.getNode()->getNumValues())
1046       DAG.ReplaceAllUsesWith(N, RV.getNode());
1047     else {
1048       assert(N->getValueType(0) == RV.getValueType() &&
1049              N->getNumValues() == 1 && "Type mismatch");
1050       SDValue OpV = RV;
1051       DAG.ReplaceAllUsesWith(N, &OpV);
1052     }
1053
1054     // Push the new node and any users onto the worklist
1055     AddToWorkList(RV.getNode());
1056     AddUsersToWorkList(RV.getNode());
1057
1058     // Add any uses of the old node to the worklist in case this node is the
1059     // last one that uses them.  They may become dead after this node is
1060     // deleted.
1061     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1062       AddToWorkList(N->getOperand(i).getNode());
1063
1064     // Finally, if the node is now dead, remove it from the graph.  The node
1065     // may not be dead if the replacement process recursively simplified to
1066     // something else needing this node.
1067     if (N->use_empty()) {
1068       // Nodes can be reintroduced into the worklist.  Make sure we do not
1069       // process a node that has been replaced.
1070       removeFromWorkList(N);
1071
1072       // Finally, since the node is now dead, remove it from the graph.
1073       DAG.DeleteNode(N);
1074     }
1075   }
1076
1077   // If the root changed (e.g. it was a dead load, update the root).
1078   DAG.setRoot(Dummy.getValue());
1079   DAG.RemoveDeadNodes();
1080 }
1081
1082 SDValue DAGCombiner::visit(SDNode *N) {
1083   switch (N->getOpcode()) {
1084   default: break;
1085   case ISD::TokenFactor:        return visitTokenFactor(N);
1086   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1087   case ISD::ADD:                return visitADD(N);
1088   case ISD::SUB:                return visitSUB(N);
1089   case ISD::ADDC:               return visitADDC(N);
1090   case ISD::SUBC:               return visitSUBC(N);
1091   case ISD::ADDE:               return visitADDE(N);
1092   case ISD::SUBE:               return visitSUBE(N);
1093   case ISD::MUL:                return visitMUL(N);
1094   case ISD::SDIV:               return visitSDIV(N);
1095   case ISD::UDIV:               return visitUDIV(N);
1096   case ISD::SREM:               return visitSREM(N);
1097   case ISD::UREM:               return visitUREM(N);
1098   case ISD::MULHU:              return visitMULHU(N);
1099   case ISD::MULHS:              return visitMULHS(N);
1100   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1101   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1102   case ISD::SMULO:              return visitSMULO(N);
1103   case ISD::UMULO:              return visitUMULO(N);
1104   case ISD::SDIVREM:            return visitSDIVREM(N);
1105   case ISD::UDIVREM:            return visitUDIVREM(N);
1106   case ISD::AND:                return visitAND(N);
1107   case ISD::OR:                 return visitOR(N);
1108   case ISD::XOR:                return visitXOR(N);
1109   case ISD::SHL:                return visitSHL(N);
1110   case ISD::SRA:                return visitSRA(N);
1111   case ISD::SRL:                return visitSRL(N);
1112   case ISD::CTLZ:               return visitCTLZ(N);
1113   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1114   case ISD::CTTZ:               return visitCTTZ(N);
1115   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1116   case ISD::CTPOP:              return visitCTPOP(N);
1117   case ISD::SELECT:             return visitSELECT(N);
1118   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1119   case ISD::SETCC:              return visitSETCC(N);
1120   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1121   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1122   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1123   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1124   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1125   case ISD::BITCAST:            return visitBITCAST(N);
1126   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1127   case ISD::FADD:               return visitFADD(N);
1128   case ISD::FSUB:               return visitFSUB(N);
1129   case ISD::FMUL:               return visitFMUL(N);
1130   case ISD::FMA:                return visitFMA(N);
1131   case ISD::FDIV:               return visitFDIV(N);
1132   case ISD::FREM:               return visitFREM(N);
1133   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1134   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1135   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1136   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1137   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1138   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1139   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1140   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1141   case ISD::FNEG:               return visitFNEG(N);
1142   case ISD::FABS:               return visitFABS(N);
1143   case ISD::BRCOND:             return visitBRCOND(N);
1144   case ISD::BR_CC:              return visitBR_CC(N);
1145   case ISD::LOAD:               return visitLOAD(N);
1146   case ISD::STORE:              return visitSTORE(N);
1147   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1148   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1149   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1150   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1151   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1152   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1153   case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
1154   }
1155   return SDValue();
1156 }
1157
1158 SDValue DAGCombiner::combine(SDNode *N) {
1159   SDValue RV = visit(N);
1160
1161   // If nothing happened, try a target-specific DAG combine.
1162   if (RV.getNode() == 0) {
1163     assert(N->getOpcode() != ISD::DELETED_NODE &&
1164            "Node was deleted but visit returned NULL!");
1165
1166     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1167         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1168
1169       // Expose the DAG combiner to the target combiner impls.
1170       TargetLowering::DAGCombinerInfo
1171         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1172
1173       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1174     }
1175   }
1176
1177   // If nothing happened still, try promoting the operation.
1178   if (RV.getNode() == 0) {
1179     switch (N->getOpcode()) {
1180     default: break;
1181     case ISD::ADD:
1182     case ISD::SUB:
1183     case ISD::MUL:
1184     case ISD::AND:
1185     case ISD::OR:
1186     case ISD::XOR:
1187       RV = PromoteIntBinOp(SDValue(N, 0));
1188       break;
1189     case ISD::SHL:
1190     case ISD::SRA:
1191     case ISD::SRL:
1192       RV = PromoteIntShiftOp(SDValue(N, 0));
1193       break;
1194     case ISD::SIGN_EXTEND:
1195     case ISD::ZERO_EXTEND:
1196     case ISD::ANY_EXTEND:
1197       RV = PromoteExtend(SDValue(N, 0));
1198       break;
1199     case ISD::LOAD:
1200       if (PromoteLoad(SDValue(N, 0)))
1201         RV = SDValue(N, 0);
1202       break;
1203     }
1204   }
1205
1206   // If N is a commutative binary node, try commuting it to enable more
1207   // sdisel CSE.
1208   if (RV.getNode() == 0 &&
1209       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1210       N->getNumValues() == 1) {
1211     SDValue N0 = N->getOperand(0);
1212     SDValue N1 = N->getOperand(1);
1213
1214     // Constant operands are canonicalized to RHS.
1215     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1216       SDValue Ops[] = { N1, N0 };
1217       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1218                                             Ops, 2);
1219       if (CSENode)
1220         return SDValue(CSENode, 0);
1221     }
1222   }
1223
1224   return RV;
1225 }
1226
1227 /// getInputChainForNode - Given a node, return its input chain if it has one,
1228 /// otherwise return a null sd operand.
1229 static SDValue getInputChainForNode(SDNode *N) {
1230   if (unsigned NumOps = N->getNumOperands()) {
1231     if (N->getOperand(0).getValueType() == MVT::Other)
1232       return N->getOperand(0);
1233     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1234       return N->getOperand(NumOps-1);
1235     for (unsigned i = 1; i < NumOps-1; ++i)
1236       if (N->getOperand(i).getValueType() == MVT::Other)
1237         return N->getOperand(i);
1238   }
1239   return SDValue();
1240 }
1241
1242 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1243   // If N has two operands, where one has an input chain equal to the other,
1244   // the 'other' chain is redundant.
1245   if (N->getNumOperands() == 2) {
1246     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1247       return N->getOperand(0);
1248     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1249       return N->getOperand(1);
1250   }
1251
1252   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1253   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1254   SmallPtrSet<SDNode*, 16> SeenOps;
1255   bool Changed = false;             // If we should replace this token factor.
1256
1257   // Start out with this token factor.
1258   TFs.push_back(N);
1259
1260   // Iterate through token factors.  The TFs grows when new token factors are
1261   // encountered.
1262   for (unsigned i = 0; i < TFs.size(); ++i) {
1263     SDNode *TF = TFs[i];
1264
1265     // Check each of the operands.
1266     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1267       SDValue Op = TF->getOperand(i);
1268
1269       switch (Op.getOpcode()) {
1270       case ISD::EntryToken:
1271         // Entry tokens don't need to be added to the list. They are
1272         // rededundant.
1273         Changed = true;
1274         break;
1275
1276       case ISD::TokenFactor:
1277         if (Op.hasOneUse() &&
1278             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1279           // Queue up for processing.
1280           TFs.push_back(Op.getNode());
1281           // Clean up in case the token factor is removed.
1282           AddToWorkList(Op.getNode());
1283           Changed = true;
1284           break;
1285         }
1286         // Fall thru
1287
1288       default:
1289         // Only add if it isn't already in the list.
1290         if (SeenOps.insert(Op.getNode()))
1291           Ops.push_back(Op);
1292         else
1293           Changed = true;
1294         break;
1295       }
1296     }
1297   }
1298
1299   SDValue Result;
1300
1301   // If we've change things around then replace token factor.
1302   if (Changed) {
1303     if (Ops.empty()) {
1304       // The entry token is the only possible outcome.
1305       Result = DAG.getEntryNode();
1306     } else {
1307       // New and improved token factor.
1308       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1309                            MVT::Other, &Ops[0], Ops.size());
1310     }
1311
1312     // Don't add users to work list.
1313     return CombineTo(N, Result, false);
1314   }
1315
1316   return Result;
1317 }
1318
1319 /// MERGE_VALUES can always be eliminated.
1320 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1321   WorkListRemover DeadNodes(*this);
1322   // Replacing results may cause a different MERGE_VALUES to suddenly
1323   // be CSE'd with N, and carry its uses with it. Iterate until no
1324   // uses remain, to ensure that the node can be safely deleted.
1325   // First add the users of this node to the work list so that they
1326   // can be tried again once they have new operands.
1327   AddUsersToWorkList(N);
1328   do {
1329     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1330       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1331   } while (!N->use_empty());
1332   removeFromWorkList(N);
1333   DAG.DeleteNode(N);
1334   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1335 }
1336
1337 static
1338 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1339                               SelectionDAG &DAG) {
1340   EVT VT = N0.getValueType();
1341   SDValue N00 = N0.getOperand(0);
1342   SDValue N01 = N0.getOperand(1);
1343   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1344
1345   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1346       isa<ConstantSDNode>(N00.getOperand(1))) {
1347     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1348     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1349                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1350                                  N00.getOperand(0), N01),
1351                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1352                                  N00.getOperand(1), N01));
1353     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1354   }
1355
1356   return SDValue();
1357 }
1358
1359 SDValue DAGCombiner::visitADD(SDNode *N) {
1360   SDValue N0 = N->getOperand(0);
1361   SDValue N1 = N->getOperand(1);
1362   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1363   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1364   EVT VT = N0.getValueType();
1365
1366   // fold vector ops
1367   if (VT.isVector()) {
1368     SDValue FoldedVOp = SimplifyVBinOp(N);
1369     if (FoldedVOp.getNode()) return FoldedVOp;
1370   }
1371
1372   // fold (add x, undef) -> undef
1373   if (N0.getOpcode() == ISD::UNDEF)
1374     return N0;
1375   if (N1.getOpcode() == ISD::UNDEF)
1376     return N1;
1377   // fold (add c1, c2) -> c1+c2
1378   if (N0C && N1C)
1379     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1380   // canonicalize constant to RHS
1381   if (N0C && !N1C)
1382     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1383   // fold (add x, 0) -> x
1384   if (N1C && N1C->isNullValue())
1385     return N0;
1386   // fold (add Sym, c) -> Sym+c
1387   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1388     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1389         GA->getOpcode() == ISD::GlobalAddress)
1390       return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1391                                   GA->getOffset() +
1392                                     (uint64_t)N1C->getSExtValue());
1393   // fold ((c1-A)+c2) -> (c1+c2)-A
1394   if (N1C && N0.getOpcode() == ISD::SUB)
1395     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1396       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1397                          DAG.getConstant(N1C->getAPIntValue()+
1398                                          N0C->getAPIntValue(), VT),
1399                          N0.getOperand(1));
1400   // reassociate add
1401   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1402   if (RADD.getNode() != 0)
1403     return RADD;
1404   // fold ((0-A) + B) -> B-A
1405   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1406       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1407     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1408   // fold (A + (0-B)) -> A-B
1409   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1410       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1411     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1412   // fold (A+(B-A)) -> B
1413   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1414     return N1.getOperand(0);
1415   // fold ((B-A)+A) -> B
1416   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1417     return N0.getOperand(0);
1418   // fold (A+(B-(A+C))) to (B-C)
1419   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1420       N0 == N1.getOperand(1).getOperand(0))
1421     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1422                        N1.getOperand(1).getOperand(1));
1423   // fold (A+(B-(C+A))) to (B-C)
1424   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1425       N0 == N1.getOperand(1).getOperand(1))
1426     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1427                        N1.getOperand(1).getOperand(0));
1428   // fold (A+((B-A)+or-C)) to (B+or-C)
1429   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1430       N1.getOperand(0).getOpcode() == ISD::SUB &&
1431       N0 == N1.getOperand(0).getOperand(1))
1432     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1433                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1434
1435   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1436   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1437     SDValue N00 = N0.getOperand(0);
1438     SDValue N01 = N0.getOperand(1);
1439     SDValue N10 = N1.getOperand(0);
1440     SDValue N11 = N1.getOperand(1);
1441
1442     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1443       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1444                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1445                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1446   }
1447
1448   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1449     return SDValue(N, 0);
1450
1451   // fold (a+b) -> (a|b) iff a and b share no bits.
1452   if (VT.isInteger() && !VT.isVector()) {
1453     APInt LHSZero, LHSOne;
1454     APInt RHSZero, RHSOne;
1455     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1456
1457     if (LHSZero.getBoolValue()) {
1458       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1459
1460       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1461       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1462       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1463         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1464     }
1465   }
1466
1467   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1468   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1469     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1470     if (Result.getNode()) return Result;
1471   }
1472   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1473     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1474     if (Result.getNode()) return Result;
1475   }
1476
1477   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1478   if (N1.getOpcode() == ISD::SHL &&
1479       N1.getOperand(0).getOpcode() == ISD::SUB)
1480     if (ConstantSDNode *C =
1481           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1482       if (C->getAPIntValue() == 0)
1483         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1484                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1485                                        N1.getOperand(0).getOperand(1),
1486                                        N1.getOperand(1)));
1487   if (N0.getOpcode() == ISD::SHL &&
1488       N0.getOperand(0).getOpcode() == ISD::SUB)
1489     if (ConstantSDNode *C =
1490           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1491       if (C->getAPIntValue() == 0)
1492         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1493                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1494                                        N0.getOperand(0).getOperand(1),
1495                                        N0.getOperand(1)));
1496
1497   if (N1.getOpcode() == ISD::AND) {
1498     SDValue AndOp0 = N1.getOperand(0);
1499     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1500     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1501     unsigned DestBits = VT.getScalarType().getSizeInBits();
1502
1503     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1504     // and similar xforms where the inner op is either ~0 or 0.
1505     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1506       DebugLoc DL = N->getDebugLoc();
1507       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1508     }
1509   }
1510
1511   // add (sext i1), X -> sub X, (zext i1)
1512   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1513       N0.getOperand(0).getValueType() == MVT::i1 &&
1514       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1515     DebugLoc DL = N->getDebugLoc();
1516     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1517     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1518   }
1519
1520   return SDValue();
1521 }
1522
1523 SDValue DAGCombiner::visitADDC(SDNode *N) {
1524   SDValue N0 = N->getOperand(0);
1525   SDValue N1 = N->getOperand(1);
1526   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1527   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1528   EVT VT = N0.getValueType();
1529
1530   // If the flag result is dead, turn this into an ADD.
1531   if (!N->hasAnyUseOfValue(1))
1532     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1533                      DAG.getNode(ISD::CARRY_FALSE,
1534                                  N->getDebugLoc(), MVT::Glue));
1535
1536   // canonicalize constant to RHS.
1537   if (N0C && !N1C)
1538     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1539
1540   // fold (addc x, 0) -> x + no carry out
1541   if (N1C && N1C->isNullValue())
1542     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1543                                         N->getDebugLoc(), MVT::Glue));
1544
1545   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1546   APInt LHSZero, LHSOne;
1547   APInt RHSZero, RHSOne;
1548   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1549
1550   if (LHSZero.getBoolValue()) {
1551     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1552
1553     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1554     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1555     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1556       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1557                        DAG.getNode(ISD::CARRY_FALSE,
1558                                    N->getDebugLoc(), MVT::Glue));
1559   }
1560
1561   return SDValue();
1562 }
1563
1564 SDValue DAGCombiner::visitADDE(SDNode *N) {
1565   SDValue N0 = N->getOperand(0);
1566   SDValue N1 = N->getOperand(1);
1567   SDValue CarryIn = N->getOperand(2);
1568   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1569   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1570
1571   // canonicalize constant to RHS
1572   if (N0C && !N1C)
1573     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1574                        N1, N0, CarryIn);
1575
1576   // fold (adde x, y, false) -> (addc x, y)
1577   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1578     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1579
1580   return SDValue();
1581 }
1582
1583 // Since it may not be valid to emit a fold to zero for vector initializers
1584 // check if we can before folding.
1585 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1586                              SelectionDAG &DAG, bool LegalOperations) {
1587   if (!VT.isVector()) {
1588     return DAG.getConstant(0, VT);
1589   }
1590   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1591     // Produce a vector of zeros.
1592     SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1593     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1594     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1595       &Ops[0], Ops.size());
1596   }
1597   return SDValue();
1598 }
1599
1600 SDValue DAGCombiner::visitSUB(SDNode *N) {
1601   SDValue N0 = N->getOperand(0);
1602   SDValue N1 = N->getOperand(1);
1603   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1604   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1605   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1606     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1607   EVT VT = N0.getValueType();
1608
1609   // fold vector ops
1610   if (VT.isVector()) {
1611     SDValue FoldedVOp = SimplifyVBinOp(N);
1612     if (FoldedVOp.getNode()) return FoldedVOp;
1613   }
1614
1615   // fold (sub x, x) -> 0
1616   // FIXME: Refactor this and xor and other similar operations together.
1617   if (N0 == N1)
1618     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1619   // fold (sub c1, c2) -> c1-c2
1620   if (N0C && N1C)
1621     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1622   // fold (sub x, c) -> (add x, -c)
1623   if (N1C)
1624     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1625                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1626   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1627   if (N0C && N0C->isAllOnesValue())
1628     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1629   // fold A-(A-B) -> B
1630   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1631     return N1.getOperand(1);
1632   // fold (A+B)-A -> B
1633   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1634     return N0.getOperand(1);
1635   // fold (A+B)-B -> A
1636   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1637     return N0.getOperand(0);
1638   // fold C2-(A+C1) -> (C2-C1)-A
1639   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1640     SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT);
1641     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1642                        N1.getOperand(0));
1643   }
1644   // fold ((A+(B+or-C))-B) -> A+or-C
1645   if (N0.getOpcode() == ISD::ADD &&
1646       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1647        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1648       N0.getOperand(1).getOperand(0) == N1)
1649     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1650                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1651   // fold ((A+(C+B))-B) -> A+C
1652   if (N0.getOpcode() == ISD::ADD &&
1653       N0.getOperand(1).getOpcode() == ISD::ADD &&
1654       N0.getOperand(1).getOperand(1) == N1)
1655     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1656                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1657   // fold ((A-(B-C))-C) -> A-B
1658   if (N0.getOpcode() == ISD::SUB &&
1659       N0.getOperand(1).getOpcode() == ISD::SUB &&
1660       N0.getOperand(1).getOperand(1) == N1)
1661     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1662                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1663
1664   // If either operand of a sub is undef, the result is undef
1665   if (N0.getOpcode() == ISD::UNDEF)
1666     return N0;
1667   if (N1.getOpcode() == ISD::UNDEF)
1668     return N1;
1669
1670   // If the relocation model supports it, consider symbol offsets.
1671   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1672     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1673       // fold (sub Sym, c) -> Sym-c
1674       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1675         return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1676                                     GA->getOffset() -
1677                                       (uint64_t)N1C->getSExtValue());
1678       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1679       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1680         if (GA->getGlobal() == GB->getGlobal())
1681           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1682                                  VT);
1683     }
1684
1685   return SDValue();
1686 }
1687
1688 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1689   SDValue N0 = N->getOperand(0);
1690   SDValue N1 = N->getOperand(1);
1691   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1692   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1693   EVT VT = N0.getValueType();
1694
1695   // If the flag result is dead, turn this into an SUB.
1696   if (!N->hasAnyUseOfValue(1))
1697     return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1698                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1699                                  MVT::Glue));
1700
1701   // fold (subc x, x) -> 0 + no borrow
1702   if (N0 == N1)
1703     return CombineTo(N, DAG.getConstant(0, VT),
1704                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1705                                  MVT::Glue));
1706
1707   // fold (subc x, 0) -> x + no borrow
1708   if (N1C && N1C->isNullValue())
1709     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1710                                         MVT::Glue));
1711
1712   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1713   if (N0C && N0C->isAllOnesValue())
1714     return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1715                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1716                                  MVT::Glue));
1717
1718   return SDValue();
1719 }
1720
1721 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1722   SDValue N0 = N->getOperand(0);
1723   SDValue N1 = N->getOperand(1);
1724   SDValue CarryIn = N->getOperand(2);
1725
1726   // fold (sube x, y, false) -> (subc x, y)
1727   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1728     return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1729
1730   return SDValue();
1731 }
1732
1733 SDValue DAGCombiner::visitMUL(SDNode *N) {
1734   SDValue N0 = N->getOperand(0);
1735   SDValue N1 = N->getOperand(1);
1736   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1737   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1738   EVT VT = N0.getValueType();
1739
1740   // fold vector ops
1741   if (VT.isVector()) {
1742     SDValue FoldedVOp = SimplifyVBinOp(N);
1743     if (FoldedVOp.getNode()) return FoldedVOp;
1744   }
1745
1746   // fold (mul x, undef) -> 0
1747   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1748     return DAG.getConstant(0, VT);
1749   // fold (mul c1, c2) -> c1*c2
1750   if (N0C && N1C)
1751     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1752   // canonicalize constant to RHS
1753   if (N0C && !N1C)
1754     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1755   // fold (mul x, 0) -> 0
1756   if (N1C && N1C->isNullValue())
1757     return N1;
1758   // fold (mul x, -1) -> 0-x
1759   if (N1C && N1C->isAllOnesValue())
1760     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1761                        DAG.getConstant(0, VT), N0);
1762   // fold (mul x, (1 << c)) -> x << c
1763   if (N1C && N1C->getAPIntValue().isPowerOf2())
1764     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1765                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1766                                        getShiftAmountTy(N0.getValueType())));
1767   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1768   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1769     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1770     // FIXME: If the input is something that is easily negated (e.g. a
1771     // single-use add), we should put the negate there.
1772     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1773                        DAG.getConstant(0, VT),
1774                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1775                             DAG.getConstant(Log2Val,
1776                                       getShiftAmountTy(N0.getValueType()))));
1777   }
1778   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1779   if (N1C && N0.getOpcode() == ISD::SHL &&
1780       isa<ConstantSDNode>(N0.getOperand(1))) {
1781     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1782                              N1, N0.getOperand(1));
1783     AddToWorkList(C3.getNode());
1784     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1785                        N0.getOperand(0), C3);
1786   }
1787
1788   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1789   // use.
1790   {
1791     SDValue Sh(0,0), Y(0,0);
1792     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1793     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1794         N0.getNode()->hasOneUse()) {
1795       Sh = N0; Y = N1;
1796     } else if (N1.getOpcode() == ISD::SHL &&
1797                isa<ConstantSDNode>(N1.getOperand(1)) &&
1798                N1.getNode()->hasOneUse()) {
1799       Sh = N1; Y = N0;
1800     }
1801
1802     if (Sh.getNode()) {
1803       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1804                                 Sh.getOperand(0), Y);
1805       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1806                          Mul, Sh.getOperand(1));
1807     }
1808   }
1809
1810   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1811   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1812       isa<ConstantSDNode>(N0.getOperand(1)))
1813     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1814                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1815                                    N0.getOperand(0), N1),
1816                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1817                                    N0.getOperand(1), N1));
1818
1819   // reassociate mul
1820   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1821   if (RMUL.getNode() != 0)
1822     return RMUL;
1823
1824   return SDValue();
1825 }
1826
1827 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1828   SDValue N0 = N->getOperand(0);
1829   SDValue N1 = N->getOperand(1);
1830   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1831   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1832   EVT VT = N->getValueType(0);
1833
1834   // fold vector ops
1835   if (VT.isVector()) {
1836     SDValue FoldedVOp = SimplifyVBinOp(N);
1837     if (FoldedVOp.getNode()) return FoldedVOp;
1838   }
1839
1840   // fold (sdiv c1, c2) -> c1/c2
1841   if (N0C && N1C && !N1C->isNullValue())
1842     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1843   // fold (sdiv X, 1) -> X
1844   if (N1C && N1C->getAPIntValue() == 1LL)
1845     return N0;
1846   // fold (sdiv X, -1) -> 0-X
1847   if (N1C && N1C->isAllOnesValue())
1848     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1849                        DAG.getConstant(0, VT), N0);
1850   // If we know the sign bits of both operands are zero, strength reduce to a
1851   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1852   if (!VT.isVector()) {
1853     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1854       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1855                          N0, N1);
1856   }
1857   // fold (sdiv X, pow2) -> simple ops after legalize
1858   if (N1C && !N1C->isNullValue() &&
1859       (N1C->getAPIntValue().isPowerOf2() ||
1860        (-N1C->getAPIntValue()).isPowerOf2())) {
1861     // If dividing by powers of two is cheap, then don't perform the following
1862     // fold.
1863     if (TLI.isPow2DivCheap())
1864       return SDValue();
1865
1866     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1867
1868     // Splat the sign bit into the register
1869     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1870                               DAG.getConstant(VT.getSizeInBits()-1,
1871                                        getShiftAmountTy(N0.getValueType())));
1872     AddToWorkList(SGN.getNode());
1873
1874     // Add (N0 < 0) ? abs2 - 1 : 0;
1875     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1876                               DAG.getConstant(VT.getSizeInBits() - lg2,
1877                                        getShiftAmountTy(SGN.getValueType())));
1878     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1879     AddToWorkList(SRL.getNode());
1880     AddToWorkList(ADD.getNode());    // Divide by pow2
1881     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1882                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1883
1884     // If we're dividing by a positive value, we're done.  Otherwise, we must
1885     // negate the result.
1886     if (N1C->getAPIntValue().isNonNegative())
1887       return SRA;
1888
1889     AddToWorkList(SRA.getNode());
1890     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1891                        DAG.getConstant(0, VT), SRA);
1892   }
1893
1894   // if integer divide is expensive and we satisfy the requirements, emit an
1895   // alternate sequence.
1896   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1897     SDValue Op = BuildSDIV(N);
1898     if (Op.getNode()) return Op;
1899   }
1900
1901   // undef / X -> 0
1902   if (N0.getOpcode() == ISD::UNDEF)
1903     return DAG.getConstant(0, VT);
1904   // X / undef -> undef
1905   if (N1.getOpcode() == ISD::UNDEF)
1906     return N1;
1907
1908   return SDValue();
1909 }
1910
1911 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1912   SDValue N0 = N->getOperand(0);
1913   SDValue N1 = N->getOperand(1);
1914   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1915   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1916   EVT VT = N->getValueType(0);
1917
1918   // fold vector ops
1919   if (VT.isVector()) {
1920     SDValue FoldedVOp = SimplifyVBinOp(N);
1921     if (FoldedVOp.getNode()) return FoldedVOp;
1922   }
1923
1924   // fold (udiv c1, c2) -> c1/c2
1925   if (N0C && N1C && !N1C->isNullValue())
1926     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1927   // fold (udiv x, (1 << c)) -> x >>u c
1928   if (N1C && N1C->getAPIntValue().isPowerOf2())
1929     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1930                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1931                                        getShiftAmountTy(N0.getValueType())));
1932   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1933   if (N1.getOpcode() == ISD::SHL) {
1934     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1935       if (SHC->getAPIntValue().isPowerOf2()) {
1936         EVT ADDVT = N1.getOperand(1).getValueType();
1937         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1938                                   N1.getOperand(1),
1939                                   DAG.getConstant(SHC->getAPIntValue()
1940                                                                   .logBase2(),
1941                                                   ADDVT));
1942         AddToWorkList(Add.getNode());
1943         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1944       }
1945     }
1946   }
1947   // fold (udiv x, c) -> alternate
1948   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1949     SDValue Op = BuildUDIV(N);
1950     if (Op.getNode()) return Op;
1951   }
1952
1953   // undef / X -> 0
1954   if (N0.getOpcode() == ISD::UNDEF)
1955     return DAG.getConstant(0, VT);
1956   // X / undef -> undef
1957   if (N1.getOpcode() == ISD::UNDEF)
1958     return N1;
1959
1960   return SDValue();
1961 }
1962
1963 SDValue DAGCombiner::visitSREM(SDNode *N) {
1964   SDValue N0 = N->getOperand(0);
1965   SDValue N1 = N->getOperand(1);
1966   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1967   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1968   EVT VT = N->getValueType(0);
1969
1970   // fold (srem c1, c2) -> c1%c2
1971   if (N0C && N1C && !N1C->isNullValue())
1972     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1973   // If we know the sign bits of both operands are zero, strength reduce to a
1974   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1975   if (!VT.isVector()) {
1976     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1977       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1978   }
1979
1980   // If X/C can be simplified by the division-by-constant logic, lower
1981   // X%C to the equivalent of X-X/C*C.
1982   if (N1C && !N1C->isNullValue()) {
1983     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1984     AddToWorkList(Div.getNode());
1985     SDValue OptimizedDiv = combine(Div.getNode());
1986     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1987       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1988                                 OptimizedDiv, N1);
1989       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1990       AddToWorkList(Mul.getNode());
1991       return Sub;
1992     }
1993   }
1994
1995   // undef % X -> 0
1996   if (N0.getOpcode() == ISD::UNDEF)
1997     return DAG.getConstant(0, VT);
1998   // X % undef -> undef
1999   if (N1.getOpcode() == ISD::UNDEF)
2000     return N1;
2001
2002   return SDValue();
2003 }
2004
2005 SDValue DAGCombiner::visitUREM(SDNode *N) {
2006   SDValue N0 = N->getOperand(0);
2007   SDValue N1 = N->getOperand(1);
2008   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2009   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2010   EVT VT = N->getValueType(0);
2011
2012   // fold (urem c1, c2) -> c1%c2
2013   if (N0C && N1C && !N1C->isNullValue())
2014     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2015   // fold (urem x, pow2) -> (and x, pow2-1)
2016   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2017     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2018                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2019   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2020   if (N1.getOpcode() == ISD::SHL) {
2021     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2022       if (SHC->getAPIntValue().isPowerOf2()) {
2023         SDValue Add =
2024           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2025                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2026                                  VT));
2027         AddToWorkList(Add.getNode());
2028         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2029       }
2030     }
2031   }
2032
2033   // If X/C can be simplified by the division-by-constant logic, lower
2034   // X%C to the equivalent of X-X/C*C.
2035   if (N1C && !N1C->isNullValue()) {
2036     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2037     AddToWorkList(Div.getNode());
2038     SDValue OptimizedDiv = combine(Div.getNode());
2039     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2040       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2041                                 OptimizedDiv, N1);
2042       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2043       AddToWorkList(Mul.getNode());
2044       return Sub;
2045     }
2046   }
2047
2048   // undef % X -> 0
2049   if (N0.getOpcode() == ISD::UNDEF)
2050     return DAG.getConstant(0, VT);
2051   // X % undef -> undef
2052   if (N1.getOpcode() == ISD::UNDEF)
2053     return N1;
2054
2055   return SDValue();
2056 }
2057
2058 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2059   SDValue N0 = N->getOperand(0);
2060   SDValue N1 = N->getOperand(1);
2061   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2062   EVT VT = N->getValueType(0);
2063   DebugLoc DL = N->getDebugLoc();
2064
2065   // fold (mulhs x, 0) -> 0
2066   if (N1C && N1C->isNullValue())
2067     return N1;
2068   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2069   if (N1C && N1C->getAPIntValue() == 1)
2070     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2071                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2072                                        getShiftAmountTy(N0.getValueType())));
2073   // fold (mulhs x, undef) -> 0
2074   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2075     return DAG.getConstant(0, VT);
2076
2077   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2078   // plus a shift.
2079   if (VT.isSimple() && !VT.isVector()) {
2080     MVT Simple = VT.getSimpleVT();
2081     unsigned SimpleSize = Simple.getSizeInBits();
2082     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2083     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2084       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2085       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2086       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2087       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2088             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2089       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2090     }
2091   }
2092
2093   return SDValue();
2094 }
2095
2096 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2097   SDValue N0 = N->getOperand(0);
2098   SDValue N1 = N->getOperand(1);
2099   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2100   EVT VT = N->getValueType(0);
2101   DebugLoc DL = N->getDebugLoc();
2102
2103   // fold (mulhu x, 0) -> 0
2104   if (N1C && N1C->isNullValue())
2105     return N1;
2106   // fold (mulhu x, 1) -> 0
2107   if (N1C && N1C->getAPIntValue() == 1)
2108     return DAG.getConstant(0, N0.getValueType());
2109   // fold (mulhu x, undef) -> 0
2110   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2111     return DAG.getConstant(0, VT);
2112
2113   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2114   // plus a shift.
2115   if (VT.isSimple() && !VT.isVector()) {
2116     MVT Simple = VT.getSimpleVT();
2117     unsigned SimpleSize = Simple.getSizeInBits();
2118     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2119     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2120       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2121       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2122       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2123       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2124             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2125       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2126     }
2127   }
2128
2129   return SDValue();
2130 }
2131
2132 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2133 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2134 /// that are being performed. Return true if a simplification was made.
2135 ///
2136 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2137                                                 unsigned HiOp) {
2138   // If the high half is not needed, just compute the low half.
2139   bool HiExists = N->hasAnyUseOfValue(1);
2140   if (!HiExists &&
2141       (!LegalOperations ||
2142        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2143     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2144                               N->op_begin(), N->getNumOperands());
2145     return CombineTo(N, Res, Res);
2146   }
2147
2148   // If the low half is not needed, just compute the high half.
2149   bool LoExists = N->hasAnyUseOfValue(0);
2150   if (!LoExists &&
2151       (!LegalOperations ||
2152        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2153     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2154                               N->op_begin(), N->getNumOperands());
2155     return CombineTo(N, Res, Res);
2156   }
2157
2158   // If both halves are used, return as it is.
2159   if (LoExists && HiExists)
2160     return SDValue();
2161
2162   // If the two computed results can be simplified separately, separate them.
2163   if (LoExists) {
2164     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2165                              N->op_begin(), N->getNumOperands());
2166     AddToWorkList(Lo.getNode());
2167     SDValue LoOpt = combine(Lo.getNode());
2168     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2169         (!LegalOperations ||
2170          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2171       return CombineTo(N, LoOpt, LoOpt);
2172   }
2173
2174   if (HiExists) {
2175     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2176                              N->op_begin(), N->getNumOperands());
2177     AddToWorkList(Hi.getNode());
2178     SDValue HiOpt = combine(Hi.getNode());
2179     if (HiOpt.getNode() && HiOpt != Hi &&
2180         (!LegalOperations ||
2181          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2182       return CombineTo(N, HiOpt, HiOpt);
2183   }
2184
2185   return SDValue();
2186 }
2187
2188 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2189   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2190   if (Res.getNode()) return Res;
2191
2192   EVT VT = N->getValueType(0);
2193   DebugLoc DL = N->getDebugLoc();
2194
2195   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2196   // plus a shift.
2197   if (VT.isSimple() && !VT.isVector()) {
2198     MVT Simple = VT.getSimpleVT();
2199     unsigned SimpleSize = Simple.getSizeInBits();
2200     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2201     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2202       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2203       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2204       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2205       // Compute the high part as N1.
2206       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2207             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2208       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2209       // Compute the low part as N0.
2210       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2211       return CombineTo(N, Lo, Hi);
2212     }
2213   }
2214
2215   return SDValue();
2216 }
2217
2218 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2219   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2220   if (Res.getNode()) return Res;
2221
2222   EVT VT = N->getValueType(0);
2223   DebugLoc DL = N->getDebugLoc();
2224
2225   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2226   // plus a shift.
2227   if (VT.isSimple() && !VT.isVector()) {
2228     MVT Simple = VT.getSimpleVT();
2229     unsigned SimpleSize = Simple.getSizeInBits();
2230     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2231     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2232       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2233       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2234       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2235       // Compute the high part as N1.
2236       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2237             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2238       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2239       // Compute the low part as N0.
2240       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2241       return CombineTo(N, Lo, Hi);
2242     }
2243   }
2244
2245   return SDValue();
2246 }
2247
2248 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2249   // (smulo x, 2) -> (saddo x, x)
2250   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2251     if (C2->getAPIntValue() == 2)
2252       return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2253                          N->getOperand(0), N->getOperand(0));
2254
2255   return SDValue();
2256 }
2257
2258 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2259   // (umulo x, 2) -> (uaddo x, x)
2260   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2261     if (C2->getAPIntValue() == 2)
2262       return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2263                          N->getOperand(0), N->getOperand(0));
2264
2265   return SDValue();
2266 }
2267
2268 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2269   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2270   if (Res.getNode()) return Res;
2271
2272   return SDValue();
2273 }
2274
2275 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2276   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2277   if (Res.getNode()) return Res;
2278
2279   return SDValue();
2280 }
2281
2282 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2283 /// two operands of the same opcode, try to simplify it.
2284 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2285   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2286   EVT VT = N0.getValueType();
2287   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2288
2289   // Bail early if none of these transforms apply.
2290   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2291
2292   // For each of OP in AND/OR/XOR:
2293   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2294   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2295   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2296   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2297   //
2298   // do not sink logical op inside of a vector extend, since it may combine
2299   // into a vsetcc.
2300   EVT Op0VT = N0.getOperand(0).getValueType();
2301   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2302        N0.getOpcode() == ISD::SIGN_EXTEND ||
2303        // Avoid infinite looping with PromoteIntBinOp.
2304        (N0.getOpcode() == ISD::ANY_EXTEND &&
2305         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2306        (N0.getOpcode() == ISD::TRUNCATE &&
2307         (!TLI.isZExtFree(VT, Op0VT) ||
2308          !TLI.isTruncateFree(Op0VT, VT)) &&
2309         TLI.isTypeLegal(Op0VT))) &&
2310       !VT.isVector() &&
2311       Op0VT == N1.getOperand(0).getValueType() &&
2312       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2313     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2314                                  N0.getOperand(0).getValueType(),
2315                                  N0.getOperand(0), N1.getOperand(0));
2316     AddToWorkList(ORNode.getNode());
2317     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2318   }
2319
2320   // For each of OP in SHL/SRL/SRA/AND...
2321   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2322   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2323   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2324   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2325        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2326       N0.getOperand(1) == N1.getOperand(1)) {
2327     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2328                                  N0.getOperand(0).getValueType(),
2329                                  N0.getOperand(0), N1.getOperand(0));
2330     AddToWorkList(ORNode.getNode());
2331     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2332                        ORNode, N0.getOperand(1));
2333   }
2334
2335   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2336   // Only perform this optimization after type legalization and before
2337   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2338   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2339   // we don't want to undo this promotion.
2340   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2341   // on scalars.
2342   if ((N0.getOpcode() == ISD::BITCAST || N0.getOpcode() == ISD::SCALAR_TO_VECTOR)
2343       && Level == AfterLegalizeTypes) {
2344     SDValue In0 = N0.getOperand(0);
2345     SDValue In1 = N1.getOperand(0);
2346     EVT In0Ty = In0.getValueType();
2347     EVT In1Ty = In1.getValueType();
2348     // If both incoming values are integers, and the original types are the same.
2349     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2350       SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), In0Ty, In0, In1);
2351       SDValue BC = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, Op);
2352       AddToWorkList(Op.getNode());
2353       return BC;
2354     }
2355   }
2356
2357   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2358   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2359   // If both shuffles use the same mask, and both shuffle within a single
2360   // vector, then it is worthwhile to move the swizzle after the operation.
2361   // The type-legalizer generates this pattern when loading illegal
2362   // vector types from memory. In many cases this allows additional shuffle
2363   // optimizations.
2364   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2365       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2366       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2367     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2368     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2369
2370     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2371            "Inputs to shuffles are not the same type");
2372
2373     unsigned NumElts = VT.getVectorNumElements();
2374
2375     // Check that both shuffles use the same mask. The masks are known to be of
2376     // the same length because the result vector type is the same.
2377     bool SameMask = true;
2378     for (unsigned i = 0; i != NumElts; ++i) {
2379       int Idx0 = SVN0->getMaskElt(i);
2380       int Idx1 = SVN1->getMaskElt(i);
2381       if (Idx0 != Idx1) {
2382         SameMask = false;
2383         break;
2384       }
2385     }
2386
2387     if (SameMask) {
2388       SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2389                                N0.getOperand(0), N1.getOperand(0));
2390       AddToWorkList(Op.getNode());
2391       return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2392                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2393     }
2394   }
2395
2396   return SDValue();
2397 }
2398
2399 SDValue DAGCombiner::visitAND(SDNode *N) {
2400   SDValue N0 = N->getOperand(0);
2401   SDValue N1 = N->getOperand(1);
2402   SDValue LL, LR, RL, RR, CC0, CC1;
2403   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2404   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2405   EVT VT = N1.getValueType();
2406   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2407
2408   // fold vector ops
2409   if (VT.isVector()) {
2410     SDValue FoldedVOp = SimplifyVBinOp(N);
2411     if (FoldedVOp.getNode()) return FoldedVOp;
2412   }
2413
2414   // fold (and x, undef) -> 0
2415   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2416     return DAG.getConstant(0, VT);
2417   // fold (and c1, c2) -> c1&c2
2418   if (N0C && N1C)
2419     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2420   // canonicalize constant to RHS
2421   if (N0C && !N1C)
2422     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2423   // fold (and x, -1) -> x
2424   if (N1C && N1C->isAllOnesValue())
2425     return N0;
2426   // if (and x, c) is known to be zero, return 0
2427   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2428                                    APInt::getAllOnesValue(BitWidth)))
2429     return DAG.getConstant(0, VT);
2430   // reassociate and
2431   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2432   if (RAND.getNode() != 0)
2433     return RAND;
2434   // fold (and (or x, C), D) -> D if (C & D) == D
2435   if (N1C && N0.getOpcode() == ISD::OR)
2436     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2437       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2438         return N1;
2439   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2440   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2441     SDValue N0Op0 = N0.getOperand(0);
2442     APInt Mask = ~N1C->getAPIntValue();
2443     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2444     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2445       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2446                                  N0.getValueType(), N0Op0);
2447
2448       // Replace uses of the AND with uses of the Zero extend node.
2449       CombineTo(N, Zext);
2450
2451       // We actually want to replace all uses of the any_extend with the
2452       // zero_extend, to avoid duplicating things.  This will later cause this
2453       // AND to be folded.
2454       CombineTo(N0.getNode(), Zext);
2455       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2456     }
2457   }
2458   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 
2459   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2460   // already be zero by virtue of the width of the base type of the load.
2461   //
2462   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2463   // more cases.
2464   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2465        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2466       N0.getOpcode() == ISD::LOAD) {
2467     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2468                                          N0 : N0.getOperand(0) );
2469
2470     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2471     // This can be a pure constant or a vector splat, in which case we treat the
2472     // vector as a scalar and use the splat value.
2473     APInt Constant = APInt::getNullValue(1);
2474     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2475       Constant = C->getAPIntValue();
2476     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2477       APInt SplatValue, SplatUndef;
2478       unsigned SplatBitSize;
2479       bool HasAnyUndefs;
2480       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2481                                              SplatBitSize, HasAnyUndefs);
2482       if (IsSplat) {
2483         // Undef bits can contribute to a possible optimisation if set, so
2484         // set them.
2485         SplatValue |= SplatUndef;
2486
2487         // The splat value may be something like "0x00FFFFFF", which means 0 for
2488         // the first vector value and FF for the rest, repeating. We need a mask
2489         // that will apply equally to all members of the vector, so AND all the
2490         // lanes of the constant together.
2491         EVT VT = Vector->getValueType(0);
2492         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2493         Constant = APInt::getAllOnesValue(BitWidth);
2494         for (unsigned i = 0, n = VT.getVectorNumElements(); i < n; ++i)
2495           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2496       }
2497     }
2498
2499     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2500     // actually legal and isn't going to get expanded, else this is a false
2501     // optimisation.
2502     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2503                                                     Load->getMemoryVT());
2504
2505     // Resize the constant to the same size as the original memory access before
2506     // extension. If it is still the AllOnesValue then this AND is completely
2507     // unneeded.
2508     Constant =
2509       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2510
2511     bool B;
2512     switch (Load->getExtensionType()) {
2513     default: B = false; break;
2514     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2515     case ISD::ZEXTLOAD:
2516     case ISD::NON_EXTLOAD: B = true; break;
2517     }
2518
2519     if (B && Constant.isAllOnesValue()) {
2520       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2521       // preserve semantics once we get rid of the AND.
2522       SDValue NewLoad(Load, 0);
2523       if (Load->getExtensionType() == ISD::EXTLOAD) {
2524         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2525                               Load->getValueType(0), Load->getDebugLoc(),
2526                               Load->getChain(), Load->getBasePtr(),
2527                               Load->getOffset(), Load->getMemoryVT(),
2528                               Load->getMemOperand());
2529         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2530         if (Load->getNumValues() == 3) {
2531           // PRE/POST_INC loads have 3 values.
2532           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2533                            NewLoad.getValue(2) };
2534           CombineTo(Load, To, 3, true);
2535         } else {
2536           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2537         }
2538       }
2539
2540       // Fold the AND away, taking care not to fold to the old load node if we
2541       // replaced it.
2542       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2543
2544       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2545     }
2546   }
2547   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2548   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2549     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2550     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2551
2552     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2553         LL.getValueType().isInteger()) {
2554       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2555       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2556         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2557                                      LR.getValueType(), LL, RL);
2558         AddToWorkList(ORNode.getNode());
2559         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2560       }
2561       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2562       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2563         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2564                                       LR.getValueType(), LL, RL);
2565         AddToWorkList(ANDNode.getNode());
2566         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2567       }
2568       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2569       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2570         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2571                                      LR.getValueType(), LL, RL);
2572         AddToWorkList(ORNode.getNode());
2573         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2574       }
2575     }
2576     // canonicalize equivalent to ll == rl
2577     if (LL == RR && LR == RL) {
2578       Op1 = ISD::getSetCCSwappedOperands(Op1);
2579       std::swap(RL, RR);
2580     }
2581     if (LL == RL && LR == RR) {
2582       bool isInteger = LL.getValueType().isInteger();
2583       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2584       if (Result != ISD::SETCC_INVALID &&
2585           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2586         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2587                             LL, LR, Result);
2588     }
2589   }
2590
2591   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2592   if (N0.getOpcode() == N1.getOpcode()) {
2593     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2594     if (Tmp.getNode()) return Tmp;
2595   }
2596
2597   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2598   // fold (and (sra)) -> (and (srl)) when possible.
2599   if (!VT.isVector() &&
2600       SimplifyDemandedBits(SDValue(N, 0)))
2601     return SDValue(N, 0);
2602
2603   // fold (zext_inreg (extload x)) -> (zextload x)
2604   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2605     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2606     EVT MemVT = LN0->getMemoryVT();
2607     // If we zero all the possible extended bits, then we can turn this into
2608     // a zextload if we are running before legalize or the operation is legal.
2609     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2610     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2611                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2612         ((!LegalOperations && !LN0->isVolatile()) ||
2613          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2614       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2615                                        LN0->getChain(), LN0->getBasePtr(),
2616                                        LN0->getPointerInfo(), MemVT,
2617                                        LN0->isVolatile(), LN0->isNonTemporal(),
2618                                        LN0->getAlignment());
2619       AddToWorkList(N);
2620       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2621       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2622     }
2623   }
2624   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2625   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2626       N0.hasOneUse()) {
2627     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2628     EVT MemVT = LN0->getMemoryVT();
2629     // If we zero all the possible extended bits, then we can turn this into
2630     // a zextload if we are running before legalize or the operation is legal.
2631     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2632     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2633                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2634         ((!LegalOperations && !LN0->isVolatile()) ||
2635          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2636       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2637                                        LN0->getChain(),
2638                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2639                                        MemVT,
2640                                        LN0->isVolatile(), LN0->isNonTemporal(),
2641                                        LN0->getAlignment());
2642       AddToWorkList(N);
2643       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2644       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2645     }
2646   }
2647
2648   // fold (and (load x), 255) -> (zextload x, i8)
2649   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2650   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2651   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2652               (N0.getOpcode() == ISD::ANY_EXTEND &&
2653                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2654     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2655     LoadSDNode *LN0 = HasAnyExt
2656       ? cast<LoadSDNode>(N0.getOperand(0))
2657       : cast<LoadSDNode>(N0);
2658     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2659         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2660       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2661       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2662         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2663         EVT LoadedVT = LN0->getMemoryVT();
2664
2665         if (ExtVT == LoadedVT &&
2666             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2667           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2668
2669           SDValue NewLoad =
2670             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2671                            LN0->getChain(), LN0->getBasePtr(),
2672                            LN0->getPointerInfo(),
2673                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2674                            LN0->getAlignment());
2675           AddToWorkList(N);
2676           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2677           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2678         }
2679
2680         // Do not change the width of a volatile load.
2681         // Do not generate loads of non-round integer types since these can
2682         // be expensive (and would be wrong if the type is not byte sized).
2683         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2684             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2685           EVT PtrType = LN0->getOperand(1).getValueType();
2686
2687           unsigned Alignment = LN0->getAlignment();
2688           SDValue NewPtr = LN0->getBasePtr();
2689
2690           // For big endian targets, we need to add an offset to the pointer
2691           // to load the correct bytes.  For little endian systems, we merely
2692           // need to read fewer bytes from the same pointer.
2693           if (TLI.isBigEndian()) {
2694             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2695             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2696             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2697             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2698                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2699             Alignment = MinAlign(Alignment, PtrOff);
2700           }
2701
2702           AddToWorkList(NewPtr.getNode());
2703
2704           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2705           SDValue Load =
2706             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2707                            LN0->getChain(), NewPtr,
2708                            LN0->getPointerInfo(),
2709                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2710                            Alignment);
2711           AddToWorkList(N);
2712           CombineTo(LN0, Load, Load.getValue(1));
2713           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2714         }
2715       }
2716     }
2717   }
2718
2719   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2720       VT.getSizeInBits() <= 64) {
2721     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2722       APInt ADDC = ADDI->getAPIntValue();
2723       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2724         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2725         // immediate for an add, but it is legal if its top c2 bits are set,
2726         // transform the ADD so the immediate doesn't need to be materialized
2727         // in a register.
2728         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2729           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2730                                              SRLI->getZExtValue());
2731           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2732             ADDC |= Mask;
2733             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2734               SDValue NewAdd =
2735                 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2736                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2737               CombineTo(N0.getNode(), NewAdd);
2738               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2739             }
2740           }
2741         }
2742       }
2743     }
2744   }
2745       
2746
2747   return SDValue();
2748 }
2749
2750 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2751 ///
2752 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2753                                         bool DemandHighBits) {
2754   if (!LegalOperations)
2755     return SDValue();
2756
2757   EVT VT = N->getValueType(0);
2758   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2759     return SDValue();
2760   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2761     return SDValue();
2762
2763   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2764   bool LookPassAnd0 = false;
2765   bool LookPassAnd1 = false;
2766   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2767       std::swap(N0, N1);
2768   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2769       std::swap(N0, N1);
2770   if (N0.getOpcode() == ISD::AND) {
2771     if (!N0.getNode()->hasOneUse())
2772       return SDValue();
2773     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2774     if (!N01C || N01C->getZExtValue() != 0xFF00)
2775       return SDValue();
2776     N0 = N0.getOperand(0);
2777     LookPassAnd0 = true;
2778   }
2779
2780   if (N1.getOpcode() == ISD::AND) {
2781     if (!N1.getNode()->hasOneUse())
2782       return SDValue();
2783     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2784     if (!N11C || N11C->getZExtValue() != 0xFF)
2785       return SDValue();
2786     N1 = N1.getOperand(0);
2787     LookPassAnd1 = true;
2788   }
2789
2790   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2791     std::swap(N0, N1);
2792   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2793     return SDValue();
2794   if (!N0.getNode()->hasOneUse() ||
2795       !N1.getNode()->hasOneUse())
2796     return SDValue();
2797
2798   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2799   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2800   if (!N01C || !N11C)
2801     return SDValue();
2802   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2803     return SDValue();
2804
2805   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2806   SDValue N00 = N0->getOperand(0);
2807   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2808     if (!N00.getNode()->hasOneUse())
2809       return SDValue();
2810     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2811     if (!N001C || N001C->getZExtValue() != 0xFF)
2812       return SDValue();
2813     N00 = N00.getOperand(0);
2814     LookPassAnd0 = true;
2815   }
2816
2817   SDValue N10 = N1->getOperand(0);
2818   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2819     if (!N10.getNode()->hasOneUse())
2820       return SDValue();
2821     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2822     if (!N101C || N101C->getZExtValue() != 0xFF00)
2823       return SDValue();
2824     N10 = N10.getOperand(0);
2825     LookPassAnd1 = true;
2826   }
2827
2828   if (N00 != N10)
2829     return SDValue();
2830
2831   // Make sure everything beyond the low halfword is zero since the SRL 16
2832   // will clear the top bits.
2833   unsigned OpSizeInBits = VT.getSizeInBits();
2834   if (DemandHighBits && OpSizeInBits > 16 &&
2835       (!LookPassAnd0 || !LookPassAnd1) &&
2836       !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2837     return SDValue();
2838
2839   SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2840   if (OpSizeInBits > 16)
2841     Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2842                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2843   return Res;
2844 }
2845
2846 /// isBSwapHWordElement - Return true if the specified node is an element
2847 /// that makes up a 32-bit packed halfword byteswap. i.e.
2848 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2849 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2850   if (!N.getNode()->hasOneUse())
2851     return false;
2852
2853   unsigned Opc = N.getOpcode();
2854   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2855     return false;
2856
2857   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2858   if (!N1C)
2859     return false;
2860
2861   unsigned Num;
2862   switch (N1C->getZExtValue()) {
2863   default:
2864     return false;
2865   case 0xFF:       Num = 0; break;
2866   case 0xFF00:     Num = 1; break;
2867   case 0xFF0000:   Num = 2; break;
2868   case 0xFF000000: Num = 3; break;
2869   }
2870
2871   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2872   SDValue N0 = N.getOperand(0);
2873   if (Opc == ISD::AND) {
2874     if (Num == 0 || Num == 2) {
2875       // (x >> 8) & 0xff
2876       // (x >> 8) & 0xff0000
2877       if (N0.getOpcode() != ISD::SRL)
2878         return false;
2879       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2880       if (!C || C->getZExtValue() != 8)
2881         return false;
2882     } else {
2883       // (x << 8) & 0xff00
2884       // (x << 8) & 0xff000000
2885       if (N0.getOpcode() != ISD::SHL)
2886         return false;
2887       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2888       if (!C || C->getZExtValue() != 8)
2889         return false;
2890     }
2891   } else if (Opc == ISD::SHL) {
2892     // (x & 0xff) << 8
2893     // (x & 0xff0000) << 8
2894     if (Num != 0 && Num != 2)
2895       return false;
2896     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2897     if (!C || C->getZExtValue() != 8)
2898       return false;
2899   } else { // Opc == ISD::SRL
2900     // (x & 0xff00) >> 8
2901     // (x & 0xff000000) >> 8
2902     if (Num != 1 && Num != 3)
2903       return false;
2904     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2905     if (!C || C->getZExtValue() != 8)
2906       return false;
2907   }
2908
2909   if (Parts[Num])
2910     return false;
2911
2912   Parts[Num] = N0.getOperand(0).getNode();
2913   return true;
2914 }
2915
2916 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2917 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2918 /// => (rotl (bswap x), 16)
2919 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2920   if (!LegalOperations)
2921     return SDValue();
2922
2923   EVT VT = N->getValueType(0);
2924   if (VT != MVT::i32)
2925     return SDValue();
2926   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2927     return SDValue();
2928
2929   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2930   // Look for either
2931   // (or (or (and), (and)), (or (and), (and)))
2932   // (or (or (or (and), (and)), (and)), (and))
2933   if (N0.getOpcode() != ISD::OR)
2934     return SDValue();
2935   SDValue N00 = N0.getOperand(0);
2936   SDValue N01 = N0.getOperand(1);
2937
2938   if (N1.getOpcode() == ISD::OR) {
2939     // (or (or (and), (and)), (or (and), (and)))
2940     SDValue N000 = N00.getOperand(0);
2941     if (!isBSwapHWordElement(N000, Parts))
2942       return SDValue();
2943
2944     SDValue N001 = N00.getOperand(1);
2945     if (!isBSwapHWordElement(N001, Parts))
2946       return SDValue();
2947     SDValue N010 = N01.getOperand(0);
2948     if (!isBSwapHWordElement(N010, Parts))
2949       return SDValue();
2950     SDValue N011 = N01.getOperand(1);
2951     if (!isBSwapHWordElement(N011, Parts))
2952       return SDValue();
2953   } else {
2954     // (or (or (or (and), (and)), (and)), (and))
2955     if (!isBSwapHWordElement(N1, Parts))
2956       return SDValue();
2957     if (!isBSwapHWordElement(N01, Parts))
2958       return SDValue();
2959     if (N00.getOpcode() != ISD::OR)
2960       return SDValue();
2961     SDValue N000 = N00.getOperand(0);
2962     if (!isBSwapHWordElement(N000, Parts))
2963       return SDValue();
2964     SDValue N001 = N00.getOperand(1);
2965     if (!isBSwapHWordElement(N001, Parts))
2966       return SDValue();
2967   }
2968
2969   // Make sure the parts are all coming from the same node.
2970   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2971     return SDValue();
2972
2973   SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
2974                               SDValue(Parts[0],0));
2975
2976   // Result of the bswap should be rotated by 16. If it's not legal, than
2977   // do  (x << 16) | (x >> 16).
2978   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
2979   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
2980     return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
2981   else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
2982     return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
2983   return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
2984                      DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
2985                      DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
2986 }
2987
2988 SDValue DAGCombiner::visitOR(SDNode *N) {
2989   SDValue N0 = N->getOperand(0);
2990   SDValue N1 = N->getOperand(1);
2991   SDValue LL, LR, RL, RR, CC0, CC1;
2992   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2993   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2994   EVT VT = N1.getValueType();
2995
2996   // fold vector ops
2997   if (VT.isVector()) {
2998     SDValue FoldedVOp = SimplifyVBinOp(N);
2999     if (FoldedVOp.getNode()) return FoldedVOp;
3000   }
3001
3002   // fold (or x, undef) -> -1
3003   if (!LegalOperations &&
3004       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3005     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3006     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3007   }
3008   // fold (or c1, c2) -> c1|c2
3009   if (N0C && N1C)
3010     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3011   // canonicalize constant to RHS
3012   if (N0C && !N1C)
3013     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3014   // fold (or x, 0) -> x
3015   if (N1C && N1C->isNullValue())
3016     return N0;
3017   // fold (or x, -1) -> -1
3018   if (N1C && N1C->isAllOnesValue())
3019     return N1;
3020   // fold (or x, c) -> c iff (x & ~c) == 0
3021   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3022     return N1;
3023
3024   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3025   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3026   if (BSwap.getNode() != 0)
3027     return BSwap;
3028   BSwap = MatchBSwapHWordLow(N, N0, N1);
3029   if (BSwap.getNode() != 0)
3030     return BSwap;
3031
3032   // reassociate or
3033   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3034   if (ROR.getNode() != 0)
3035     return ROR;
3036   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3037   // iff (c1 & c2) == 0.
3038   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3039              isa<ConstantSDNode>(N0.getOperand(1))) {
3040     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3041     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3042       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3043                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3044                                      N0.getOperand(0), N1),
3045                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3046   }
3047   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3048   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3049     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3050     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3051
3052     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3053         LL.getValueType().isInteger()) {
3054       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3055       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3056       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3057           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3058         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3059                                      LR.getValueType(), LL, RL);
3060         AddToWorkList(ORNode.getNode());
3061         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3062       }
3063       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3064       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3065       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3066           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3067         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3068                                       LR.getValueType(), LL, RL);
3069         AddToWorkList(ANDNode.getNode());
3070         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3071       }
3072     }
3073     // canonicalize equivalent to ll == rl
3074     if (LL == RR && LR == RL) {
3075       Op1 = ISD::getSetCCSwappedOperands(Op1);
3076       std::swap(RL, RR);
3077     }
3078     if (LL == RL && LR == RR) {
3079       bool isInteger = LL.getValueType().isInteger();
3080       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3081       if (Result != ISD::SETCC_INVALID &&
3082           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
3083         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3084                             LL, LR, Result);
3085     }
3086   }
3087
3088   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3089   if (N0.getOpcode() == N1.getOpcode()) {
3090     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3091     if (Tmp.getNode()) return Tmp;
3092   }
3093
3094   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3095   if (N0.getOpcode() == ISD::AND &&
3096       N1.getOpcode() == ISD::AND &&
3097       N0.getOperand(1).getOpcode() == ISD::Constant &&
3098       N1.getOperand(1).getOpcode() == ISD::Constant &&
3099       // Don't increase # computations.
3100       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3101     // We can only do this xform if we know that bits from X that are set in C2
3102     // but not in C1 are already zero.  Likewise for Y.
3103     const APInt &LHSMask =
3104       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3105     const APInt &RHSMask =
3106       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3107
3108     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3109         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3110       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3111                               N0.getOperand(0), N1.getOperand(0));
3112       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3113                          DAG.getConstant(LHSMask | RHSMask, VT));
3114     }
3115   }
3116
3117   // See if this is some rotate idiom.
3118   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3119     return SDValue(Rot, 0);
3120
3121   // Simplify the operands using demanded-bits information.
3122   if (!VT.isVector() &&
3123       SimplifyDemandedBits(SDValue(N, 0)))
3124     return SDValue(N, 0);
3125
3126   return SDValue();
3127 }
3128
3129 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3130 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3131   if (Op.getOpcode() == ISD::AND) {
3132     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3133       Mask = Op.getOperand(1);
3134       Op = Op.getOperand(0);
3135     } else {
3136       return false;
3137     }
3138   }
3139
3140   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3141     Shift = Op;
3142     return true;
3143   }
3144
3145   return false;
3146 }
3147
3148 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3149 // idioms for rotate, and if the target supports rotation instructions, generate
3150 // a rot[lr].
3151 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3152   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3153   EVT VT = LHS.getValueType();
3154   if (!TLI.isTypeLegal(VT)) return 0;
3155
3156   // The target must have at least one rotate flavor.
3157   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3158   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3159   if (!HasROTL && !HasROTR) return 0;
3160
3161   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3162   SDValue LHSShift;   // The shift.
3163   SDValue LHSMask;    // AND value if any.
3164   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3165     return 0; // Not part of a rotate.
3166
3167   SDValue RHSShift;   // The shift.
3168   SDValue RHSMask;    // AND value if any.
3169   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3170     return 0; // Not part of a rotate.
3171
3172   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3173     return 0;   // Not shifting the same value.
3174
3175   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3176     return 0;   // Shifts must disagree.
3177
3178   // Canonicalize shl to left side in a shl/srl pair.
3179   if (RHSShift.getOpcode() == ISD::SHL) {
3180     std::swap(LHS, RHS);
3181     std::swap(LHSShift, RHSShift);
3182     std::swap(LHSMask , RHSMask );
3183   }
3184
3185   unsigned OpSizeInBits = VT.getSizeInBits();
3186   SDValue LHSShiftArg = LHSShift.getOperand(0);
3187   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3188   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3189
3190   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3191   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3192   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3193       RHSShiftAmt.getOpcode() == ISD::Constant) {
3194     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3195     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3196     if ((LShVal + RShVal) != OpSizeInBits)
3197       return 0;
3198
3199     SDValue Rot;
3200     if (HasROTL)
3201       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
3202     else
3203       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
3204
3205     // If there is an AND of either shifted operand, apply it to the result.
3206     if (LHSMask.getNode() || RHSMask.getNode()) {
3207       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3208
3209       if (LHSMask.getNode()) {
3210         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3211         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3212       }
3213       if (RHSMask.getNode()) {
3214         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3215         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3216       }
3217
3218       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3219     }
3220
3221     return Rot.getNode();
3222   }
3223
3224   // If there is a mask here, and we have a variable shift, we can't be sure
3225   // that we're masking out the right stuff.
3226   if (LHSMask.getNode() || RHSMask.getNode())
3227     return 0;
3228
3229   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3230   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3231   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3232       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3233     if (ConstantSDNode *SUBC =
3234           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3235       if (SUBC->getAPIntValue() == OpSizeInBits) {
3236         if (HasROTL)
3237           return DAG.getNode(ISD::ROTL, DL, VT,
3238                              LHSShiftArg, LHSShiftAmt).getNode();
3239         else
3240           return DAG.getNode(ISD::ROTR, DL, VT,
3241                              LHSShiftArg, RHSShiftAmt).getNode();
3242       }
3243     }
3244   }
3245
3246   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3247   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3248   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3249       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3250     if (ConstantSDNode *SUBC =
3251           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3252       if (SUBC->getAPIntValue() == OpSizeInBits) {
3253         if (HasROTR)
3254           return DAG.getNode(ISD::ROTR, DL, VT,
3255                              LHSShiftArg, RHSShiftAmt).getNode();
3256         else
3257           return DAG.getNode(ISD::ROTL, DL, VT,
3258                              LHSShiftArg, LHSShiftAmt).getNode();
3259       }
3260     }
3261   }
3262
3263   // Look for sign/zext/any-extended or truncate cases:
3264   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3265        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3266        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3267        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3268       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3269        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3270        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3271        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3272     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3273     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3274     if (RExtOp0.getOpcode() == ISD::SUB &&
3275         RExtOp0.getOperand(1) == LExtOp0) {
3276       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3277       //   (rotl x, y)
3278       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3279       //   (rotr x, (sub 32, y))
3280       if (ConstantSDNode *SUBC =
3281             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3282         if (SUBC->getAPIntValue() == OpSizeInBits) {
3283           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3284                              LHSShiftArg,
3285                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3286         }
3287       }
3288     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3289                RExtOp0 == LExtOp0.getOperand(1)) {
3290       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3291       //   (rotr x, y)
3292       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3293       //   (rotl x, (sub 32, y))
3294       if (ConstantSDNode *SUBC =
3295             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3296         if (SUBC->getAPIntValue() == OpSizeInBits) {
3297           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3298                              LHSShiftArg,
3299                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3300         }
3301       }
3302     }
3303   }
3304
3305   return 0;
3306 }
3307
3308 SDValue DAGCombiner::visitXOR(SDNode *N) {
3309   SDValue N0 = N->getOperand(0);
3310   SDValue N1 = N->getOperand(1);
3311   SDValue LHS, RHS, CC;
3312   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3313   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3314   EVT VT = N0.getValueType();
3315
3316   // fold vector ops
3317   if (VT.isVector()) {
3318     SDValue FoldedVOp = SimplifyVBinOp(N);
3319     if (FoldedVOp.getNode()) return FoldedVOp;
3320   }
3321
3322   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3323   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3324     return DAG.getConstant(0, VT);
3325   // fold (xor x, undef) -> undef
3326   if (N0.getOpcode() == ISD::UNDEF)
3327     return N0;
3328   if (N1.getOpcode() == ISD::UNDEF)
3329     return N1;
3330   // fold (xor c1, c2) -> c1^c2
3331   if (N0C && N1C)
3332     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3333   // canonicalize constant to RHS
3334   if (N0C && !N1C)
3335     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3336   // fold (xor x, 0) -> x
3337   if (N1C && N1C->isNullValue())
3338     return N0;
3339   // reassociate xor
3340   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3341   if (RXOR.getNode() != 0)
3342     return RXOR;
3343
3344   // fold !(x cc y) -> (x !cc y)
3345   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3346     bool isInt = LHS.getValueType().isInteger();
3347     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3348                                                isInt);
3349
3350     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3351       switch (N0.getOpcode()) {
3352       default:
3353         llvm_unreachable("Unhandled SetCC Equivalent!");
3354       case ISD::SETCC:
3355         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3356       case ISD::SELECT_CC:
3357         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3358                                N0.getOperand(3), NotCC);
3359       }
3360     }
3361   }
3362
3363   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3364   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3365       N0.getNode()->hasOneUse() &&
3366       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3367     SDValue V = N0.getOperand(0);
3368     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3369                     DAG.getConstant(1, V.getValueType()));
3370     AddToWorkList(V.getNode());
3371     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3372   }
3373
3374   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3375   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3376       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3377     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3378     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3379       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3380       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3381       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3382       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3383       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3384     }
3385   }
3386   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3387   if (N1C && N1C->isAllOnesValue() &&
3388       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3389     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3390     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3391       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3392       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3393       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3394       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3395       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3396     }
3397   }
3398   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3399   if (N1C && N0.getOpcode() == ISD::XOR) {
3400     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3401     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3402     if (N00C)
3403       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3404                          DAG.getConstant(N1C->getAPIntValue() ^
3405                                          N00C->getAPIntValue(), VT));
3406     if (N01C)
3407       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3408                          DAG.getConstant(N1C->getAPIntValue() ^
3409                                          N01C->getAPIntValue(), VT));
3410   }
3411   // fold (xor x, x) -> 0
3412   if (N0 == N1)
3413     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3414
3415   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3416   if (N0.getOpcode() == N1.getOpcode()) {
3417     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3418     if (Tmp.getNode()) return Tmp;
3419   }
3420
3421   // Simplify the expression using non-local knowledge.
3422   if (!VT.isVector() &&
3423       SimplifyDemandedBits(SDValue(N, 0)))
3424     return SDValue(N, 0);
3425
3426   return SDValue();
3427 }
3428
3429 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3430 /// the shift amount is a constant.
3431 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3432   SDNode *LHS = N->getOperand(0).getNode();
3433   if (!LHS->hasOneUse()) return SDValue();
3434
3435   // We want to pull some binops through shifts, so that we have (and (shift))
3436   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3437   // thing happens with address calculations, so it's important to canonicalize
3438   // it.
3439   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3440
3441   switch (LHS->getOpcode()) {
3442   default: return SDValue();
3443   case ISD::OR:
3444   case ISD::XOR:
3445     HighBitSet = false; // We can only transform sra if the high bit is clear.
3446     break;
3447   case ISD::AND:
3448     HighBitSet = true;  // We can only transform sra if the high bit is set.
3449     break;
3450   case ISD::ADD:
3451     if (N->getOpcode() != ISD::SHL)
3452       return SDValue(); // only shl(add) not sr[al](add).
3453     HighBitSet = false; // We can only transform sra if the high bit is clear.
3454     break;
3455   }
3456
3457   // We require the RHS of the binop to be a constant as well.
3458   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3459   if (!BinOpCst) return SDValue();
3460
3461   // FIXME: disable this unless the input to the binop is a shift by a constant.
3462   // If it is not a shift, it pessimizes some common cases like:
3463   //
3464   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3465   //    int bar(int *X, int i) { return X[i & 255]; }
3466   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3467   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3468        BinOpLHSVal->getOpcode() != ISD::SRA &&
3469        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3470       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3471     return SDValue();
3472
3473   EVT VT = N->getValueType(0);
3474
3475   // If this is a signed shift right, and the high bit is modified by the
3476   // logical operation, do not perform the transformation. The highBitSet
3477   // boolean indicates the value of the high bit of the constant which would
3478   // cause it to be modified for this operation.
3479   if (N->getOpcode() == ISD::SRA) {
3480     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3481     if (BinOpRHSSignSet != HighBitSet)
3482       return SDValue();
3483   }
3484
3485   // Fold the constants, shifting the binop RHS by the shift amount.
3486   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3487                                N->getValueType(0),
3488                                LHS->getOperand(1), N->getOperand(1));
3489
3490   // Create the new shift.
3491   SDValue NewShift = DAG.getNode(N->getOpcode(),
3492                                  LHS->getOperand(0).getDebugLoc(),
3493                                  VT, LHS->getOperand(0), N->getOperand(1));
3494
3495   // Create the new binop.
3496   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3497 }
3498
3499 SDValue DAGCombiner::visitSHL(SDNode *N) {
3500   SDValue N0 = N->getOperand(0);
3501   SDValue N1 = N->getOperand(1);
3502   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3503   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3504   EVT VT = N0.getValueType();
3505   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3506
3507   // fold (shl c1, c2) -> c1<<c2
3508   if (N0C && N1C)
3509     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3510   // fold (shl 0, x) -> 0
3511   if (N0C && N0C->isNullValue())
3512     return N0;
3513   // fold (shl x, c >= size(x)) -> undef
3514   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3515     return DAG.getUNDEF(VT);
3516   // fold (shl x, 0) -> x
3517   if (N1C && N1C->isNullValue())
3518     return N0;
3519   // fold (shl undef, x) -> 0
3520   if (N0.getOpcode() == ISD::UNDEF)
3521     return DAG.getConstant(0, VT);
3522   // if (shl x, c) is known to be zero, return 0
3523   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3524                             APInt::getAllOnesValue(OpSizeInBits)))
3525     return DAG.getConstant(0, VT);
3526   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3527   if (N1.getOpcode() == ISD::TRUNCATE &&
3528       N1.getOperand(0).getOpcode() == ISD::AND &&
3529       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3530     SDValue N101 = N1.getOperand(0).getOperand(1);
3531     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3532       EVT TruncVT = N1.getValueType();
3533       SDValue N100 = N1.getOperand(0).getOperand(0);
3534       APInt TruncC = N101C->getAPIntValue();
3535       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3536       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3537                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3538                                      DAG.getNode(ISD::TRUNCATE,
3539                                                  N->getDebugLoc(),
3540                                                  TruncVT, N100),
3541                                      DAG.getConstant(TruncC, TruncVT)));
3542     }
3543   }
3544
3545   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3546     return SDValue(N, 0);
3547
3548   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3549   if (N1C && N0.getOpcode() == ISD::SHL &&
3550       N0.getOperand(1).getOpcode() == ISD::Constant) {
3551     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3552     uint64_t c2 = N1C->getZExtValue();
3553     if (c1 + c2 >= OpSizeInBits)
3554       return DAG.getConstant(0, VT);
3555     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3556                        DAG.getConstant(c1 + c2, N1.getValueType()));
3557   }
3558
3559   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3560   // For this to be valid, the second form must not preserve any of the bits
3561   // that are shifted out by the inner shift in the first form.  This means
3562   // the outer shift size must be >= the number of bits added by the ext.
3563   // As a corollary, we don't care what kind of ext it is.
3564   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3565               N0.getOpcode() == ISD::ANY_EXTEND ||
3566               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3567       N0.getOperand(0).getOpcode() == ISD::SHL &&
3568       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3569     uint64_t c1 =
3570       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3571     uint64_t c2 = N1C->getZExtValue();
3572     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3573     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3574     if (c2 >= OpSizeInBits - InnerShiftSize) {
3575       if (c1 + c2 >= OpSizeInBits)
3576         return DAG.getConstant(0, VT);
3577       return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3578                          DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3579                                      N0.getOperand(0)->getOperand(0)),
3580                          DAG.getConstant(c1 + c2, N1.getValueType()));
3581     }
3582   }
3583
3584   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3585   //                               (and (srl x, (sub c1, c2), MASK)
3586   // Only fold this if the inner shift has no other uses -- if it does, folding
3587   // this will increase the total number of instructions.
3588   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3589       N0.getOperand(1).getOpcode() == ISD::Constant) {
3590     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3591     if (c1 < VT.getSizeInBits()) {
3592       uint64_t c2 = N1C->getZExtValue();
3593       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3594                                          VT.getSizeInBits() - c1);
3595       SDValue Shift;
3596       if (c2 > c1) {
3597         Mask = Mask.shl(c2-c1);
3598         Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3599                             DAG.getConstant(c2-c1, N1.getValueType()));
3600       } else {
3601         Mask = Mask.lshr(c1-c2);
3602         Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3603                             DAG.getConstant(c1-c2, N1.getValueType()));
3604       }
3605       return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3606                          DAG.getConstant(Mask, VT));
3607     }
3608   }
3609   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3610   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3611     SDValue HiBitsMask =
3612       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3613                                             VT.getSizeInBits() -
3614                                               N1C->getZExtValue()),
3615                       VT);
3616     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3617                        HiBitsMask);
3618   }
3619
3620   if (N1C) {
3621     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3622     if (NewSHL.getNode())
3623       return NewSHL;
3624   }
3625
3626   return SDValue();
3627 }
3628
3629 SDValue DAGCombiner::visitSRA(SDNode *N) {
3630   SDValue N0 = N->getOperand(0);
3631   SDValue N1 = N->getOperand(1);
3632   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3633   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3634   EVT VT = N0.getValueType();
3635   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3636
3637   // fold (sra c1, c2) -> (sra c1, c2)
3638   if (N0C && N1C)
3639     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3640   // fold (sra 0, x) -> 0
3641   if (N0C && N0C->isNullValue())
3642     return N0;
3643   // fold (sra -1, x) -> -1
3644   if (N0C && N0C->isAllOnesValue())
3645     return N0;
3646   // fold (sra x, (setge c, size(x))) -> undef
3647   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3648     return DAG.getUNDEF(VT);
3649   // fold (sra x, 0) -> x
3650   if (N1C && N1C->isNullValue())
3651     return N0;
3652   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3653   // sext_inreg.
3654   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3655     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3656     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3657     if (VT.isVector())
3658       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3659                                ExtVT, VT.getVectorNumElements());
3660     if ((!LegalOperations ||
3661          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3662       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3663                          N0.getOperand(0), DAG.getValueType(ExtVT));
3664   }
3665
3666   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3667   if (N1C && N0.getOpcode() == ISD::SRA) {
3668     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3669       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3670       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3671       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3672                          DAG.getConstant(Sum, N1C->getValueType(0)));
3673     }
3674   }
3675
3676   // fold (sra (shl X, m), (sub result_size, n))
3677   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3678   // result_size - n != m.
3679   // If truncate is free for the target sext(shl) is likely to result in better
3680   // code.
3681   if (N0.getOpcode() == ISD::SHL) {
3682     // Get the two constanst of the shifts, CN0 = m, CN = n.
3683     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3684     if (N01C && N1C) {
3685       // Determine what the truncate's result bitsize and type would be.
3686       EVT TruncVT =
3687         EVT::getIntegerVT(*DAG.getContext(),
3688                           OpSizeInBits - N1C->getZExtValue());
3689       // Determine the residual right-shift amount.
3690       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3691
3692       // If the shift is not a no-op (in which case this should be just a sign
3693       // extend already), the truncated to type is legal, sign_extend is legal
3694       // on that type, and the truncate to that type is both legal and free,
3695       // perform the transform.
3696       if ((ShiftAmt > 0) &&
3697           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3698           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3699           TLI.isTruncateFree(VT, TruncVT)) {
3700
3701           SDValue Amt = DAG.getConstant(ShiftAmt,
3702               getShiftAmountTy(N0.getOperand(0).getValueType()));
3703           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3704                                       N0.getOperand(0), Amt);
3705           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3706                                       Shift);
3707           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3708                              N->getValueType(0), Trunc);
3709       }
3710     }
3711   }
3712
3713   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3714   if (N1.getOpcode() == ISD::TRUNCATE &&
3715       N1.getOperand(0).getOpcode() == ISD::AND &&
3716       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3717     SDValue N101 = N1.getOperand(0).getOperand(1);
3718     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3719       EVT TruncVT = N1.getValueType();
3720       SDValue N100 = N1.getOperand(0).getOperand(0);
3721       APInt TruncC = N101C->getAPIntValue();
3722       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3723       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3724                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3725                                      TruncVT,
3726                                      DAG.getNode(ISD::TRUNCATE,
3727                                                  N->getDebugLoc(),
3728                                                  TruncVT, N100),
3729                                      DAG.getConstant(TruncC, TruncVT)));
3730     }
3731   }
3732
3733   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3734   //      if c1 is equal to the number of bits the trunc removes
3735   if (N0.getOpcode() == ISD::TRUNCATE &&
3736       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3737        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3738       N0.getOperand(0).hasOneUse() &&
3739       N0.getOperand(0).getOperand(1).hasOneUse() &&
3740       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3741     EVT LargeVT = N0.getOperand(0).getValueType();
3742     ConstantSDNode *LargeShiftAmt =
3743       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3744
3745     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3746         LargeShiftAmt->getZExtValue()) {
3747       SDValue Amt =
3748         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3749               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3750       SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3751                                 N0.getOperand(0).getOperand(0), Amt);
3752       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3753     }
3754   }
3755
3756   // Simplify, based on bits shifted out of the LHS.
3757   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3758     return SDValue(N, 0);
3759
3760
3761   // If the sign bit is known to be zero, switch this to a SRL.
3762   if (DAG.SignBitIsZero(N0))
3763     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3764
3765   if (N1C) {
3766     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3767     if (NewSRA.getNode())
3768       return NewSRA;
3769   }
3770
3771   return SDValue();
3772 }
3773
3774 SDValue DAGCombiner::visitSRL(SDNode *N) {
3775   SDValue N0 = N->getOperand(0);
3776   SDValue N1 = N->getOperand(1);
3777   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3778   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3779   EVT VT = N0.getValueType();
3780   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3781
3782   // fold (srl c1, c2) -> c1 >>u c2
3783   if (N0C && N1C)
3784     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3785   // fold (srl 0, x) -> 0
3786   if (N0C && N0C->isNullValue())
3787     return N0;
3788   // fold (srl x, c >= size(x)) -> undef
3789   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3790     return DAG.getUNDEF(VT);
3791   // fold (srl x, 0) -> x
3792   if (N1C && N1C->isNullValue())
3793     return N0;
3794   // if (srl x, c) is known to be zero, return 0
3795   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3796                                    APInt::getAllOnesValue(OpSizeInBits)))
3797     return DAG.getConstant(0, VT);
3798
3799   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3800   if (N1C && N0.getOpcode() == ISD::SRL &&
3801       N0.getOperand(1).getOpcode() == ISD::Constant) {
3802     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3803     uint64_t c2 = N1C->getZExtValue();
3804     if (c1 + c2 >= OpSizeInBits)
3805       return DAG.getConstant(0, VT);
3806     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3807                        DAG.getConstant(c1 + c2, N1.getValueType()));
3808   }
3809
3810   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3811   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3812       N0.getOperand(0).getOpcode() == ISD::SRL &&
3813       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3814     uint64_t c1 =
3815       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3816     uint64_t c2 = N1C->getZExtValue();
3817     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3818     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3819     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3820     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3821     if (c1 + OpSizeInBits == InnerShiftSize) {
3822       if (c1 + c2 >= InnerShiftSize)
3823         return DAG.getConstant(0, VT);
3824       return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3825                          DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3826                                      N0.getOperand(0)->getOperand(0),
3827                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3828     }
3829   }
3830
3831   // fold (srl (shl x, c), c) -> (and x, cst2)
3832   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3833       N0.getValueSizeInBits() <= 64) {
3834     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3835     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3836                        DAG.getConstant(~0ULL >> ShAmt, VT));
3837   }
3838
3839
3840   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3841   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3842     // Shifting in all undef bits?
3843     EVT SmallVT = N0.getOperand(0).getValueType();
3844     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3845       return DAG.getUNDEF(VT);
3846
3847     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3848       uint64_t ShiftAmt = N1C->getZExtValue();
3849       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3850                                        N0.getOperand(0),
3851                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3852       AddToWorkList(SmallShift.getNode());
3853       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3854     }
3855   }
3856
3857   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3858   // bit, which is unmodified by sra.
3859   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3860     if (N0.getOpcode() == ISD::SRA)
3861       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3862   }
3863
3864   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3865   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3866       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3867     APInt KnownZero, KnownOne;
3868     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3869
3870     // If any of the input bits are KnownOne, then the input couldn't be all
3871     // zeros, thus the result of the srl will always be zero.
3872     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3873
3874     // If all of the bits input the to ctlz node are known to be zero, then
3875     // the result of the ctlz is "32" and the result of the shift is one.
3876     APInt UnknownBits = ~KnownZero;
3877     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3878
3879     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3880     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3881       // Okay, we know that only that the single bit specified by UnknownBits
3882       // could be set on input to the CTLZ node. If this bit is set, the SRL
3883       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3884       // to an SRL/XOR pair, which is likely to simplify more.
3885       unsigned ShAmt = UnknownBits.countTrailingZeros();
3886       SDValue Op = N0.getOperand(0);
3887
3888       if (ShAmt) {
3889         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3890                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3891         AddToWorkList(Op.getNode());
3892       }
3893
3894       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3895                          Op, DAG.getConstant(1, VT));
3896     }
3897   }
3898
3899   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3900   if (N1.getOpcode() == ISD::TRUNCATE &&
3901       N1.getOperand(0).getOpcode() == ISD::AND &&
3902       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3903     SDValue N101 = N1.getOperand(0).getOperand(1);
3904     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3905       EVT TruncVT = N1.getValueType();
3906       SDValue N100 = N1.getOperand(0).getOperand(0);
3907       APInt TruncC = N101C->getAPIntValue();
3908       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3909       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3910                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3911                                      TruncVT,
3912                                      DAG.getNode(ISD::TRUNCATE,
3913                                                  N->getDebugLoc(),
3914                                                  TruncVT, N100),
3915                                      DAG.getConstant(TruncC, TruncVT)));
3916     }
3917   }
3918
3919   // fold operands of srl based on knowledge that the low bits are not
3920   // demanded.
3921   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3922     return SDValue(N, 0);
3923
3924   if (N1C) {
3925     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3926     if (NewSRL.getNode())
3927       return NewSRL;
3928   }
3929
3930   // Attempt to convert a srl of a load into a narrower zero-extending load.
3931   SDValue NarrowLoad = ReduceLoadWidth(N);
3932   if (NarrowLoad.getNode())
3933     return NarrowLoad;
3934
3935   // Here is a common situation. We want to optimize:
3936   //
3937   //   %a = ...
3938   //   %b = and i32 %a, 2
3939   //   %c = srl i32 %b, 1
3940   //   brcond i32 %c ...
3941   //
3942   // into
3943   //
3944   //   %a = ...
3945   //   %b = and %a, 2
3946   //   %c = setcc eq %b, 0
3947   //   brcond %c ...
3948   //
3949   // However when after the source operand of SRL is optimized into AND, the SRL
3950   // itself may not be optimized further. Look for it and add the BRCOND into
3951   // the worklist.
3952   if (N->hasOneUse()) {
3953     SDNode *Use = *N->use_begin();
3954     if (Use->getOpcode() == ISD::BRCOND)
3955       AddToWorkList(Use);
3956     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3957       // Also look pass the truncate.
3958       Use = *Use->use_begin();
3959       if (Use->getOpcode() == ISD::BRCOND)
3960         AddToWorkList(Use);
3961     }
3962   }
3963
3964   return SDValue();
3965 }
3966
3967 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3968   SDValue N0 = N->getOperand(0);
3969   EVT VT = N->getValueType(0);
3970
3971   // fold (ctlz c1) -> c2
3972   if (isa<ConstantSDNode>(N0))
3973     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3974   return SDValue();
3975 }
3976
3977 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
3978   SDValue N0 = N->getOperand(0);
3979   EVT VT = N->getValueType(0);
3980
3981   // fold (ctlz_zero_undef c1) -> c2
3982   if (isa<ConstantSDNode>(N0))
3983     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3984   return SDValue();
3985 }
3986
3987 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3988   SDValue N0 = N->getOperand(0);
3989   EVT VT = N->getValueType(0);
3990
3991   // fold (cttz c1) -> c2
3992   if (isa<ConstantSDNode>(N0))
3993     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3994   return SDValue();
3995 }
3996
3997 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
3998   SDValue N0 = N->getOperand(0);
3999   EVT VT = N->getValueType(0);
4000
4001   // fold (cttz_zero_undef c1) -> c2
4002   if (isa<ConstantSDNode>(N0))
4003     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4004   return SDValue();
4005 }
4006
4007 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4008   SDValue N0 = N->getOperand(0);
4009   EVT VT = N->getValueType(0);
4010
4011   // fold (ctpop c1) -> c2
4012   if (isa<ConstantSDNode>(N0))
4013     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4014   return SDValue();
4015 }
4016
4017 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4018   SDValue N0 = N->getOperand(0);
4019   SDValue N1 = N->getOperand(1);
4020   SDValue N2 = N->getOperand(2);
4021   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4022   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4023   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4024   EVT VT = N->getValueType(0);
4025   EVT VT0 = N0.getValueType();
4026
4027   // fold (select C, X, X) -> X
4028   if (N1 == N2)
4029     return N1;
4030   // fold (select true, X, Y) -> X
4031   if (N0C && !N0C->isNullValue())
4032     return N1;
4033   // fold (select false, X, Y) -> Y
4034   if (N0C && N0C->isNullValue())
4035     return N2;
4036   // fold (select C, 1, X) -> (or C, X)
4037   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4038     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4039   // fold (select C, 0, 1) -> (xor C, 1)
4040   if (VT.isInteger() &&
4041       (VT0 == MVT::i1 ||
4042        (VT0.isInteger() &&
4043         TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) &&
4044       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4045     SDValue XORNode;
4046     if (VT == VT0)
4047       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4048                          N0, DAG.getConstant(1, VT0));
4049     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4050                           N0, DAG.getConstant(1, VT0));
4051     AddToWorkList(XORNode.getNode());
4052     if (VT.bitsGT(VT0))
4053       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4054     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4055   }
4056   // fold (select C, 0, X) -> (and (not C), X)
4057   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4058     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4059     AddToWorkList(NOTNode.getNode());
4060     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4061   }
4062   // fold (select C, X, 1) -> (or (not C), X)
4063   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4064     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4065     AddToWorkList(NOTNode.getNode());
4066     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4067   }
4068   // fold (select C, X, 0) -> (and C, X)
4069   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4070     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4071   // fold (select X, X, Y) -> (or X, Y)
4072   // fold (select X, 1, Y) -> (or X, Y)
4073   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4074     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4075   // fold (select X, Y, X) -> (and X, Y)
4076   // fold (select X, Y, 0) -> (and X, Y)
4077   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4078     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4079
4080   // If we can fold this based on the true/false value, do so.
4081   if (SimplifySelectOps(N, N1, N2))
4082     return SDValue(N, 0);  // Don't revisit N.
4083
4084   // fold selects based on a setcc into other things, such as min/max/abs
4085   if (N0.getOpcode() == ISD::SETCC) {
4086     // FIXME:
4087     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4088     // having to say they don't support SELECT_CC on every type the DAG knows
4089     // about, since there is no way to mark an opcode illegal at all value types
4090     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4091         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4092       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4093                          N0.getOperand(0), N0.getOperand(1),
4094                          N1, N2, N0.getOperand(2));
4095     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4096   }
4097
4098   return SDValue();
4099 }
4100
4101 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4102   SDValue N0 = N->getOperand(0);
4103   SDValue N1 = N->getOperand(1);
4104   SDValue N2 = N->getOperand(2);
4105   SDValue N3 = N->getOperand(3);
4106   SDValue N4 = N->getOperand(4);
4107   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4108
4109   // fold select_cc lhs, rhs, x, x, cc -> x
4110   if (N2 == N3)
4111     return N2;
4112
4113   // Determine if the condition we're dealing with is constant
4114   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4115                               N0, N1, CC, N->getDebugLoc(), false);
4116   if (SCC.getNode()) AddToWorkList(SCC.getNode());
4117
4118   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4119     if (!SCCC->isNullValue())
4120       return N2;    // cond always true -> true val
4121     else
4122       return N3;    // cond always false -> false val
4123   }
4124
4125   // Fold to a simpler select_cc
4126   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4127     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4128                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4129                        SCC.getOperand(2));
4130
4131   // If we can fold this based on the true/false value, do so.
4132   if (SimplifySelectOps(N, N2, N3))
4133     return SDValue(N, 0);  // Don't revisit N.
4134
4135   // fold select_cc into other things, such as min/max/abs
4136   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4137 }
4138
4139 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4140   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4141                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4142                        N->getDebugLoc());
4143 }
4144
4145 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4146 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4147 // transformation. Returns true if extension are possible and the above
4148 // mentioned transformation is profitable.
4149 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4150                                     unsigned ExtOpc,
4151                                     SmallVector<SDNode*, 4> &ExtendNodes,
4152                                     const TargetLowering &TLI) {
4153   bool HasCopyToRegUses = false;
4154   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4155   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4156                             UE = N0.getNode()->use_end();
4157        UI != UE; ++UI) {
4158     SDNode *User = *UI;
4159     if (User == N)
4160       continue;
4161     if (UI.getUse().getResNo() != N0.getResNo())
4162       continue;
4163     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4164     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4165       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4166       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4167         // Sign bits will be lost after a zext.
4168         return false;
4169       bool Add = false;
4170       for (unsigned i = 0; i != 2; ++i) {
4171         SDValue UseOp = User->getOperand(i);
4172         if (UseOp == N0)
4173           continue;
4174         if (!isa<ConstantSDNode>(UseOp))
4175           return false;
4176         Add = true;
4177       }
4178       if (Add)
4179         ExtendNodes.push_back(User);
4180       continue;
4181     }
4182     // If truncates aren't free and there are users we can't
4183     // extend, it isn't worthwhile.
4184     if (!isTruncFree)
4185       return false;
4186     // Remember if this value is live-out.
4187     if (User->getOpcode() == ISD::CopyToReg)
4188       HasCopyToRegUses = true;
4189   }
4190
4191   if (HasCopyToRegUses) {
4192     bool BothLiveOut = false;
4193     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4194          UI != UE; ++UI) {
4195       SDUse &Use = UI.getUse();
4196       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4197         BothLiveOut = true;
4198         break;
4199       }
4200     }
4201     if (BothLiveOut)
4202       // Both unextended and extended values are live out. There had better be
4203       // a good reason for the transformation.
4204       return ExtendNodes.size();
4205   }
4206   return true;
4207 }
4208
4209 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4210                                   SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4211                                   ISD::NodeType ExtType) {
4212   // Extend SetCC uses if necessary.
4213   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4214     SDNode *SetCC = SetCCs[i];
4215     SmallVector<SDValue, 4> Ops;
4216
4217     for (unsigned j = 0; j != 2; ++j) {
4218       SDValue SOp = SetCC->getOperand(j);
4219       if (SOp == Trunc)
4220         Ops.push_back(ExtLoad);
4221       else
4222         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4223     }
4224
4225     Ops.push_back(SetCC->getOperand(2));
4226     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4227                                  &Ops[0], Ops.size()));
4228   }
4229 }
4230
4231 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4232   SDValue N0 = N->getOperand(0);
4233   EVT VT = N->getValueType(0);
4234
4235   // fold (sext c1) -> c1
4236   if (isa<ConstantSDNode>(N0))
4237     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4238
4239   // fold (sext (sext x)) -> (sext x)
4240   // fold (sext (aext x)) -> (sext x)
4241   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4242     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4243                        N0.getOperand(0));
4244
4245   if (N0.getOpcode() == ISD::TRUNCATE) {
4246     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4247     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4248     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4249     if (NarrowLoad.getNode()) {
4250       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4251       if (NarrowLoad.getNode() != N0.getNode()) {
4252         CombineTo(N0.getNode(), NarrowLoad);
4253         // CombineTo deleted the truncate, if needed, but not what's under it.
4254         AddToWorkList(oye);
4255       }
4256       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4257     }
4258
4259     // See if the value being truncated is already sign extended.  If so, just
4260     // eliminate the trunc/sext pair.
4261     SDValue Op = N0.getOperand(0);
4262     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4263     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4264     unsigned DestBits = VT.getScalarType().getSizeInBits();
4265     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4266
4267     if (OpBits == DestBits) {
4268       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4269       // bits, it is already ready.
4270       if (NumSignBits > DestBits-MidBits)
4271         return Op;
4272     } else if (OpBits < DestBits) {
4273       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4274       // bits, just sext from i32.
4275       if (NumSignBits > OpBits-MidBits)
4276         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4277     } else {
4278       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4279       // bits, just truncate to i32.
4280       if (NumSignBits > OpBits-MidBits)
4281         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4282     }
4283
4284     // fold (sext (truncate x)) -> (sextinreg x).
4285     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4286                                                  N0.getValueType())) {
4287       if (OpBits < DestBits)
4288         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4289       else if (OpBits > DestBits)
4290         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4291       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4292                          DAG.getValueType(N0.getValueType()));
4293     }
4294   }
4295
4296   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4297   // None of the supported targets knows how to perform load and sign extend
4298   // on vectors in one instruction.  We only perform this transformation on
4299   // scalars.
4300   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4301       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4302        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4303     bool DoXform = true;
4304     SmallVector<SDNode*, 4> SetCCs;
4305     if (!N0.hasOneUse())
4306       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4307     if (DoXform) {
4308       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4309       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4310                                        LN0->getChain(),
4311                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4312                                        N0.getValueType(),
4313                                        LN0->isVolatile(), LN0->isNonTemporal(),
4314                                        LN0->getAlignment());
4315       CombineTo(N, ExtLoad);
4316       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4317                                   N0.getValueType(), ExtLoad);
4318       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4319       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4320                       ISD::SIGN_EXTEND);
4321       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4322     }
4323   }
4324
4325   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4326   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4327   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4328       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4329     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4330     EVT MemVT = LN0->getMemoryVT();
4331     if ((!LegalOperations && !LN0->isVolatile()) ||
4332         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4333       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4334                                        LN0->getChain(),
4335                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4336                                        MemVT,
4337                                        LN0->isVolatile(), LN0->isNonTemporal(),
4338                                        LN0->getAlignment());
4339       CombineTo(N, ExtLoad);
4340       CombineTo(N0.getNode(),
4341                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4342                             N0.getValueType(), ExtLoad),
4343                 ExtLoad.getValue(1));
4344       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4345     }
4346   }
4347
4348   // fold (sext (and/or/xor (load x), cst)) ->
4349   //      (and/or/xor (sextload x), (sext cst))
4350   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4351        N0.getOpcode() == ISD::XOR) &&
4352       isa<LoadSDNode>(N0.getOperand(0)) &&
4353       N0.getOperand(1).getOpcode() == ISD::Constant &&
4354       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4355       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4356     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4357     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4358       bool DoXform = true;
4359       SmallVector<SDNode*, 4> SetCCs;
4360       if (!N0.hasOneUse())
4361         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4362                                           SetCCs, TLI);
4363       if (DoXform) {
4364         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4365                                          LN0->getChain(), LN0->getBasePtr(),
4366                                          LN0->getPointerInfo(),
4367                                          LN0->getMemoryVT(),
4368                                          LN0->isVolatile(),
4369                                          LN0->isNonTemporal(),
4370                                          LN0->getAlignment());
4371         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4372         Mask = Mask.sext(VT.getSizeInBits());
4373         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4374                                   ExtLoad, DAG.getConstant(Mask, VT));
4375         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4376                                     N0.getOperand(0).getDebugLoc(),
4377                                     N0.getOperand(0).getValueType(), ExtLoad);
4378         CombineTo(N, And);
4379         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4380         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4381                         ISD::SIGN_EXTEND);
4382         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4383       }
4384     }
4385   }
4386
4387   if (N0.getOpcode() == ISD::SETCC) {
4388     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4389     // Only do this before legalize for now.
4390     if (VT.isVector() && !LegalOperations) {
4391       EVT N0VT = N0.getOperand(0).getValueType();
4392       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4393       // of the same size as the compared operands. Only optimize sext(setcc())
4394       // if this is the case.
4395       EVT SVT = TLI.getSetCCResultType(N0VT);
4396
4397       // We know that the # elements of the results is the same as the
4398       // # elements of the compare (and the # elements of the compare result
4399       // for that matter).  Check to see that they are the same size.  If so,
4400       // we know that the element size of the sext'd result matches the
4401       // element size of the compare operands.
4402       if (VT.getSizeInBits() == SVT.getSizeInBits())
4403         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4404                              N0.getOperand(1),
4405                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4406       // If the desired elements are smaller or larger than the source
4407       // elements we can use a matching integer vector type and then
4408       // truncate/sign extend
4409       else {
4410         EVT MatchingElementType =
4411           EVT::getIntegerVT(*DAG.getContext(),
4412                             N0VT.getScalarType().getSizeInBits());
4413         EVT MatchingVectorType =
4414           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4415                            N0VT.getVectorNumElements());
4416
4417         if (SVT == MatchingVectorType) {
4418           SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4419                                  N0.getOperand(0), N0.getOperand(1),
4420                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
4421           return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4422         }
4423       }
4424     }
4425
4426     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4427     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4428     SDValue NegOne =
4429       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4430     SDValue SCC =
4431       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4432                        NegOne, DAG.getConstant(0, VT),
4433                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4434     if (SCC.getNode()) return SCC;
4435     if (!LegalOperations ||
4436         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4437       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4438                          DAG.getSetCC(N->getDebugLoc(),
4439                                       TLI.getSetCCResultType(VT),
4440                                       N0.getOperand(0), N0.getOperand(1),
4441                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4442                          NegOne, DAG.getConstant(0, VT));
4443   }
4444
4445   // fold (sext x) -> (zext x) if the sign bit is known zero.
4446   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4447       DAG.SignBitIsZero(N0))
4448     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4449
4450   return SDValue();
4451 }
4452
4453 // isTruncateOf - If N is a truncate of some other value, return true, record
4454 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4455 // This function computes KnownZero to avoid a duplicated call to
4456 // ComputeMaskedBits in the caller.
4457 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4458                          APInt &KnownZero) {
4459   APInt KnownOne;
4460   if (N->getOpcode() == ISD::TRUNCATE) {
4461     Op = N->getOperand(0);
4462     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4463     return true;
4464   }
4465
4466   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4467       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4468     return false;
4469
4470   SDValue Op0 = N->getOperand(0);
4471   SDValue Op1 = N->getOperand(1);
4472   assert(Op0.getValueType() == Op1.getValueType());
4473
4474   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4475   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4476   if (COp0 && COp0->isNullValue())
4477     Op = Op1;
4478   else if (COp1 && COp1->isNullValue())
4479     Op = Op0;
4480   else
4481     return false;
4482
4483   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4484
4485   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4486     return false;
4487
4488   return true;
4489 }
4490
4491 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4492   SDValue N0 = N->getOperand(0);
4493   EVT VT = N->getValueType(0);
4494
4495   // fold (zext c1) -> c1
4496   if (isa<ConstantSDNode>(N0))
4497     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4498   // fold (zext (zext x)) -> (zext x)
4499   // fold (zext (aext x)) -> (zext x)
4500   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4501     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4502                        N0.getOperand(0));
4503
4504   // fold (zext (truncate x)) -> (zext x) or
4505   //      (zext (truncate x)) -> (truncate x)
4506   // This is valid when the truncated bits of x are already zero.
4507   // FIXME: We should extend this to work for vectors too.
4508   SDValue Op;
4509   APInt KnownZero;
4510   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4511     APInt TruncatedBits =
4512       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4513       APInt(Op.getValueSizeInBits(), 0) :
4514       APInt::getBitsSet(Op.getValueSizeInBits(),
4515                         N0.getValueSizeInBits(),
4516                         std::min(Op.getValueSizeInBits(),
4517                                  VT.getSizeInBits()));
4518     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4519       if (VT.bitsGT(Op.getValueType()))
4520         return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4521       if (VT.bitsLT(Op.getValueType()))
4522         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4523
4524       return Op;
4525     }
4526   }
4527
4528   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4529   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4530   if (N0.getOpcode() == ISD::TRUNCATE) {
4531     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4532     if (NarrowLoad.getNode()) {
4533       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4534       if (NarrowLoad.getNode() != N0.getNode()) {
4535         CombineTo(N0.getNode(), NarrowLoad);
4536         // CombineTo deleted the truncate, if needed, but not what's under it.
4537         AddToWorkList(oye);
4538       }
4539       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4540     }
4541   }
4542
4543   // fold (zext (truncate x)) -> (and x, mask)
4544   if (N0.getOpcode() == ISD::TRUNCATE &&
4545       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4546
4547     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4548     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4549     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4550     if (NarrowLoad.getNode()) {
4551       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4552       if (NarrowLoad.getNode() != N0.getNode()) {
4553         CombineTo(N0.getNode(), NarrowLoad);
4554         // CombineTo deleted the truncate, if needed, but not what's under it.
4555         AddToWorkList(oye);
4556       }
4557       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4558     }
4559
4560     SDValue Op = N0.getOperand(0);
4561     if (Op.getValueType().bitsLT(VT)) {
4562       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4563       AddToWorkList(Op.getNode());
4564     } else if (Op.getValueType().bitsGT(VT)) {
4565       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4566       AddToWorkList(Op.getNode());
4567     }
4568     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4569                                   N0.getValueType().getScalarType());
4570   }
4571
4572   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4573   // if either of the casts is not free.
4574   if (N0.getOpcode() == ISD::AND &&
4575       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4576       N0.getOperand(1).getOpcode() == ISD::Constant &&
4577       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4578                            N0.getValueType()) ||
4579        !TLI.isZExtFree(N0.getValueType(), VT))) {
4580     SDValue X = N0.getOperand(0).getOperand(0);
4581     if (X.getValueType().bitsLT(VT)) {
4582       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4583     } else if (X.getValueType().bitsGT(VT)) {
4584       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4585     }
4586     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4587     Mask = Mask.zext(VT.getSizeInBits());
4588     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4589                        X, DAG.getConstant(Mask, VT));
4590   }
4591
4592   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4593   // None of the supported targets knows how to perform load and vector_zext
4594   // on vectors in one instruction.  We only perform this transformation on
4595   // scalars.
4596   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4597       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4598        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4599     bool DoXform = true;
4600     SmallVector<SDNode*, 4> SetCCs;
4601     if (!N0.hasOneUse())
4602       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4603     if (DoXform) {
4604       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4605       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4606                                        LN0->getChain(),
4607                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4608                                        N0.getValueType(),
4609                                        LN0->isVolatile(), LN0->isNonTemporal(),
4610                                        LN0->getAlignment());
4611       CombineTo(N, ExtLoad);
4612       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4613                                   N0.getValueType(), ExtLoad);
4614       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4615
4616       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4617                       ISD::ZERO_EXTEND);
4618       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4619     }
4620   }
4621
4622   // fold (zext (and/or/xor (load x), cst)) ->
4623   //      (and/or/xor (zextload x), (zext cst))
4624   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4625        N0.getOpcode() == ISD::XOR) &&
4626       isa<LoadSDNode>(N0.getOperand(0)) &&
4627       N0.getOperand(1).getOpcode() == ISD::Constant &&
4628       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4629       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4630     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4631     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4632       bool DoXform = true;
4633       SmallVector<SDNode*, 4> SetCCs;
4634       if (!N0.hasOneUse())
4635         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4636                                           SetCCs, TLI);
4637       if (DoXform) {
4638         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4639                                          LN0->getChain(), LN0->getBasePtr(),
4640                                          LN0->getPointerInfo(),
4641                                          LN0->getMemoryVT(),
4642                                          LN0->isVolatile(),
4643                                          LN0->isNonTemporal(),
4644                                          LN0->getAlignment());
4645         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4646         Mask = Mask.zext(VT.getSizeInBits());
4647         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4648                                   ExtLoad, DAG.getConstant(Mask, VT));
4649         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4650                                     N0.getOperand(0).getDebugLoc(),
4651                                     N0.getOperand(0).getValueType(), ExtLoad);
4652         CombineTo(N, And);
4653         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4654         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4655                         ISD::ZERO_EXTEND);
4656         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4657       }
4658     }
4659   }
4660
4661   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4662   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4663   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4664       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4665     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4666     EVT MemVT = LN0->getMemoryVT();
4667     if ((!LegalOperations && !LN0->isVolatile()) ||
4668         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4669       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4670                                        LN0->getChain(),
4671                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4672                                        MemVT,
4673                                        LN0->isVolatile(), LN0->isNonTemporal(),
4674                                        LN0->getAlignment());
4675       CombineTo(N, ExtLoad);
4676       CombineTo(N0.getNode(),
4677                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4678                             ExtLoad),
4679                 ExtLoad.getValue(1));
4680       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4681     }
4682   }
4683
4684   if (N0.getOpcode() == ISD::SETCC) {
4685     if (!LegalOperations && VT.isVector()) {
4686       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4687       // Only do this before legalize for now.
4688       EVT N0VT = N0.getOperand(0).getValueType();
4689       EVT EltVT = VT.getVectorElementType();
4690       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4691                                     DAG.getConstant(1, EltVT));
4692       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4693         // We know that the # elements of the results is the same as the
4694         // # elements of the compare (and the # elements of the compare result
4695         // for that matter).  Check to see that they are the same size.  If so,
4696         // we know that the element size of the sext'd result matches the
4697         // element size of the compare operands.
4698         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4699                            DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4700                                          N0.getOperand(1),
4701                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4702                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4703                                        &OneOps[0], OneOps.size()));
4704
4705       // If the desired elements are smaller or larger than the source
4706       // elements we can use a matching integer vector type and then
4707       // truncate/sign extend
4708       EVT MatchingElementType =
4709         EVT::getIntegerVT(*DAG.getContext(),
4710                           N0VT.getScalarType().getSizeInBits());
4711       EVT MatchingVectorType =
4712         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4713                          N0VT.getVectorNumElements());
4714       SDValue VsetCC =
4715         DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4716                       N0.getOperand(1),
4717                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4718       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4719                          DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4720                          DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4721                                      &OneOps[0], OneOps.size()));
4722     }
4723
4724     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4725     SDValue SCC =
4726       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4727                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4728                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4729     if (SCC.getNode()) return SCC;
4730   }
4731
4732   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4733   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4734       isa<ConstantSDNode>(N0.getOperand(1)) &&
4735       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4736       N0.hasOneUse()) {
4737     SDValue ShAmt = N0.getOperand(1);
4738     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4739     if (N0.getOpcode() == ISD::SHL) {
4740       SDValue InnerZExt = N0.getOperand(0);
4741       // If the original shl may be shifting out bits, do not perform this
4742       // transformation.
4743       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4744         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4745       if (ShAmtVal > KnownZeroBits)
4746         return SDValue();
4747     }
4748
4749     DebugLoc DL = N->getDebugLoc();
4750
4751     // Ensure that the shift amount is wide enough for the shifted value.
4752     if (VT.getSizeInBits() >= 256)
4753       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4754
4755     return DAG.getNode(N0.getOpcode(), DL, VT,
4756                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4757                        ShAmt);
4758   }
4759
4760   return SDValue();
4761 }
4762
4763 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4764   SDValue N0 = N->getOperand(0);
4765   EVT VT = N->getValueType(0);
4766
4767   // fold (aext c1) -> c1
4768   if (isa<ConstantSDNode>(N0))
4769     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4770   // fold (aext (aext x)) -> (aext x)
4771   // fold (aext (zext x)) -> (zext x)
4772   // fold (aext (sext x)) -> (sext x)
4773   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4774       N0.getOpcode() == ISD::ZERO_EXTEND ||
4775       N0.getOpcode() == ISD::SIGN_EXTEND)
4776     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4777
4778   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4779   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4780   if (N0.getOpcode() == ISD::TRUNCATE) {
4781     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4782     if (NarrowLoad.getNode()) {
4783       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4784       if (NarrowLoad.getNode() != N0.getNode()) {
4785         CombineTo(N0.getNode(), NarrowLoad);
4786         // CombineTo deleted the truncate, if needed, but not what's under it.
4787         AddToWorkList(oye);
4788       }
4789       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4790     }
4791   }
4792
4793   // fold (aext (truncate x))
4794   if (N0.getOpcode() == ISD::TRUNCATE) {
4795     SDValue TruncOp = N0.getOperand(0);
4796     if (TruncOp.getValueType() == VT)
4797       return TruncOp; // x iff x size == zext size.
4798     if (TruncOp.getValueType().bitsGT(VT))
4799       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4800     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4801   }
4802
4803   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4804   // if the trunc is not free.
4805   if (N0.getOpcode() == ISD::AND &&
4806       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4807       N0.getOperand(1).getOpcode() == ISD::Constant &&
4808       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4809                           N0.getValueType())) {
4810     SDValue X = N0.getOperand(0).getOperand(0);
4811     if (X.getValueType().bitsLT(VT)) {
4812       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4813     } else if (X.getValueType().bitsGT(VT)) {
4814       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4815     }
4816     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4817     Mask = Mask.zext(VT.getSizeInBits());
4818     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4819                        X, DAG.getConstant(Mask, VT));
4820   }
4821
4822   // fold (aext (load x)) -> (aext (truncate (extload x)))
4823   // None of the supported targets knows how to perform load and any_ext
4824   // on vectors in one instruction.  We only perform this transformation on
4825   // scalars.
4826   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4827       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4828        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4829     bool DoXform = true;
4830     SmallVector<SDNode*, 4> SetCCs;
4831     if (!N0.hasOneUse())
4832       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4833     if (DoXform) {
4834       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4835       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4836                                        LN0->getChain(),
4837                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4838                                        N0.getValueType(),
4839                                        LN0->isVolatile(), LN0->isNonTemporal(),
4840                                        LN0->getAlignment());
4841       CombineTo(N, ExtLoad);
4842       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4843                                   N0.getValueType(), ExtLoad);
4844       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4845       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4846                       ISD::ANY_EXTEND);
4847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4848     }
4849   }
4850
4851   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4852   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4853   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4854   if (N0.getOpcode() == ISD::LOAD &&
4855       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4856       N0.hasOneUse()) {
4857     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4858     EVT MemVT = LN0->getMemoryVT();
4859     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4860                                      VT, LN0->getChain(), LN0->getBasePtr(),
4861                                      LN0->getPointerInfo(), MemVT,
4862                                      LN0->isVolatile(), LN0->isNonTemporal(),
4863                                      LN0->getAlignment());
4864     CombineTo(N, ExtLoad);
4865     CombineTo(N0.getNode(),
4866               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4867                           N0.getValueType(), ExtLoad),
4868               ExtLoad.getValue(1));
4869     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4870   }
4871
4872   if (N0.getOpcode() == ISD::SETCC) {
4873     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4874     // Only do this before legalize for now.
4875     if (VT.isVector() && !LegalOperations) {
4876       EVT N0VT = N0.getOperand(0).getValueType();
4877         // We know that the # elements of the results is the same as the
4878         // # elements of the compare (and the # elements of the compare result
4879         // for that matter).  Check to see that they are the same size.  If so,
4880         // we know that the element size of the sext'd result matches the
4881         // element size of the compare operands.
4882       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4883         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4884                              N0.getOperand(1),
4885                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4886       // If the desired elements are smaller or larger than the source
4887       // elements we can use a matching integer vector type and then
4888       // truncate/sign extend
4889       else {
4890         EVT MatchingElementType =
4891           EVT::getIntegerVT(*DAG.getContext(),
4892                             N0VT.getScalarType().getSizeInBits());
4893         EVT MatchingVectorType =
4894           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4895                            N0VT.getVectorNumElements());
4896         SDValue VsetCC =
4897           DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4898                         N0.getOperand(1),
4899                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
4900         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4901       }
4902     }
4903
4904     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4905     SDValue SCC =
4906       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4907                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4908                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4909     if (SCC.getNode())
4910       return SCC;
4911   }
4912
4913   return SDValue();
4914 }
4915
4916 /// GetDemandedBits - See if the specified operand can be simplified with the
4917 /// knowledge that only the bits specified by Mask are used.  If so, return the
4918 /// simpler operand, otherwise return a null SDValue.
4919 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4920   switch (V.getOpcode()) {
4921   default: break;
4922   case ISD::Constant: {
4923     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4924     assert(CV != 0 && "Const value should be ConstSDNode.");
4925     const APInt &CVal = CV->getAPIntValue();
4926     APInt NewVal = CVal & Mask;
4927     if (NewVal != CVal) {
4928       return DAG.getConstant(NewVal, V.getValueType());
4929     }
4930     break;
4931   }
4932   case ISD::OR:
4933   case ISD::XOR:
4934     // If the LHS or RHS don't contribute bits to the or, drop them.
4935     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4936       return V.getOperand(1);
4937     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4938       return V.getOperand(0);
4939     break;
4940   case ISD::SRL:
4941     // Only look at single-use SRLs.
4942     if (!V.getNode()->hasOneUse())
4943       break;
4944     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4945       // See if we can recursively simplify the LHS.
4946       unsigned Amt = RHSC->getZExtValue();
4947
4948       // Watch out for shift count overflow though.
4949       if (Amt >= Mask.getBitWidth()) break;
4950       APInt NewMask = Mask << Amt;
4951       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4952       if (SimplifyLHS.getNode())
4953         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4954                            SimplifyLHS, V.getOperand(1));
4955     }
4956   }
4957   return SDValue();
4958 }
4959
4960 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4961 /// bits and then truncated to a narrower type and where N is a multiple
4962 /// of number of bits of the narrower type, transform it to a narrower load
4963 /// from address + N / num of bits of new type. If the result is to be
4964 /// extended, also fold the extension to form a extending load.
4965 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4966   unsigned Opc = N->getOpcode();
4967
4968   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4969   SDValue N0 = N->getOperand(0);
4970   EVT VT = N->getValueType(0);
4971   EVT ExtVT = VT;
4972
4973   // This transformation isn't valid for vector loads.
4974   if (VT.isVector())
4975     return SDValue();
4976
4977   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4978   // extended to VT.
4979   if (Opc == ISD::SIGN_EXTEND_INREG) {
4980     ExtType = ISD::SEXTLOAD;
4981     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4982   } else if (Opc == ISD::SRL) {
4983     // Another special-case: SRL is basically zero-extending a narrower value.
4984     ExtType = ISD::ZEXTLOAD;
4985     N0 = SDValue(N, 0);
4986     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4987     if (!N01) return SDValue();
4988     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4989                               VT.getSizeInBits() - N01->getZExtValue());
4990   }
4991   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4992     return SDValue();
4993
4994   unsigned EVTBits = ExtVT.getSizeInBits();
4995
4996   // Do not generate loads of non-round integer types since these can
4997   // be expensive (and would be wrong if the type is not byte sized).
4998   if (!ExtVT.isRound())
4999     return SDValue();
5000
5001   unsigned ShAmt = 0;
5002   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5003     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5004       ShAmt = N01->getZExtValue();
5005       // Is the shift amount a multiple of size of VT?
5006       if ((ShAmt & (EVTBits-1)) == 0) {
5007         N0 = N0.getOperand(0);
5008         // Is the load width a multiple of size of VT?
5009         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5010           return SDValue();
5011       }
5012
5013       // At this point, we must have a load or else we can't do the transform.
5014       if (!isa<LoadSDNode>(N0)) return SDValue();
5015
5016       // If the shift amount is larger than the input type then we're not
5017       // accessing any of the loaded bytes.  If the load was a zextload/extload
5018       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5019       // If the load was a sextload then the result is a splat of the sign bit
5020       // of the extended byte.  This is not worth optimizing for.
5021       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5022         return SDValue();
5023     }
5024   }
5025
5026   // If the load is shifted left (and the result isn't shifted back right),
5027   // we can fold the truncate through the shift.
5028   unsigned ShLeftAmt = 0;
5029   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5030       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5031     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5032       ShLeftAmt = N01->getZExtValue();
5033       N0 = N0.getOperand(0);
5034     }
5035   }
5036
5037   // If we haven't found a load, we can't narrow it.  Don't transform one with
5038   // multiple uses, this would require adding a new load.
5039   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
5040       // Don't change the width of a volatile load.
5041       cast<LoadSDNode>(N0)->isVolatile())
5042     return SDValue();
5043
5044   // Verify that we are actually reducing a load width here.
5045   if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
5046     return SDValue();
5047
5048   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5049   EVT PtrType = N0.getOperand(1).getValueType();
5050
5051   if (PtrType == MVT::Untyped || PtrType.isExtended())
5052     // It's not possible to generate a constant of extended or untyped type.
5053     return SDValue();
5054
5055   // For big endian targets, we need to adjust the offset to the pointer to
5056   // load the correct bytes.
5057   if (TLI.isBigEndian()) {
5058     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5059     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5060     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5061   }
5062
5063   uint64_t PtrOff = ShAmt / 8;
5064   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5065   SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5066                                PtrType, LN0->getBasePtr(),
5067                                DAG.getConstant(PtrOff, PtrType));
5068   AddToWorkList(NewPtr.getNode());
5069
5070   SDValue Load;
5071   if (ExtType == ISD::NON_EXTLOAD)
5072     Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5073                         LN0->getPointerInfo().getWithOffset(PtrOff),
5074                         LN0->isVolatile(), LN0->isNonTemporal(),
5075                         LN0->isInvariant(), NewAlign);
5076   else
5077     Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5078                           LN0->getPointerInfo().getWithOffset(PtrOff),
5079                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5080                           NewAlign);
5081
5082   // Replace the old load's chain with the new load's chain.
5083   WorkListRemover DeadNodes(*this);
5084   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5085
5086   // Shift the result left, if we've swallowed a left shift.
5087   SDValue Result = Load;
5088   if (ShLeftAmt != 0) {
5089     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5090     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5091       ShImmTy = VT;
5092     Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5093                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5094   }
5095
5096   // Return the new loaded value.
5097   return Result;
5098 }
5099
5100 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5101   SDValue N0 = N->getOperand(0);
5102   SDValue N1 = N->getOperand(1);
5103   EVT VT = N->getValueType(0);
5104   EVT EVT = cast<VTSDNode>(N1)->getVT();
5105   unsigned VTBits = VT.getScalarType().getSizeInBits();
5106   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5107
5108   // fold (sext_in_reg c1) -> c1
5109   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5110     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5111
5112   // If the input is already sign extended, just drop the extension.
5113   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5114     return N0;
5115
5116   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5117   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5118       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5119     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5120                        N0.getOperand(0), N1);
5121   }
5122
5123   // fold (sext_in_reg (sext x)) -> (sext x)
5124   // fold (sext_in_reg (aext x)) -> (sext x)
5125   // if x is small enough.
5126   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5127     SDValue N00 = N0.getOperand(0);
5128     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5129         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5130       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5131   }
5132
5133   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5134   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5135     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5136
5137   // fold operands of sext_in_reg based on knowledge that the top bits are not
5138   // demanded.
5139   if (SimplifyDemandedBits(SDValue(N, 0)))
5140     return SDValue(N, 0);
5141
5142   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5143   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5144   SDValue NarrowLoad = ReduceLoadWidth(N);
5145   if (NarrowLoad.getNode())
5146     return NarrowLoad;
5147
5148   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5149   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5150   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5151   if (N0.getOpcode() == ISD::SRL) {
5152     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5153       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5154         // We can turn this into an SRA iff the input to the SRL is already sign
5155         // extended enough.
5156         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5157         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5158           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5159                              N0.getOperand(0), N0.getOperand(1));
5160       }
5161   }
5162
5163   // fold (sext_inreg (extload x)) -> (sextload x)
5164   if (ISD::isEXTLoad(N0.getNode()) &&
5165       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5166       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5167       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5168        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5169     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5170     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5171                                      LN0->getChain(),
5172                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5173                                      EVT,
5174                                      LN0->isVolatile(), LN0->isNonTemporal(),
5175                                      LN0->getAlignment());
5176     CombineTo(N, ExtLoad);
5177     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5178     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5179   }
5180   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5181   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5182       N0.hasOneUse() &&
5183       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5184       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5185        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5186     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5187     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5188                                      LN0->getChain(),
5189                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5190                                      EVT,
5191                                      LN0->isVolatile(), LN0->isNonTemporal(),
5192                                      LN0->getAlignment());
5193     CombineTo(N, ExtLoad);
5194     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5195     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5196   }
5197
5198   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5199   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5200     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5201                                        N0.getOperand(1), false);
5202     if (BSwap.getNode() != 0)
5203       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5204                          BSwap, N1);
5205   }
5206
5207   return SDValue();
5208 }
5209
5210 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5211   SDValue N0 = N->getOperand(0);
5212   EVT VT = N->getValueType(0);
5213   bool isLE = TLI.isLittleEndian();
5214
5215   // noop truncate
5216   if (N0.getValueType() == N->getValueType(0))
5217     return N0;
5218   // fold (truncate c1) -> c1
5219   if (isa<ConstantSDNode>(N0))
5220     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5221   // fold (truncate (truncate x)) -> (truncate x)
5222   if (N0.getOpcode() == ISD::TRUNCATE)
5223     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5224   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5225   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5226       N0.getOpcode() == ISD::SIGN_EXTEND ||
5227       N0.getOpcode() == ISD::ANY_EXTEND) {
5228     if (N0.getOperand(0).getValueType().bitsLT(VT))
5229       // if the source is smaller than the dest, we still need an extend
5230       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5231                          N0.getOperand(0));
5232     else if (N0.getOperand(0).getValueType().bitsGT(VT))
5233       // if the source is larger than the dest, than we just need the truncate
5234       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5235     else
5236       // if the source and dest are the same type, we can drop both the extend
5237       // and the truncate.
5238       return N0.getOperand(0);
5239   }
5240
5241   // Fold extract-and-trunc into a narrow extract. For example:
5242   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5243   //   i32 y = TRUNCATE(i64 x)
5244   //        -- becomes --
5245   //   v16i8 b = BITCAST (v2i64 val)
5246   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5247   //
5248   // Note: We only run this optimization after type legalization (which often
5249   // creates this pattern) and before operation legalization after which
5250   // we need to be more careful about the vector instructions that we generate.
5251   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5252       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5253
5254     EVT VecTy = N0.getOperand(0).getValueType();
5255     EVT ExTy = N0.getValueType();
5256     EVT TrTy = N->getValueType(0);
5257
5258     unsigned NumElem = VecTy.getVectorNumElements();
5259     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5260
5261     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5262     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5263
5264     SDValue EltNo = N0->getOperand(1);
5265     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5266       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5267       EVT IndexTy = N0->getOperand(1).getValueType();
5268       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5269
5270       SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5271                               NVT, N0.getOperand(0));
5272
5273       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5274                          N->getDebugLoc(), TrTy, V,
5275                          DAG.getConstant(Index, IndexTy));
5276     }
5277   }
5278
5279   // See if we can simplify the input to this truncate through knowledge that
5280   // only the low bits are being used.
5281   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5282   // Currently we only perform this optimization on scalars because vectors
5283   // may have different active low bits.
5284   if (!VT.isVector()) {
5285     SDValue Shorter =
5286       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5287                                                VT.getSizeInBits()));
5288     if (Shorter.getNode())
5289       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5290   }
5291   // fold (truncate (load x)) -> (smaller load x)
5292   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5293   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5294     SDValue Reduced = ReduceLoadWidth(N);
5295     if (Reduced.getNode())
5296       return Reduced;
5297   }
5298
5299   // Simplify the operands using demanded-bits information.
5300   if (!VT.isVector() &&
5301       SimplifyDemandedBits(SDValue(N, 0)))
5302     return SDValue(N, 0);
5303
5304   return SDValue();
5305 }
5306
5307 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5308   SDValue Elt = N->getOperand(i);
5309   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5310     return Elt.getNode();
5311   return Elt.getOperand(Elt.getResNo()).getNode();
5312 }
5313
5314 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5315 /// if load locations are consecutive.
5316 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5317   assert(N->getOpcode() == ISD::BUILD_PAIR);
5318
5319   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5320   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5321   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5322       LD1->getPointerInfo().getAddrSpace() !=
5323          LD2->getPointerInfo().getAddrSpace())
5324     return SDValue();
5325   EVT LD1VT = LD1->getValueType(0);
5326
5327   if (ISD::isNON_EXTLoad(LD2) &&
5328       LD2->hasOneUse() &&
5329       // If both are volatile this would reduce the number of volatile loads.
5330       // If one is volatile it might be ok, but play conservative and bail out.
5331       !LD1->isVolatile() &&
5332       !LD2->isVolatile() &&
5333       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5334     unsigned Align = LD1->getAlignment();
5335     unsigned NewAlign = TLI.getTargetData()->
5336       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5337
5338     if (NewAlign <= Align &&
5339         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5340       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5341                          LD1->getBasePtr(), LD1->getPointerInfo(),
5342                          false, false, false, Align);
5343   }
5344
5345   return SDValue();
5346 }
5347
5348 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5349   SDValue N0 = N->getOperand(0);
5350   EVT VT = N->getValueType(0);
5351
5352   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5353   // Only do this before legalize, since afterward the target may be depending
5354   // on the bitconvert.
5355   // First check to see if this is all constant.
5356   if (!LegalTypes &&
5357       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5358       VT.isVector()) {
5359     bool isSimple = true;
5360     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5361       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5362           N0.getOperand(i).getOpcode() != ISD::Constant &&
5363           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5364         isSimple = false;
5365         break;
5366       }
5367
5368     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5369     assert(!DestEltVT.isVector() &&
5370            "Element type of vector ValueType must not be vector!");
5371     if (isSimple)
5372       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5373   }
5374
5375   // If the input is a constant, let getNode fold it.
5376   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5377     SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5378     if (Res.getNode() != N) {
5379       if (!LegalOperations ||
5380           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5381         return Res;
5382
5383       // Folding it resulted in an illegal node, and it's too late to
5384       // do that. Clean up the old node and forego the transformation.
5385       // Ideally this won't happen very often, because instcombine
5386       // and the earlier dagcombine runs (where illegal nodes are
5387       // permitted) should have folded most of them already.
5388       DAG.DeleteNode(Res.getNode());
5389     }
5390   }
5391
5392   // (conv (conv x, t1), t2) -> (conv x, t2)
5393   if (N0.getOpcode() == ISD::BITCAST)
5394     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5395                        N0.getOperand(0));
5396
5397   // fold (conv (load x)) -> (load (conv*)x)
5398   // If the resultant load doesn't need a higher alignment than the original!
5399   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5400       // Do not change the width of a volatile load.
5401       !cast<LoadSDNode>(N0)->isVolatile() &&
5402       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5403     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5404     unsigned Align = TLI.getTargetData()->
5405       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5406     unsigned OrigAlign = LN0->getAlignment();
5407
5408     if (Align <= OrigAlign) {
5409       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5410                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5411                                  LN0->isVolatile(), LN0->isNonTemporal(),
5412                                  LN0->isInvariant(), OrigAlign);
5413       AddToWorkList(N);
5414       CombineTo(N0.getNode(),
5415                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5416                             N0.getValueType(), Load),
5417                 Load.getValue(1));
5418       return Load;
5419     }
5420   }
5421
5422   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5423   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5424   // This often reduces constant pool loads.
5425   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5426        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5427       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
5428     SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5429                                   N0.getOperand(0));
5430     AddToWorkList(NewConv.getNode());
5431
5432     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5433     if (N0.getOpcode() == ISD::FNEG)
5434       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5435                          NewConv, DAG.getConstant(SignBit, VT));
5436     assert(N0.getOpcode() == ISD::FABS);
5437     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5438                        NewConv, DAG.getConstant(~SignBit, VT));
5439   }
5440
5441   // fold (bitconvert (fcopysign cst, x)) ->
5442   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5443   // Note that we don't handle (copysign x, cst) because this can always be
5444   // folded to an fneg or fabs.
5445   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5446       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5447       VT.isInteger() && !VT.isVector()) {
5448     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5449     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5450     if (isTypeLegal(IntXVT)) {
5451       SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5452                               IntXVT, N0.getOperand(1));
5453       AddToWorkList(X.getNode());
5454
5455       // If X has a different width than the result/lhs, sext it or truncate it.
5456       unsigned VTWidth = VT.getSizeInBits();
5457       if (OrigXWidth < VTWidth) {
5458         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5459         AddToWorkList(X.getNode());
5460       } else if (OrigXWidth > VTWidth) {
5461         // To get the sign bit in the right place, we have to shift it right
5462         // before truncating.
5463         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5464                         X.getValueType(), X,
5465                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5466         AddToWorkList(X.getNode());
5467         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5468         AddToWorkList(X.getNode());
5469       }
5470
5471       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5472       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5473                       X, DAG.getConstant(SignBit, VT));
5474       AddToWorkList(X.getNode());
5475
5476       SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5477                                 VT, N0.getOperand(0));
5478       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5479                         Cst, DAG.getConstant(~SignBit, VT));
5480       AddToWorkList(Cst.getNode());
5481
5482       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5483     }
5484   }
5485
5486   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5487   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5488     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5489     if (CombineLD.getNode())
5490       return CombineLD;
5491   }
5492
5493   return SDValue();
5494 }
5495
5496 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5497   EVT VT = N->getValueType(0);
5498   return CombineConsecutiveLoads(N, VT);
5499 }
5500
5501 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5502 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5503 /// destination element value type.
5504 SDValue DAGCombiner::
5505 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5506   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5507
5508   // If this is already the right type, we're done.
5509   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5510
5511   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5512   unsigned DstBitSize = DstEltVT.getSizeInBits();
5513
5514   // If this is a conversion of N elements of one type to N elements of another
5515   // type, convert each element.  This handles FP<->INT cases.
5516   if (SrcBitSize == DstBitSize) {
5517     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5518                               BV->getValueType(0).getVectorNumElements());
5519
5520     // Due to the FP element handling below calling this routine recursively,
5521     // we can end up with a scalar-to-vector node here.
5522     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5523       return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5524                          DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5525                                      DstEltVT, BV->getOperand(0)));
5526
5527     SmallVector<SDValue, 8> Ops;
5528     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5529       SDValue Op = BV->getOperand(i);
5530       // If the vector element type is not legal, the BUILD_VECTOR operands
5531       // are promoted and implicitly truncated.  Make that explicit here.
5532       if (Op.getValueType() != SrcEltVT)
5533         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5534       Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5535                                 DstEltVT, Op));
5536       AddToWorkList(Ops.back().getNode());
5537     }
5538     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5539                        &Ops[0], Ops.size());
5540   }
5541
5542   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5543   // handle annoying details of growing/shrinking FP values, we convert them to
5544   // int first.
5545   if (SrcEltVT.isFloatingPoint()) {
5546     // Convert the input float vector to a int vector where the elements are the
5547     // same sizes.
5548     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5549     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5550     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5551     SrcEltVT = IntVT;
5552   }
5553
5554   // Now we know the input is an integer vector.  If the output is a FP type,
5555   // convert to integer first, then to FP of the right size.
5556   if (DstEltVT.isFloatingPoint()) {
5557     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5558     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5559     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5560
5561     // Next, convert to FP elements of the same size.
5562     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5563   }
5564
5565   // Okay, we know the src/dst types are both integers of differing types.
5566   // Handling growing first.
5567   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5568   if (SrcBitSize < DstBitSize) {
5569     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5570
5571     SmallVector<SDValue, 8> Ops;
5572     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5573          i += NumInputsPerOutput) {
5574       bool isLE = TLI.isLittleEndian();
5575       APInt NewBits = APInt(DstBitSize, 0);
5576       bool EltIsUndef = true;
5577       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5578         // Shift the previously computed bits over.
5579         NewBits <<= SrcBitSize;
5580         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5581         if (Op.getOpcode() == ISD::UNDEF) continue;
5582         EltIsUndef = false;
5583
5584         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5585                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5586       }
5587
5588       if (EltIsUndef)
5589         Ops.push_back(DAG.getUNDEF(DstEltVT));
5590       else
5591         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5592     }
5593
5594     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5595     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5596                        &Ops[0], Ops.size());
5597   }
5598
5599   // Finally, this must be the case where we are shrinking elements: each input
5600   // turns into multiple outputs.
5601   bool isS2V = ISD::isScalarToVector(BV);
5602   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5603   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5604                             NumOutputsPerInput*BV->getNumOperands());
5605   SmallVector<SDValue, 8> Ops;
5606
5607   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5608     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5609       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5610         Ops.push_back(DAG.getUNDEF(DstEltVT));
5611       continue;
5612     }
5613
5614     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5615                   getAPIntValue().zextOrTrunc(SrcBitSize);
5616
5617     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5618       APInt ThisVal = OpVal.trunc(DstBitSize);
5619       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5620       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5621         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5622         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5623                            Ops[0]);
5624       OpVal = OpVal.lshr(DstBitSize);
5625     }
5626
5627     // For big endian targets, swap the order of the pieces of each element.
5628     if (TLI.isBigEndian())
5629       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5630   }
5631
5632   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5633                      &Ops[0], Ops.size());
5634 }
5635
5636 SDValue DAGCombiner::visitFADD(SDNode *N) {
5637   SDValue N0 = N->getOperand(0);
5638   SDValue N1 = N->getOperand(1);
5639   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5640   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5641   EVT VT = N->getValueType(0);
5642
5643   // fold vector ops
5644   if (VT.isVector()) {
5645     SDValue FoldedVOp = SimplifyVBinOp(N);
5646     if (FoldedVOp.getNode()) return FoldedVOp;
5647   }
5648
5649   // fold (fadd c1, c2) -> c1 + c2
5650   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5651     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5652   // canonicalize constant to RHS
5653   if (N0CFP && !N1CFP)
5654     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5655   // fold (fadd A, 0) -> A
5656   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5657       N1CFP->getValueAPF().isZero())
5658     return N0;
5659   // fold (fadd A, (fneg B)) -> (fsub A, B)
5660   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5661       isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5662     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5663                        GetNegatedExpression(N1, DAG, LegalOperations));
5664   // fold (fadd (fneg A), B) -> (fsub B, A)
5665   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5666       isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5667     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5668                        GetNegatedExpression(N0, DAG, LegalOperations));
5669
5670   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5671   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5672       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5673       isa<ConstantFPSDNode>(N0.getOperand(1)))
5674     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5675                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5676                                    N0.getOperand(1), N1));
5677
5678   // FADD -> FMA combines:
5679   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5680        DAG.getTarget().Options.UnsafeFPMath) &&
5681       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5682       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5683
5684     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5685     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5686       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5687                          N0.getOperand(0), N0.getOperand(1), N1);
5688     }
5689   
5690     // fold (fadd x, (fmul y, z)) -> (fma x, y, z)
5691     // Note: Commutes FADD operands.
5692     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5693       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5694                          N1.getOperand(0), N1.getOperand(1), N0);
5695     }
5696   }
5697
5698   return SDValue();
5699 }
5700
5701 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5702   SDValue N0 = N->getOperand(0);
5703   SDValue N1 = N->getOperand(1);
5704   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5705   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5706   EVT VT = N->getValueType(0);
5707   DebugLoc dl = N->getDebugLoc();
5708
5709   // fold vector ops
5710   if (VT.isVector()) {
5711     SDValue FoldedVOp = SimplifyVBinOp(N);
5712     if (FoldedVOp.getNode()) return FoldedVOp;
5713   }
5714
5715   // fold (fsub c1, c2) -> c1-c2
5716   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5717     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5718   // fold (fsub A, 0) -> A
5719   if (DAG.getTarget().Options.UnsafeFPMath &&
5720       N1CFP && N1CFP->getValueAPF().isZero())
5721     return N0;
5722   // fold (fsub 0, B) -> -B
5723   if (DAG.getTarget().Options.UnsafeFPMath &&
5724       N0CFP && N0CFP->getValueAPF().isZero()) {
5725     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5726       return GetNegatedExpression(N1, DAG, LegalOperations);
5727     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5728       return DAG.getNode(ISD::FNEG, dl, VT, N1);
5729   }
5730   // fold (fsub A, (fneg B)) -> (fadd A, B)
5731   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5732     return DAG.getNode(ISD::FADD, dl, VT, N0,
5733                        GetNegatedExpression(N1, DAG, LegalOperations));
5734
5735   // If 'unsafe math' is enabled, fold
5736   //    (fsub x, x) -> 0.0 &
5737   //    (fsub x, (fadd x, y)) -> (fneg y) &
5738   //    (fsub x, (fadd y, x)) -> (fneg y)
5739   if (DAG.getTarget().Options.UnsafeFPMath) {
5740     if (N0 == N1)
5741       return DAG.getConstantFP(0.0f, VT);
5742
5743     if (N1.getOpcode() == ISD::FADD) {
5744       SDValue N10 = N1->getOperand(0);
5745       SDValue N11 = N1->getOperand(1);
5746
5747       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
5748                                           &DAG.getTarget().Options))
5749         return GetNegatedExpression(N11, DAG, LegalOperations);
5750       else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
5751                                                &DAG.getTarget().Options))
5752         return GetNegatedExpression(N10, DAG, LegalOperations);
5753     }
5754   }
5755
5756   // FSUB -> FMA combines:
5757   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5758        DAG.getTarget().Options.UnsafeFPMath) &&
5759       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5760       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5761
5762     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
5763     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5764       return DAG.getNode(ISD::FMA, dl, VT,
5765                          N0.getOperand(0), N0.getOperand(1),
5766                          DAG.getNode(ISD::FNEG, dl, VT, N1));
5767     }
5768
5769     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
5770     // Note: Commutes FSUB operands.
5771     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5772       return DAG.getNode(ISD::FMA, dl, VT,
5773                          DAG.getNode(ISD::FNEG, dl, VT,
5774                          N1.getOperand(0)),
5775                          N1.getOperand(1), N0);
5776     }
5777
5778     // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
5779     if (N0.getOpcode() == ISD::FNEG && 
5780         N0.getOperand(0).getOpcode() == ISD::FMUL &&
5781         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
5782       SDValue N00 = N0.getOperand(0).getOperand(0);
5783       SDValue N01 = N0.getOperand(0).getOperand(1);
5784       return DAG.getNode(ISD::FMA, dl, VT,
5785                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
5786                          DAG.getNode(ISD::FNEG, dl, VT, N1));
5787     }
5788   }
5789
5790   return SDValue();
5791 }
5792
5793 SDValue DAGCombiner::visitFMUL(SDNode *N) {
5794   SDValue N0 = N->getOperand(0);
5795   SDValue N1 = N->getOperand(1);
5796   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5797   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5798   EVT VT = N->getValueType(0);
5799   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5800
5801   // fold vector ops
5802   if (VT.isVector()) {
5803     SDValue FoldedVOp = SimplifyVBinOp(N);
5804     if (FoldedVOp.getNode()) return FoldedVOp;
5805   }
5806
5807   // fold (fmul c1, c2) -> c1*c2
5808   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5809     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5810   // canonicalize constant to RHS
5811   if (N0CFP && !N1CFP)
5812     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5813   // fold (fmul A, 0) -> 0
5814   if (DAG.getTarget().Options.UnsafeFPMath &&
5815       N1CFP && N1CFP->getValueAPF().isZero())
5816     return N1;
5817   // fold (fmul A, 0) -> 0, vector edition.
5818   if (DAG.getTarget().Options.UnsafeFPMath &&
5819       ISD::isBuildVectorAllZeros(N1.getNode()))
5820     return N1;
5821   // fold (fmul A, 1.0) -> A
5822   if (N1CFP && N1CFP->isExactlyValue(1.0))
5823     return N0;
5824   // fold (fmul X, 2.0) -> (fadd X, X)
5825   if (N1CFP && N1CFP->isExactlyValue(+2.0))
5826     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5827   // fold (fmul X, -1.0) -> (fneg X)
5828   if (N1CFP && N1CFP->isExactlyValue(-1.0))
5829     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5830       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5831
5832   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5833   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5834                                        &DAG.getTarget().Options)) {
5835     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 
5836                                          &DAG.getTarget().Options)) {
5837       // Both can be negated for free, check to see if at least one is cheaper
5838       // negated.
5839       if (LHSNeg == 2 || RHSNeg == 2)
5840         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5841                            GetNegatedExpression(N0, DAG, LegalOperations),
5842                            GetNegatedExpression(N1, DAG, LegalOperations));
5843     }
5844   }
5845
5846   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5847   if (DAG.getTarget().Options.UnsafeFPMath &&
5848       N1CFP && N0.getOpcode() == ISD::FMUL &&
5849       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5850     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5851                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5852                                    N0.getOperand(1), N1));
5853
5854   return SDValue();
5855 }
5856
5857 SDValue DAGCombiner::visitFMA(SDNode *N) {
5858   SDValue N0 = N->getOperand(0);
5859   SDValue N1 = N->getOperand(1);
5860   SDValue N2 = N->getOperand(2);
5861   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5862   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5863   EVT VT = N->getValueType(0);
5864
5865   if (N0CFP && N0CFP->isExactlyValue(1.0))
5866     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
5867   if (N1CFP && N1CFP->isExactlyValue(1.0))
5868     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
5869
5870   // Canonicalize (fma c, x, y) -> (fma x, c, y)
5871   if (N0CFP && !N1CFP)
5872     return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
5873
5874   return SDValue();
5875 }
5876
5877 SDValue DAGCombiner::visitFDIV(SDNode *N) {
5878   SDValue N0 = N->getOperand(0);
5879   SDValue N1 = N->getOperand(1);
5880   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5881   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5882   EVT VT = N->getValueType(0);
5883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5884
5885   // fold vector ops
5886   if (VT.isVector()) {
5887     SDValue FoldedVOp = SimplifyVBinOp(N);
5888     if (FoldedVOp.getNode()) return FoldedVOp;
5889   }
5890
5891   // fold (fdiv c1, c2) -> c1/c2
5892   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5893     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5894
5895   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
5896   if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) {
5897     // Compute the reciprocal 1.0 / c2.
5898     APFloat N1APF = N1CFP->getValueAPF();
5899     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
5900     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
5901     // Only do the transform if the reciprocal is a legal fp immediate that
5902     // isn't too nasty (eg NaN, denormal, ...).
5903     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
5904         (!LegalOperations ||
5905          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
5906          // backend)... we should handle this gracefully after Legalize.
5907          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
5908          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
5909          TLI.isFPImmLegal(Recip, VT)))
5910       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
5911                          DAG.getConstantFP(Recip, VT));
5912   }
5913
5914   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5915   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5916                                        &DAG.getTarget().Options)) {
5917     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
5918                                          &DAG.getTarget().Options)) {
5919       // Both can be negated for free, check to see if at least one is cheaper
5920       // negated.
5921       if (LHSNeg == 2 || RHSNeg == 2)
5922         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5923                            GetNegatedExpression(N0, DAG, LegalOperations),
5924                            GetNegatedExpression(N1, DAG, LegalOperations));
5925     }
5926   }
5927
5928   return SDValue();
5929 }
5930
5931 SDValue DAGCombiner::visitFREM(SDNode *N) {
5932   SDValue N0 = N->getOperand(0);
5933   SDValue N1 = N->getOperand(1);
5934   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5935   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5936   EVT VT = N->getValueType(0);
5937
5938   // fold (frem c1, c2) -> fmod(c1,c2)
5939   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5940     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5941
5942   return SDValue();
5943 }
5944
5945 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5946   SDValue N0 = N->getOperand(0);
5947   SDValue N1 = N->getOperand(1);
5948   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5949   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5950   EVT VT = N->getValueType(0);
5951
5952   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
5953     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5954
5955   if (N1CFP) {
5956     const APFloat& V = N1CFP->getValueAPF();
5957     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
5958     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5959     if (!V.isNegative()) {
5960       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5961         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5962     } else {
5963       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5964         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5965                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5966     }
5967   }
5968
5969   // copysign(fabs(x), y) -> copysign(x, y)
5970   // copysign(fneg(x), y) -> copysign(x, y)
5971   // copysign(copysign(x,z), y) -> copysign(x, y)
5972   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5973       N0.getOpcode() == ISD::FCOPYSIGN)
5974     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5975                        N0.getOperand(0), N1);
5976
5977   // copysign(x, abs(y)) -> abs(x)
5978   if (N1.getOpcode() == ISD::FABS)
5979     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5980
5981   // copysign(x, copysign(y,z)) -> copysign(x, z)
5982   if (N1.getOpcode() == ISD::FCOPYSIGN)
5983     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5984                        N0, N1.getOperand(1));
5985
5986   // copysign(x, fp_extend(y)) -> copysign(x, y)
5987   // copysign(x, fp_round(y)) -> copysign(x, y)
5988   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5989     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5990                        N0, N1.getOperand(0));
5991
5992   return SDValue();
5993 }
5994
5995 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5996   SDValue N0 = N->getOperand(0);
5997   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5998   EVT VT = N->getValueType(0);
5999   EVT OpVT = N0.getValueType();
6000
6001   // fold (sint_to_fp c1) -> c1fp
6002   if (N0C && OpVT != MVT::ppcf128 &&
6003       // ...but only if the target supports immediate floating-point values
6004       (!LegalOperations ||
6005        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6006     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6007
6008   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6009   // but UINT_TO_FP is legal on this target, try to convert.
6010   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6011       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6012     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6013     if (DAG.SignBitIsZero(N0))
6014       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6015   }
6016
6017   // The next optimizations are desireable only if SELECT_CC can be lowered.
6018   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6019   // having to say they don't support SELECT_CC on every type the DAG knows
6020   // about, since there is no way to mark an opcode illegal at all value types
6021   // (See also visitSELECT)
6022   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6023     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6024     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6025         !VT.isVector() &&
6026         (!LegalOperations ||
6027          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6028       SDValue Ops[] =
6029         { N0.getOperand(0), N0.getOperand(1),
6030           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6031           N0.getOperand(2) };
6032       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6033     }
6034
6035     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6036     //      (select_cc x, y, 1.0, 0.0,, cc)
6037     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6038         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6039         (!LegalOperations ||
6040          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6041       SDValue Ops[] =
6042         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6043           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6044           N0.getOperand(0).getOperand(2) };
6045       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6046     }
6047   }
6048
6049   return SDValue();
6050 }
6051
6052 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6053   SDValue N0 = N->getOperand(0);
6054   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6055   EVT VT = N->getValueType(0);
6056   EVT OpVT = N0.getValueType();
6057
6058   // fold (uint_to_fp c1) -> c1fp
6059   if (N0C && OpVT != MVT::ppcf128 &&
6060       // ...but only if the target supports immediate floating-point values
6061       (!LegalOperations ||
6062        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6063     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6064
6065   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6066   // but SINT_TO_FP is legal on this target, try to convert.
6067   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6068       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6069     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6070     if (DAG.SignBitIsZero(N0))
6071       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6072   }
6073
6074   // The next optimizations are desireable only if SELECT_CC can be lowered.
6075   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6076   // having to say they don't support SELECT_CC on every type the DAG knows
6077   // about, since there is no way to mark an opcode illegal at all value types
6078   // (See also visitSELECT)
6079   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6080     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6081
6082     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6083         (!LegalOperations ||
6084          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6085       SDValue Ops[] =
6086         { N0.getOperand(0), N0.getOperand(1),
6087           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6088           N0.getOperand(2) };
6089       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6090     }
6091   }
6092
6093   return SDValue();
6094 }
6095
6096 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6097   SDValue N0 = N->getOperand(0);
6098   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6099   EVT VT = N->getValueType(0);
6100
6101   // fold (fp_to_sint c1fp) -> c1
6102   if (N0CFP)
6103     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6104
6105   return SDValue();
6106 }
6107
6108 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6109   SDValue N0 = N->getOperand(0);
6110   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6111   EVT VT = N->getValueType(0);
6112
6113   // fold (fp_to_uint c1fp) -> c1
6114   if (N0CFP && VT != MVT::ppcf128)
6115     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6116
6117   return SDValue();
6118 }
6119
6120 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6121   SDValue N0 = N->getOperand(0);
6122   SDValue N1 = N->getOperand(1);
6123   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6124   EVT VT = N->getValueType(0);
6125
6126   // fold (fp_round c1fp) -> c1fp
6127   if (N0CFP && N0.getValueType() != MVT::ppcf128)
6128     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6129
6130   // fold (fp_round (fp_extend x)) -> x
6131   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6132     return N0.getOperand(0);
6133
6134   // fold (fp_round (fp_round x)) -> (fp_round x)
6135   if (N0.getOpcode() == ISD::FP_ROUND) {
6136     // This is a value preserving truncation if both round's are.
6137     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6138                    N0.getNode()->getConstantOperandVal(1) == 1;
6139     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6140                        DAG.getIntPtrConstant(IsTrunc));
6141   }
6142
6143   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6144   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6145     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6146                               N0.getOperand(0), N1);
6147     AddToWorkList(Tmp.getNode());
6148     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6149                        Tmp, N0.getOperand(1));
6150   }
6151
6152   return SDValue();
6153 }
6154
6155 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6156   SDValue N0 = N->getOperand(0);
6157   EVT VT = N->getValueType(0);
6158   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6159   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6160
6161   // fold (fp_round_inreg c1fp) -> c1fp
6162   if (N0CFP && isTypeLegal(EVT)) {
6163     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6164     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6165   }
6166
6167   return SDValue();
6168 }
6169
6170 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6171   SDValue N0 = N->getOperand(0);
6172   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6173   EVT VT = N->getValueType(0);
6174
6175   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6176   if (N->hasOneUse() &&
6177       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6178     return SDValue();
6179
6180   // fold (fp_extend c1fp) -> c1fp
6181   if (N0CFP && VT != MVT::ppcf128)
6182     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6183
6184   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6185   // value of X.
6186   if (N0.getOpcode() == ISD::FP_ROUND
6187       && N0.getNode()->getConstantOperandVal(1) == 1) {
6188     SDValue In = N0.getOperand(0);
6189     if (In.getValueType() == VT) return In;
6190     if (VT.bitsLT(In.getValueType()))
6191       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6192                          In, N0.getOperand(1));
6193     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6194   }
6195
6196   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6197   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6198       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6199        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6200     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6201     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6202                                      LN0->getChain(),
6203                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6204                                      N0.getValueType(),
6205                                      LN0->isVolatile(), LN0->isNonTemporal(),
6206                                      LN0->getAlignment());
6207     CombineTo(N, ExtLoad);
6208     CombineTo(N0.getNode(),
6209               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6210                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6211               ExtLoad.getValue(1));
6212     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6213   }
6214
6215   return SDValue();
6216 }
6217
6218 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6219   SDValue N0 = N->getOperand(0);
6220   EVT VT = N->getValueType(0);
6221
6222   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6223                          &DAG.getTarget().Options))
6224     return GetNegatedExpression(N0, DAG, LegalOperations);
6225
6226   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6227   // constant pool values.
6228   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6229       !VT.isVector() &&
6230       N0.getNode()->hasOneUse() &&
6231       N0.getOperand(0).getValueType().isInteger()) {
6232     SDValue Int = N0.getOperand(0);
6233     EVT IntVT = Int.getValueType();
6234     if (IntVT.isInteger() && !IntVT.isVector()) {
6235       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6236               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6237       AddToWorkList(Int.getNode());
6238       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6239                          VT, Int);
6240     }
6241   }
6242
6243   return SDValue();
6244 }
6245
6246 SDValue DAGCombiner::visitFABS(SDNode *N) {
6247   SDValue N0 = N->getOperand(0);
6248   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6249   EVT VT = N->getValueType(0);
6250
6251   // fold (fabs c1) -> fabs(c1)
6252   if (N0CFP && VT != MVT::ppcf128)
6253     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6254   // fold (fabs (fabs x)) -> (fabs x)
6255   if (N0.getOpcode() == ISD::FABS)
6256     return N->getOperand(0);
6257   // fold (fabs (fneg x)) -> (fabs x)
6258   // fold (fabs (fcopysign x, y)) -> (fabs x)
6259   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6260     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6261
6262   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6263   // constant pool values.
6264   if (!TLI.isFAbsFree(VT) && 
6265       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6266       N0.getOperand(0).getValueType().isInteger() &&
6267       !N0.getOperand(0).getValueType().isVector()) {
6268     SDValue Int = N0.getOperand(0);
6269     EVT IntVT = Int.getValueType();
6270     if (IntVT.isInteger() && !IntVT.isVector()) {
6271       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6272              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6273       AddToWorkList(Int.getNode());
6274       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6275                          N->getValueType(0), Int);
6276     }
6277   }
6278
6279   return SDValue();
6280 }
6281
6282 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6283   SDValue Chain = N->getOperand(0);
6284   SDValue N1 = N->getOperand(1);
6285   SDValue N2 = N->getOperand(2);
6286
6287   // If N is a constant we could fold this into a fallthrough or unconditional
6288   // branch. However that doesn't happen very often in normal code, because
6289   // Instcombine/SimplifyCFG should have handled the available opportunities.
6290   // If we did this folding here, it would be necessary to update the
6291   // MachineBasicBlock CFG, which is awkward.
6292
6293   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6294   // on the target.
6295   if (N1.getOpcode() == ISD::SETCC &&
6296       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
6297     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6298                        Chain, N1.getOperand(2),
6299                        N1.getOperand(0), N1.getOperand(1), N2);
6300   }
6301
6302   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6303       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6304        (N1.getOperand(0).hasOneUse() &&
6305         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6306     SDNode *Trunc = 0;
6307     if (N1.getOpcode() == ISD::TRUNCATE) {
6308       // Look pass the truncate.
6309       Trunc = N1.getNode();
6310       N1 = N1.getOperand(0);
6311     }
6312
6313     // Match this pattern so that we can generate simpler code:
6314     //
6315     //   %a = ...
6316     //   %b = and i32 %a, 2
6317     //   %c = srl i32 %b, 1
6318     //   brcond i32 %c ...
6319     //
6320     // into
6321     //
6322     //   %a = ...
6323     //   %b = and i32 %a, 2
6324     //   %c = setcc eq %b, 0
6325     //   brcond %c ...
6326     //
6327     // This applies only when the AND constant value has one bit set and the
6328     // SRL constant is equal to the log2 of the AND constant. The back-end is
6329     // smart enough to convert the result into a TEST/JMP sequence.
6330     SDValue Op0 = N1.getOperand(0);
6331     SDValue Op1 = N1.getOperand(1);
6332
6333     if (Op0.getOpcode() == ISD::AND &&
6334         Op1.getOpcode() == ISD::Constant) {
6335       SDValue AndOp1 = Op0.getOperand(1);
6336
6337       if (AndOp1.getOpcode() == ISD::Constant) {
6338         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6339
6340         if (AndConst.isPowerOf2() &&
6341             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6342           SDValue SetCC =
6343             DAG.getSetCC(N->getDebugLoc(),
6344                          TLI.getSetCCResultType(Op0.getValueType()),
6345                          Op0, DAG.getConstant(0, Op0.getValueType()),
6346                          ISD::SETNE);
6347
6348           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6349                                           MVT::Other, Chain, SetCC, N2);
6350           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6351           // will convert it back to (X & C1) >> C2.
6352           CombineTo(N, NewBRCond, false);
6353           // Truncate is dead.
6354           if (Trunc) {
6355             removeFromWorkList(Trunc);
6356             DAG.DeleteNode(Trunc);
6357           }
6358           // Replace the uses of SRL with SETCC
6359           WorkListRemover DeadNodes(*this);
6360           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6361           removeFromWorkList(N1.getNode());
6362           DAG.DeleteNode(N1.getNode());
6363           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6364         }
6365       }
6366     }
6367
6368     if (Trunc)
6369       // Restore N1 if the above transformation doesn't match.
6370       N1 = N->getOperand(1);
6371   }
6372
6373   // Transform br(xor(x, y)) -> br(x != y)
6374   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6375   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6376     SDNode *TheXor = N1.getNode();
6377     SDValue Op0 = TheXor->getOperand(0);
6378     SDValue Op1 = TheXor->getOperand(1);
6379     if (Op0.getOpcode() == Op1.getOpcode()) {
6380       // Avoid missing important xor optimizations.
6381       SDValue Tmp = visitXOR(TheXor);
6382       if (Tmp.getNode() && Tmp.getNode() != TheXor) {
6383         DEBUG(dbgs() << "\nReplacing.8 ";
6384               TheXor->dump(&DAG);
6385               dbgs() << "\nWith: ";
6386               Tmp.getNode()->dump(&DAG);
6387               dbgs() << '\n');
6388         WorkListRemover DeadNodes(*this);
6389         DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6390         removeFromWorkList(TheXor);
6391         DAG.DeleteNode(TheXor);
6392         return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6393                            MVT::Other, Chain, Tmp, N2);
6394       }
6395     }
6396
6397     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6398       bool Equal = false;
6399       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6400         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6401             Op0.getOpcode() == ISD::XOR) {
6402           TheXor = Op0.getNode();
6403           Equal = true;
6404         }
6405
6406       EVT SetCCVT = N1.getValueType();
6407       if (LegalTypes)
6408         SetCCVT = TLI.getSetCCResultType(SetCCVT);
6409       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6410                                    SetCCVT,
6411                                    Op0, Op1,
6412                                    Equal ? ISD::SETEQ : ISD::SETNE);
6413       // Replace the uses of XOR with SETCC
6414       WorkListRemover DeadNodes(*this);
6415       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6416       removeFromWorkList(N1.getNode());
6417       DAG.DeleteNode(N1.getNode());
6418       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6419                          MVT::Other, Chain, SetCC, N2);
6420     }
6421   }
6422
6423   return SDValue();
6424 }
6425
6426 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6427 //
6428 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6429   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6430   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6431
6432   // If N is a constant we could fold this into a fallthrough or unconditional
6433   // branch. However that doesn't happen very often in normal code, because
6434   // Instcombine/SimplifyCFG should have handled the available opportunities.
6435   // If we did this folding here, it would be necessary to update the
6436   // MachineBasicBlock CFG, which is awkward.
6437
6438   // Use SimplifySetCC to simplify SETCC's.
6439   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6440                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6441                                false);
6442   if (Simp.getNode()) AddToWorkList(Simp.getNode());
6443
6444   // fold to a simpler setcc
6445   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6446     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6447                        N->getOperand(0), Simp.getOperand(2),
6448                        Simp.getOperand(0), Simp.getOperand(1),
6449                        N->getOperand(4));
6450
6451   return SDValue();
6452 }
6453
6454 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6455 /// uses N as its base pointer and that N may be folded in the load / store
6456 /// addressing mode.
6457 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6458                                     SelectionDAG &DAG,
6459                                     const TargetLowering &TLI) {
6460   EVT VT;
6461   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6462     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6463       return false;
6464     VT = Use->getValueType(0);
6465   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6466     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6467       return false;
6468     VT = ST->getValue().getValueType();
6469   } else
6470     return false;
6471
6472   TargetLowering::AddrMode AM;
6473   if (N->getOpcode() == ISD::ADD) {
6474     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6475     if (Offset)
6476       // [reg +/- imm]
6477       AM.BaseOffs = Offset->getSExtValue();
6478     else
6479       // [reg +/- reg]
6480       AM.Scale = 1;
6481   } else if (N->getOpcode() == ISD::SUB) {
6482     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6483     if (Offset)
6484       // [reg +/- imm]
6485       AM.BaseOffs = -Offset->getSExtValue();
6486     else
6487       // [reg +/- reg]
6488       AM.Scale = 1;
6489   } else
6490     return false;
6491
6492   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6493 }
6494
6495 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6496 /// pre-indexed load / store when the base pointer is an add or subtract
6497 /// and it has other uses besides the load / store. After the
6498 /// transformation, the new indexed load / store has effectively folded
6499 /// the add / subtract in and all of its other uses are redirected to the
6500 /// new load / store.
6501 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6502   if (Level < AfterLegalizeDAG)
6503     return false;
6504
6505   bool isLoad = true;
6506   SDValue Ptr;
6507   EVT VT;
6508   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6509     if (LD->isIndexed())
6510       return false;
6511     VT = LD->getMemoryVT();
6512     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6513         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6514       return false;
6515     Ptr = LD->getBasePtr();
6516   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6517     if (ST->isIndexed())
6518       return false;
6519     VT = ST->getMemoryVT();
6520     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6521         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6522       return false;
6523     Ptr = ST->getBasePtr();
6524     isLoad = false;
6525   } else {
6526     return false;
6527   }
6528
6529   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6530   // out.  There is no reason to make this a preinc/predec.
6531   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6532       Ptr.getNode()->hasOneUse())
6533     return false;
6534
6535   // Ask the target to do addressing mode selection.
6536   SDValue BasePtr;
6537   SDValue Offset;
6538   ISD::MemIndexedMode AM = ISD::UNINDEXED;
6539   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6540     return false;
6541   // Don't create a indexed load / store with zero offset.
6542   if (isa<ConstantSDNode>(Offset) &&
6543       cast<ConstantSDNode>(Offset)->isNullValue())
6544     return false;
6545
6546   // Try turning it into a pre-indexed load / store except when:
6547   // 1) The new base ptr is a frame index.
6548   // 2) If N is a store and the new base ptr is either the same as or is a
6549   //    predecessor of the value being stored.
6550   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6551   //    that would create a cycle.
6552   // 4) All uses are load / store ops that use it as old base ptr.
6553
6554   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
6555   // (plus the implicit offset) to a register to preinc anyway.
6556   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6557     return false;
6558
6559   // Check #2.
6560   if (!isLoad) {
6561     SDValue Val = cast<StoreSDNode>(N)->getValue();
6562     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
6563       return false;
6564   }
6565
6566   // Now check for #3 and #4.
6567   bool RealUse = false;
6568
6569   // Caches for hasPredecessorHelper
6570   SmallPtrSet<const SDNode *, 32> Visited;
6571   SmallVector<const SDNode *, 16> Worklist;
6572
6573   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6574          E = Ptr.getNode()->use_end(); I != E; ++I) {
6575     SDNode *Use = *I;
6576     if (Use == N)
6577       continue;
6578     if (N->hasPredecessorHelper(Use, Visited, Worklist))
6579       return false;
6580
6581     // If Ptr may be folded in addressing mode of other use, then it's
6582     // not profitable to do this transformation.
6583     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
6584       RealUse = true;
6585   }
6586
6587   if (!RealUse)
6588     return false;
6589
6590   SDValue Result;
6591   if (isLoad)
6592     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6593                                 BasePtr, Offset, AM);
6594   else
6595     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6596                                  BasePtr, Offset, AM);
6597   ++PreIndexedNodes;
6598   ++NodesCombined;
6599   DEBUG(dbgs() << "\nReplacing.4 ";
6600         N->dump(&DAG);
6601         dbgs() << "\nWith: ";
6602         Result.getNode()->dump(&DAG);
6603         dbgs() << '\n');
6604   WorkListRemover DeadNodes(*this);
6605   if (isLoad) {
6606     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6607     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6608   } else {
6609     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6610   }
6611
6612   // Finally, since the node is now dead, remove it from the graph.
6613   DAG.DeleteNode(N);
6614
6615   // Replace the uses of Ptr with uses of the updated base value.
6616   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
6617   removeFromWorkList(Ptr.getNode());
6618   DAG.DeleteNode(Ptr.getNode());
6619
6620   return true;
6621 }
6622
6623 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6624 /// add / sub of the base pointer node into a post-indexed load / store.
6625 /// The transformation folded the add / subtract into the new indexed
6626 /// load / store effectively and all of its uses are redirected to the
6627 /// new load / store.
6628 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6629   if (Level < AfterLegalizeDAG)
6630     return false;
6631
6632   bool isLoad = true;
6633   SDValue Ptr;
6634   EVT VT;
6635   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6636     if (LD->isIndexed())
6637       return false;
6638     VT = LD->getMemoryVT();
6639     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6640         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6641       return false;
6642     Ptr = LD->getBasePtr();
6643   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6644     if (ST->isIndexed())
6645       return false;
6646     VT = ST->getMemoryVT();
6647     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6648         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6649       return false;
6650     Ptr = ST->getBasePtr();
6651     isLoad = false;
6652   } else {
6653     return false;
6654   }
6655
6656   if (Ptr.getNode()->hasOneUse())
6657     return false;
6658
6659   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6660          E = Ptr.getNode()->use_end(); I != E; ++I) {
6661     SDNode *Op = *I;
6662     if (Op == N ||
6663         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6664       continue;
6665
6666     SDValue BasePtr;
6667     SDValue Offset;
6668     ISD::MemIndexedMode AM = ISD::UNINDEXED;
6669     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6670       // Don't create a indexed load / store with zero offset.
6671       if (isa<ConstantSDNode>(Offset) &&
6672           cast<ConstantSDNode>(Offset)->isNullValue())
6673         continue;
6674
6675       // Try turning it into a post-indexed load / store except when
6676       // 1) All uses are load / store ops that use it as base ptr (and
6677       //    it may be folded as addressing mmode).
6678       // 2) Op must be independent of N, i.e. Op is neither a predecessor
6679       //    nor a successor of N. Otherwise, if Op is folded that would
6680       //    create a cycle.
6681
6682       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6683         continue;
6684
6685       // Check for #1.
6686       bool TryNext = false;
6687       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6688              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6689         SDNode *Use = *II;
6690         if (Use == Ptr.getNode())
6691           continue;
6692
6693         // If all the uses are load / store addresses, then don't do the
6694         // transformation.
6695         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6696           bool RealUse = false;
6697           for (SDNode::use_iterator III = Use->use_begin(),
6698                  EEE = Use->use_end(); III != EEE; ++III) {
6699             SDNode *UseUse = *III;
6700             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 
6701               RealUse = true;
6702           }
6703
6704           if (!RealUse) {
6705             TryNext = true;
6706             break;
6707           }
6708         }
6709       }
6710
6711       if (TryNext)
6712         continue;
6713
6714       // Check for #2
6715       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
6716         SDValue Result = isLoad
6717           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6718                                BasePtr, Offset, AM)
6719           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6720                                 BasePtr, Offset, AM);
6721         ++PostIndexedNodes;
6722         ++NodesCombined;
6723         DEBUG(dbgs() << "\nReplacing.5 ";
6724               N->dump(&DAG);
6725               dbgs() << "\nWith: ";
6726               Result.getNode()->dump(&DAG);
6727               dbgs() << '\n');
6728         WorkListRemover DeadNodes(*this);
6729         if (isLoad) {
6730           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6731           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6732         } else {
6733           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6734         }
6735
6736         // Finally, since the node is now dead, remove it from the graph.
6737         DAG.DeleteNode(N);
6738
6739         // Replace the uses of Use with uses of the updated base value.
6740         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
6741                                       Result.getValue(isLoad ? 1 : 0));
6742         removeFromWorkList(Op);
6743         DAG.DeleteNode(Op);
6744         return true;
6745       }
6746     }
6747   }
6748
6749   return false;
6750 }
6751
6752 SDValue DAGCombiner::visitLOAD(SDNode *N) {
6753   LoadSDNode *LD  = cast<LoadSDNode>(N);
6754   SDValue Chain = LD->getChain();
6755   SDValue Ptr   = LD->getBasePtr();
6756
6757   // If load is not volatile and there are no uses of the loaded value (and
6758   // the updated indexed value in case of indexed loads), change uses of the
6759   // chain value into uses of the chain input (i.e. delete the dead load).
6760   if (!LD->isVolatile()) {
6761     if (N->getValueType(1) == MVT::Other) {
6762       // Unindexed loads.
6763       if (!N->hasAnyUseOfValue(0)) {
6764         // It's not safe to use the two value CombineTo variant here. e.g.
6765         // v1, chain2 = load chain1, loc
6766         // v2, chain3 = load chain2, loc
6767         // v3         = add v2, c
6768         // Now we replace use of chain2 with chain1.  This makes the second load
6769         // isomorphic to the one we are deleting, and thus makes this load live.
6770         DEBUG(dbgs() << "\nReplacing.6 ";
6771               N->dump(&DAG);
6772               dbgs() << "\nWith chain: ";
6773               Chain.getNode()->dump(&DAG);
6774               dbgs() << "\n");
6775         WorkListRemover DeadNodes(*this);
6776         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
6777
6778         if (N->use_empty()) {
6779           removeFromWorkList(N);
6780           DAG.DeleteNode(N);
6781         }
6782
6783         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6784       }
6785     } else {
6786       // Indexed loads.
6787       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
6788       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
6789         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
6790         DEBUG(dbgs() << "\nReplacing.7 ";
6791               N->dump(&DAG);
6792               dbgs() << "\nWith: ";
6793               Undef.getNode()->dump(&DAG);
6794               dbgs() << " and 2 other values\n");
6795         WorkListRemover DeadNodes(*this);
6796         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
6797         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
6798                                       DAG.getUNDEF(N->getValueType(1)));
6799         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
6800         removeFromWorkList(N);
6801         DAG.DeleteNode(N);
6802         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6803       }
6804     }
6805   }
6806
6807   // If this load is directly stored, replace the load value with the stored
6808   // value.
6809   // TODO: Handle store large -> read small portion.
6810   // TODO: Handle TRUNCSTORE/LOADEXT
6811   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
6812     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
6813       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
6814       if (PrevST->getBasePtr() == Ptr &&
6815           PrevST->getValue().getValueType() == N->getValueType(0))
6816       return CombineTo(N, Chain.getOperand(1), Chain);
6817     }
6818   }
6819
6820   // Try to infer better alignment information than the load already has.
6821   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
6822     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6823       if (Align > LD->getAlignment())
6824         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
6825                               LD->getValueType(0),
6826                               Chain, Ptr, LD->getPointerInfo(),
6827                               LD->getMemoryVT(),
6828                               LD->isVolatile(), LD->isNonTemporal(), Align);
6829     }
6830   }
6831
6832   if (CombinerAA) {
6833     // Walk up chain skipping non-aliasing memory nodes.
6834     SDValue BetterChain = FindBetterChain(N, Chain);
6835
6836     // If there is a better chain.
6837     if (Chain != BetterChain) {
6838       SDValue ReplLoad;
6839
6840       // Replace the chain to void dependency.
6841       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
6842         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
6843                                BetterChain, Ptr, LD->getPointerInfo(),
6844                                LD->isVolatile(), LD->isNonTemporal(),
6845                                LD->isInvariant(), LD->getAlignment());
6846       } else {
6847         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
6848                                   LD->getValueType(0),
6849                                   BetterChain, Ptr, LD->getPointerInfo(),
6850                                   LD->getMemoryVT(),
6851                                   LD->isVolatile(),
6852                                   LD->isNonTemporal(),
6853                                   LD->getAlignment());
6854       }
6855
6856       // Create token factor to keep old chain connected.
6857       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6858                                   MVT::Other, Chain, ReplLoad.getValue(1));
6859
6860       // Make sure the new and old chains are cleaned up.
6861       AddToWorkList(Token.getNode());
6862
6863       // Replace uses with load result and token factor. Don't add users
6864       // to work list.
6865       return CombineTo(N, ReplLoad.getValue(0), Token, false);
6866     }
6867   }
6868
6869   // Try transforming N to an indexed load.
6870   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6871     return SDValue(N, 0);
6872
6873   return SDValue();
6874 }
6875
6876 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
6877 /// load is having specific bytes cleared out.  If so, return the byte size
6878 /// being masked out and the shift amount.
6879 static std::pair<unsigned, unsigned>
6880 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
6881   std::pair<unsigned, unsigned> Result(0, 0);
6882
6883   // Check for the structure we're looking for.
6884   if (V->getOpcode() != ISD::AND ||
6885       !isa<ConstantSDNode>(V->getOperand(1)) ||
6886       !ISD::isNormalLoad(V->getOperand(0).getNode()))
6887     return Result;
6888
6889   // Check the chain and pointer.
6890   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
6891   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
6892
6893   // The store should be chained directly to the load or be an operand of a
6894   // tokenfactor.
6895   if (LD == Chain.getNode())
6896     ; // ok.
6897   else if (Chain->getOpcode() != ISD::TokenFactor)
6898     return Result; // Fail.
6899   else {
6900     bool isOk = false;
6901     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
6902       if (Chain->getOperand(i).getNode() == LD) {
6903         isOk = true;
6904         break;
6905       }
6906     if (!isOk) return Result;
6907   }
6908
6909   // This only handles simple types.
6910   if (V.getValueType() != MVT::i16 &&
6911       V.getValueType() != MVT::i32 &&
6912       V.getValueType() != MVT::i64)
6913     return Result;
6914
6915   // Check the constant mask.  Invert it so that the bits being masked out are
6916   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
6917   // follow the sign bit for uniformity.
6918   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
6919   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
6920   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
6921   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
6922   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
6923   if (NotMaskLZ == 64) return Result;  // All zero mask.
6924
6925   // See if we have a continuous run of bits.  If so, we have 0*1+0*
6926   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
6927     return Result;
6928
6929   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
6930   if (V.getValueType() != MVT::i64 && NotMaskLZ)
6931     NotMaskLZ -= 64-V.getValueSizeInBits();
6932
6933   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
6934   switch (MaskedBytes) {
6935   case 1:
6936   case 2:
6937   case 4: break;
6938   default: return Result; // All one mask, or 5-byte mask.
6939   }
6940
6941   // Verify that the first bit starts at a multiple of mask so that the access
6942   // is aligned the same as the access width.
6943   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
6944
6945   Result.first = MaskedBytes;
6946   Result.second = NotMaskTZ/8;
6947   return Result;
6948 }
6949
6950
6951 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6952 /// provides a value as specified by MaskInfo.  If so, replace the specified
6953 /// store with a narrower store of truncated IVal.
6954 static SDNode *
6955 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6956                                 SDValue IVal, StoreSDNode *St,
6957                                 DAGCombiner *DC) {
6958   unsigned NumBytes = MaskInfo.first;
6959   unsigned ByteShift = MaskInfo.second;
6960   SelectionDAG &DAG = DC->getDAG();
6961
6962   // Check to see if IVal is all zeros in the part being masked in by the 'or'
6963   // that uses this.  If not, this is not a replacement.
6964   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
6965                                   ByteShift*8, (ByteShift+NumBytes)*8);
6966   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
6967
6968   // Check that it is legal on the target to do this.  It is legal if the new
6969   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
6970   // legalization.
6971   MVT VT = MVT::getIntegerVT(NumBytes*8);
6972   if (!DC->isTypeLegal(VT))
6973     return 0;
6974
6975   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
6976   // shifted by ByteShift and truncated down to NumBytes.
6977   if (ByteShift)
6978     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
6979                        DAG.getConstant(ByteShift*8,
6980                                     DC->getShiftAmountTy(IVal.getValueType())));
6981
6982   // Figure out the offset for the store and the alignment of the access.
6983   unsigned StOffset;
6984   unsigned NewAlign = St->getAlignment();
6985
6986   if (DAG.getTargetLoweringInfo().isLittleEndian())
6987     StOffset = ByteShift;
6988   else
6989     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
6990
6991   SDValue Ptr = St->getBasePtr();
6992   if (StOffset) {
6993     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
6994                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
6995     NewAlign = MinAlign(NewAlign, StOffset);
6996   }
6997
6998   // Truncate down to the new size.
6999   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7000
7001   ++OpsNarrowed;
7002   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7003                       St->getPointerInfo().getWithOffset(StOffset),
7004                       false, false, NewAlign).getNode();
7005 }
7006
7007
7008 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7009 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7010 /// of the loaded bits, try narrowing the load and store if it would end up
7011 /// being a win for performance or code size.
7012 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7013   StoreSDNode *ST  = cast<StoreSDNode>(N);
7014   if (ST->isVolatile())
7015     return SDValue();
7016
7017   SDValue Chain = ST->getChain();
7018   SDValue Value = ST->getValue();
7019   SDValue Ptr   = ST->getBasePtr();
7020   EVT VT = Value.getValueType();
7021
7022   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7023     return SDValue();
7024
7025   unsigned Opc = Value.getOpcode();
7026
7027   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7028   // is a byte mask indicating a consecutive number of bytes, check to see if
7029   // Y is known to provide just those bytes.  If so, we try to replace the
7030   // load + replace + store sequence with a single (narrower) store, which makes
7031   // the load dead.
7032   if (Opc == ISD::OR) {
7033     std::pair<unsigned, unsigned> MaskedLoad;
7034     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7035     if (MaskedLoad.first)
7036       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7037                                                   Value.getOperand(1), ST,this))
7038         return SDValue(NewST, 0);
7039
7040     // Or is commutative, so try swapping X and Y.
7041     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7042     if (MaskedLoad.first)
7043       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7044                                                   Value.getOperand(0), ST,this))
7045         return SDValue(NewST, 0);
7046   }
7047
7048   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7049       Value.getOperand(1).getOpcode() != ISD::Constant)
7050     return SDValue();
7051
7052   SDValue N0 = Value.getOperand(0);
7053   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7054       Chain == SDValue(N0.getNode(), 1)) {
7055     LoadSDNode *LD = cast<LoadSDNode>(N0);
7056     if (LD->getBasePtr() != Ptr ||
7057         LD->getPointerInfo().getAddrSpace() !=
7058         ST->getPointerInfo().getAddrSpace())
7059       return SDValue();
7060
7061     // Find the type to narrow it the load / op / store to.
7062     SDValue N1 = Value.getOperand(1);
7063     unsigned BitWidth = N1.getValueSizeInBits();
7064     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7065     if (Opc == ISD::AND)
7066       Imm ^= APInt::getAllOnesValue(BitWidth);
7067     if (Imm == 0 || Imm.isAllOnesValue())
7068       return SDValue();
7069     unsigned ShAmt = Imm.countTrailingZeros();
7070     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7071     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7072     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7073     while (NewBW < BitWidth &&
7074            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7075              TLI.isNarrowingProfitable(VT, NewVT))) {
7076       NewBW = NextPowerOf2(NewBW);
7077       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7078     }
7079     if (NewBW >= BitWidth)
7080       return SDValue();
7081
7082     // If the lsb changed does not start at the type bitwidth boundary,
7083     // start at the previous one.
7084     if (ShAmt % NewBW)
7085       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7086     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
7087     if ((Imm & Mask) == Imm) {
7088       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7089       if (Opc == ISD::AND)
7090         NewImm ^= APInt::getAllOnesValue(NewBW);
7091       uint64_t PtrOff = ShAmt / 8;
7092       // For big endian targets, we need to adjust the offset to the pointer to
7093       // load the correct bytes.
7094       if (TLI.isBigEndian())
7095         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7096
7097       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7098       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7099       if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
7100         return SDValue();
7101
7102       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7103                                    Ptr.getValueType(), Ptr,
7104                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7105       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7106                                   LD->getChain(), NewPtr,
7107                                   LD->getPointerInfo().getWithOffset(PtrOff),
7108                                   LD->isVolatile(), LD->isNonTemporal(),
7109                                   LD->isInvariant(), NewAlign);
7110       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7111                                    DAG.getConstant(NewImm, NewVT));
7112       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7113                                    NewVal, NewPtr,
7114                                    ST->getPointerInfo().getWithOffset(PtrOff),
7115                                    false, false, NewAlign);
7116
7117       AddToWorkList(NewPtr.getNode());
7118       AddToWorkList(NewLD.getNode());
7119       AddToWorkList(NewVal.getNode());
7120       WorkListRemover DeadNodes(*this);
7121       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7122       ++OpsNarrowed;
7123       return NewST;
7124     }
7125   }
7126
7127   return SDValue();
7128 }
7129
7130 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7131 /// if the load value isn't used by any other operations, then consider
7132 /// transforming the pair to integer load / store operations if the target
7133 /// deems the transformation profitable.
7134 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7135   StoreSDNode *ST  = cast<StoreSDNode>(N);
7136   SDValue Chain = ST->getChain();
7137   SDValue Value = ST->getValue();
7138   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7139       Value.hasOneUse() &&
7140       Chain == SDValue(Value.getNode(), 1)) {
7141     LoadSDNode *LD = cast<LoadSDNode>(Value);
7142     EVT VT = LD->getMemoryVT();
7143     if (!VT.isFloatingPoint() ||
7144         VT != ST->getMemoryVT() ||
7145         LD->isNonTemporal() ||
7146         ST->isNonTemporal() ||
7147         LD->getPointerInfo().getAddrSpace() != 0 ||
7148         ST->getPointerInfo().getAddrSpace() != 0)
7149       return SDValue();
7150
7151     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7152     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7153         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7154         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7155         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7156       return SDValue();
7157
7158     unsigned LDAlign = LD->getAlignment();
7159     unsigned STAlign = ST->getAlignment();
7160     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7161     unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
7162     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7163       return SDValue();
7164
7165     SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7166                                 LD->getChain(), LD->getBasePtr(),
7167                                 LD->getPointerInfo(),
7168                                 false, false, false, LDAlign);
7169
7170     SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7171                                  NewLD, ST->getBasePtr(),
7172                                  ST->getPointerInfo(),
7173                                  false, false, STAlign);
7174
7175     AddToWorkList(NewLD.getNode());
7176     AddToWorkList(NewST.getNode());
7177     WorkListRemover DeadNodes(*this);
7178     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7179     ++LdStFP2Int;
7180     return NewST;
7181   }
7182
7183   return SDValue();
7184 }
7185
7186 SDValue DAGCombiner::visitSTORE(SDNode *N) {
7187   StoreSDNode *ST  = cast<StoreSDNode>(N);
7188   SDValue Chain = ST->getChain();
7189   SDValue Value = ST->getValue();
7190   SDValue Ptr   = ST->getBasePtr();
7191
7192   // If this is a store of a bit convert, store the input value if the
7193   // resultant store does not need a higher alignment than the original.
7194   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
7195       ST->isUnindexed()) {
7196     unsigned OrigAlign = ST->getAlignment();
7197     EVT SVT = Value.getOperand(0).getValueType();
7198     unsigned Align = TLI.getTargetData()->
7199       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
7200     if (Align <= OrigAlign &&
7201         ((!LegalOperations && !ST->isVolatile()) ||
7202          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
7203       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7204                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
7205                           ST->isNonTemporal(), OrigAlign);
7206   }
7207
7208   // Turn 'store undef, Ptr' -> nothing.
7209   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
7210     return Chain;
7211
7212   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
7213   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
7214     // NOTE: If the original store is volatile, this transform must not increase
7215     // the number of stores.  For example, on x86-32 an f64 can be stored in one
7216     // processor operation but an i64 (which is not legal) requires two.  So the
7217     // transform should not be done in this case.
7218     if (Value.getOpcode() != ISD::TargetConstantFP) {
7219       SDValue Tmp;
7220       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
7221       default: llvm_unreachable("Unknown FP type");
7222       case MVT::f16:    // We don't do this for these yet.
7223       case MVT::f80:
7224       case MVT::f128:
7225       case MVT::ppcf128:
7226         break;
7227       case MVT::f32:
7228         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
7229             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7230           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
7231                               bitcastToAPInt().getZExtValue(), MVT::i32);
7232           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7233                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
7234                               ST->isNonTemporal(), ST->getAlignment());
7235         }
7236         break;
7237       case MVT::f64:
7238         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
7239              !ST->isVolatile()) ||
7240             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
7241           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
7242                                 getZExtValue(), MVT::i64);
7243           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7244                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
7245                               ST->isNonTemporal(), ST->getAlignment());
7246         }
7247
7248         if (!ST->isVolatile() &&
7249             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7250           // Many FP stores are not made apparent until after legalize, e.g. for
7251           // argument passing.  Since this is so common, custom legalize the
7252           // 64-bit integer store into two 32-bit stores.
7253           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
7254           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
7255           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
7256           if (TLI.isBigEndian()) std::swap(Lo, Hi);
7257
7258           unsigned Alignment = ST->getAlignment();
7259           bool isVolatile = ST->isVolatile();
7260           bool isNonTemporal = ST->isNonTemporal();
7261
7262           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
7263                                      Ptr, ST->getPointerInfo(),
7264                                      isVolatile, isNonTemporal,
7265                                      ST->getAlignment());
7266           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
7267                             DAG.getConstant(4, Ptr.getValueType()));
7268           Alignment = MinAlign(Alignment, 4U);
7269           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
7270                                      Ptr, ST->getPointerInfo().getWithOffset(4),
7271                                      isVolatile, isNonTemporal,
7272                                      Alignment);
7273           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7274                              St0, St1);
7275         }
7276
7277         break;
7278       }
7279     }
7280   }
7281
7282   // Try to infer better alignment information than the store already has.
7283   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
7284     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7285       if (Align > ST->getAlignment())
7286         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
7287                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7288                                  ST->isVolatile(), ST->isNonTemporal(), Align);
7289     }
7290   }
7291
7292   // Try transforming a pair floating point load / store ops to integer
7293   // load / store ops.
7294   SDValue NewST = TransformFPLoadStorePair(N);
7295   if (NewST.getNode())
7296     return NewST;
7297
7298   if (CombinerAA) {
7299     // Walk up chain skipping non-aliasing memory nodes.
7300     SDValue BetterChain = FindBetterChain(N, Chain);
7301
7302     // If there is a better chain.
7303     if (Chain != BetterChain) {
7304       SDValue ReplStore;
7305
7306       // Replace the chain to avoid dependency.
7307       if (ST->isTruncatingStore()) {
7308         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7309                                       ST->getPointerInfo(),
7310                                       ST->getMemoryVT(), ST->isVolatile(),
7311                                       ST->isNonTemporal(), ST->getAlignment());
7312       } else {
7313         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7314                                  ST->getPointerInfo(),
7315                                  ST->isVolatile(), ST->isNonTemporal(),
7316                                  ST->getAlignment());
7317       }
7318
7319       // Create token to keep both nodes around.
7320       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7321                                   MVT::Other, Chain, ReplStore);
7322
7323       // Make sure the new and old chains are cleaned up.
7324       AddToWorkList(Token.getNode());
7325
7326       // Don't add users to work list.
7327       return CombineTo(N, Token, false);
7328     }
7329   }
7330
7331   // Try transforming N to an indexed store.
7332   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7333     return SDValue(N, 0);
7334
7335   // FIXME: is there such a thing as a truncating indexed store?
7336   if (ST->isTruncatingStore() && ST->isUnindexed() &&
7337       Value.getValueType().isInteger()) {
7338     // See if we can simplify the input to this truncstore with knowledge that
7339     // only the low bits are being used.  For example:
7340     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
7341     SDValue Shorter =
7342       GetDemandedBits(Value,
7343                       APInt::getLowBitsSet(
7344                         Value.getValueType().getScalarType().getSizeInBits(),
7345                         ST->getMemoryVT().getScalarType().getSizeInBits()));
7346     AddToWorkList(Value.getNode());
7347     if (Shorter.getNode())
7348       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
7349                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7350                                ST->isVolatile(), ST->isNonTemporal(),
7351                                ST->getAlignment());
7352
7353     // Otherwise, see if we can simplify the operation with
7354     // SimplifyDemandedBits, which only works if the value has a single use.
7355     if (SimplifyDemandedBits(Value,
7356                         APInt::getLowBitsSet(
7357                           Value.getValueType().getScalarType().getSizeInBits(),
7358                           ST->getMemoryVT().getScalarType().getSizeInBits())))
7359       return SDValue(N, 0);
7360   }
7361
7362   // If this is a load followed by a store to the same location, then the store
7363   // is dead/noop.
7364   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
7365     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
7366         ST->isUnindexed() && !ST->isVolatile() &&
7367         // There can't be any side effects between the load and store, such as
7368         // a call or store.
7369         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
7370       // The store is dead, remove it.
7371       return Chain;
7372     }
7373   }
7374
7375   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
7376   // truncating store.  We can do this even if this is already a truncstore.
7377   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
7378       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
7379       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
7380                             ST->getMemoryVT())) {
7381     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7382                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7383                              ST->isVolatile(), ST->isNonTemporal(),
7384                              ST->getAlignment());
7385   }
7386
7387   return ReduceLoadOpStoreWidth(N);
7388 }
7389
7390 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
7391   SDValue InVec = N->getOperand(0);
7392   SDValue InVal = N->getOperand(1);
7393   SDValue EltNo = N->getOperand(2);
7394   DebugLoc dl = N->getDebugLoc();
7395
7396   // If the inserted element is an UNDEF, just use the input vector.
7397   if (InVal.getOpcode() == ISD::UNDEF)
7398     return InVec;
7399
7400   EVT VT = InVec.getValueType();
7401
7402   // If we can't generate a legal BUILD_VECTOR, exit
7403   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
7404     return SDValue();
7405
7406   // Check that we know which element is being inserted
7407   if (!isa<ConstantSDNode>(EltNo))
7408     return SDValue();
7409   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7410
7411   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
7412   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
7413   // vector elements.
7414   SmallVector<SDValue, 8> Ops;
7415   if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
7416     Ops.append(InVec.getNode()->op_begin(),
7417                InVec.getNode()->op_end());
7418   } else if (InVec.getOpcode() == ISD::UNDEF) {
7419     unsigned NElts = VT.getVectorNumElements();
7420     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
7421   } else {
7422     return SDValue();
7423   }
7424
7425   // Insert the element
7426   if (Elt < Ops.size()) {
7427     // All the operands of BUILD_VECTOR must have the same type;
7428     // we enforce that here.
7429     EVT OpVT = Ops[0].getValueType();
7430     if (InVal.getValueType() != OpVT)
7431       InVal = OpVT.bitsGT(InVal.getValueType()) ?
7432                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
7433                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
7434     Ops[Elt] = InVal;
7435   }
7436
7437   // Return the new vector
7438   return DAG.getNode(ISD::BUILD_VECTOR, dl,
7439                      VT, &Ops[0], Ops.size());
7440 }
7441
7442 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
7443   // (vextract (scalar_to_vector val, 0) -> val
7444   SDValue InVec = N->getOperand(0);
7445   EVT VT = InVec.getValueType();
7446   EVT NVT = N->getValueType(0);
7447
7448   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7449     // Check if the result type doesn't match the inserted element type. A
7450     // SCALAR_TO_VECTOR may truncate the inserted element and the
7451     // EXTRACT_VECTOR_ELT may widen the extracted vector.
7452     SDValue InOp = InVec.getOperand(0);
7453     if (InOp.getValueType() != NVT) {
7454       assert(InOp.getValueType().isInteger() && NVT.isInteger());
7455       return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
7456     }
7457     return InOp;
7458   }
7459
7460   SDValue EltNo = N->getOperand(1);
7461   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
7462
7463   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
7464   // We only perform this optimization before the op legalization phase because
7465   // we may introduce new vector instructions which are not backed by TD patterns.
7466   // For example on AVX, extracting elements from a wide vector without using
7467   // extract_subvector.
7468   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
7469       && ConstEltNo && !LegalOperations) {
7470     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7471     int NumElem = VT.getVectorNumElements();
7472     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
7473     // Find the new index to extract from.
7474     int OrigElt = SVOp->getMaskElt(Elt);
7475
7476     // Extracting an undef index is undef.
7477     if (OrigElt == -1)
7478       return DAG.getUNDEF(NVT);
7479
7480     // Select the right vector half to extract from.
7481     if (OrigElt < NumElem) {
7482       InVec = InVec->getOperand(0);
7483     } else {
7484       InVec = InVec->getOperand(1);
7485       OrigElt -= NumElem;
7486     }
7487
7488     EVT IndexTy = N->getOperand(1).getValueType();
7489     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
7490                        InVec, DAG.getConstant(OrigElt, IndexTy));
7491   }
7492
7493   // Perform only after legalization to ensure build_vector / vector_shuffle
7494   // optimizations have already been done.
7495   if (!LegalOperations) return SDValue();
7496
7497   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
7498   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
7499   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
7500
7501   if (ConstEltNo) {
7502     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7503     bool NewLoad = false;
7504     bool BCNumEltsChanged = false;
7505     EVT ExtVT = VT.getVectorElementType();
7506     EVT LVT = ExtVT;
7507
7508     // If the result of load has to be truncated, then it's not necessarily
7509     // profitable.
7510     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
7511       return SDValue();
7512
7513     if (InVec.getOpcode() == ISD::BITCAST) {
7514       // Don't duplicate a load with other uses.
7515       if (!InVec.hasOneUse())
7516         return SDValue();
7517
7518       EVT BCVT = InVec.getOperand(0).getValueType();
7519       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
7520         return SDValue();
7521       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
7522         BCNumEltsChanged = true;
7523       InVec = InVec.getOperand(0);
7524       ExtVT = BCVT.getVectorElementType();
7525       NewLoad = true;
7526     }
7527
7528     LoadSDNode *LN0 = NULL;
7529     const ShuffleVectorSDNode *SVN = NULL;
7530     if (ISD::isNormalLoad(InVec.getNode())) {
7531       LN0 = cast<LoadSDNode>(InVec);
7532     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7533                InVec.getOperand(0).getValueType() == ExtVT &&
7534                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
7535       // Don't duplicate a load with other uses.
7536       if (!InVec.hasOneUse())
7537         return SDValue();
7538
7539       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
7540     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
7541       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
7542       // =>
7543       // (load $addr+1*size)
7544
7545       // Don't duplicate a load with other uses.
7546       if (!InVec.hasOneUse())
7547         return SDValue();
7548
7549       // If the bit convert changed the number of elements, it is unsafe
7550       // to examine the mask.
7551       if (BCNumEltsChanged)
7552         return SDValue();
7553
7554       // Select the input vector, guarding against out of range extract vector.
7555       unsigned NumElems = VT.getVectorNumElements();
7556       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
7557       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
7558
7559       if (InVec.getOpcode() == ISD::BITCAST) {
7560         // Don't duplicate a load with other uses.
7561         if (!InVec.hasOneUse())
7562           return SDValue();
7563
7564         InVec = InVec.getOperand(0);
7565       }
7566       if (ISD::isNormalLoad(InVec.getNode())) {
7567         LN0 = cast<LoadSDNode>(InVec);
7568         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
7569       }
7570     }
7571
7572     // Make sure we found a non-volatile load and the extractelement is
7573     // the only use.
7574     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
7575       return SDValue();
7576
7577     // If Idx was -1 above, Elt is going to be -1, so just return undef.
7578     if (Elt == -1)
7579       return DAG.getUNDEF(LVT);
7580
7581     unsigned Align = LN0->getAlignment();
7582     if (NewLoad) {
7583       // Check the resultant load doesn't need a higher alignment than the
7584       // original load.
7585       unsigned NewAlign =
7586         TLI.getTargetData()
7587             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
7588
7589       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
7590         return SDValue();
7591
7592       Align = NewAlign;
7593     }
7594
7595     SDValue NewPtr = LN0->getBasePtr();
7596     unsigned PtrOff = 0;
7597
7598     if (Elt) {
7599       PtrOff = LVT.getSizeInBits() * Elt / 8;
7600       EVT PtrType = NewPtr.getValueType();
7601       if (TLI.isBigEndian())
7602         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
7603       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
7604                            DAG.getConstant(PtrOff, PtrType));
7605     }
7606
7607     // The replacement we need to do here is a little tricky: we need to
7608     // replace an extractelement of a load with a load.
7609     // Use ReplaceAllUsesOfValuesWith to do the replacement.
7610     // Note that this replacement assumes that the extractvalue is the only
7611     // use of the load; that's okay because we don't want to perform this
7612     // transformation in other cases anyway.
7613     SDValue Load;
7614     SDValue Chain;
7615     if (NVT.bitsGT(LVT)) {
7616       // If the result type of vextract is wider than the load, then issue an
7617       // extending load instead.
7618       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
7619         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
7620       Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
7621                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
7622                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
7623       Chain = Load.getValue(1);
7624     } else {
7625       Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
7626                          LN0->getPointerInfo().getWithOffset(PtrOff),
7627                          LN0->isVolatile(), LN0->isNonTemporal(), 
7628                          LN0->isInvariant(), Align);
7629       Chain = Load.getValue(1);
7630       if (NVT.bitsLT(LVT))
7631         Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
7632       else
7633         Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
7634     }
7635     WorkListRemover DeadNodes(*this);
7636     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
7637     SDValue To[] = { Load, Chain };
7638     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7639     // Since we're explcitly calling ReplaceAllUses, add the new node to the
7640     // worklist explicitly as well.
7641     AddToWorkList(Load.getNode());
7642     AddUsersToWorkList(Load.getNode()); // Add users too
7643     // Make sure to revisit this node to clean it up; it will usually be dead.
7644     AddToWorkList(N);
7645     return SDValue(N, 0);
7646   }
7647
7648   return SDValue();
7649 }
7650
7651 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
7652   unsigned NumInScalars = N->getNumOperands();
7653   DebugLoc dl = N->getDebugLoc();
7654   EVT VT = N->getValueType(0);
7655
7656   // A vector built entirely of undefs is undef.
7657   if (ISD::allOperandsUndef(N))
7658     return DAG.getUNDEF(VT);
7659
7660   // Check to see if this is a BUILD_VECTOR of a bunch of values
7661   // which come from any_extend or zero_extend nodes. If so, we can create
7662   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
7663   // optimizations. We do not handle sign-extend because we can't fill the sign
7664   // using shuffles.
7665   EVT SourceType = MVT::Other;
7666   bool AllAnyExt = true;
7667
7668   for (unsigned i = 0; i != NumInScalars; ++i) {
7669     SDValue In = N->getOperand(i);
7670     // Ignore undef inputs.
7671     if (In.getOpcode() == ISD::UNDEF) continue;
7672
7673     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
7674     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
7675
7676     // Abort if the element is not an extension.
7677     if (!ZeroExt && !AnyExt) {
7678       SourceType = MVT::Other;
7679       break;
7680     }
7681
7682     // The input is a ZeroExt or AnyExt. Check the original type.
7683     EVT InTy = In.getOperand(0).getValueType();
7684
7685     // Check that all of the widened source types are the same.
7686     if (SourceType == MVT::Other)
7687       // First time.
7688       SourceType = InTy;
7689     else if (InTy != SourceType) {
7690       // Multiple income types. Abort.
7691       SourceType = MVT::Other;
7692       break;
7693     }
7694
7695     // Check if all of the extends are ANY_EXTENDs.
7696     AllAnyExt &= AnyExt;
7697   }
7698
7699   // In order to have valid types, all of the inputs must be extended from the
7700   // same source type and all of the inputs must be any or zero extend.
7701   // Scalar sizes must be a power of two.
7702   EVT OutScalarTy = N->getValueType(0).getScalarType();
7703   bool ValidTypes = SourceType != MVT::Other &&
7704                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
7705                  isPowerOf2_32(SourceType.getSizeInBits());
7706
7707   // We perform this optimization post type-legalization because
7708   // the type-legalizer often scalarizes integer-promoted vectors.
7709   // Performing this optimization before may create bit-casts which
7710   // will be type-legalized to complex code sequences.
7711   // We perform this optimization only before the operation legalizer because we
7712   // may introduce illegal operations.
7713   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
7714   // turn into a single shuffle instruction.
7715   if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) &&
7716       ValidTypes) {
7717     bool isLE = TLI.isLittleEndian();
7718     unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
7719     assert(ElemRatio > 1 && "Invalid element size ratio");
7720     SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
7721                                  DAG.getConstant(0, SourceType);
7722
7723     unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements();
7724     SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
7725
7726     // Populate the new build_vector
7727     for (unsigned i=0; i < N->getNumOperands(); ++i) {
7728       SDValue Cast = N->getOperand(i);
7729       assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
7730               Cast.getOpcode() == ISD::ZERO_EXTEND ||
7731               Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
7732       SDValue In;
7733       if (Cast.getOpcode() == ISD::UNDEF)
7734         In = DAG.getUNDEF(SourceType);
7735       else
7736         In = Cast->getOperand(0);
7737       unsigned Index = isLE ? (i * ElemRatio) :
7738                               (i * ElemRatio + (ElemRatio - 1));
7739
7740       assert(Index < Ops.size() && "Invalid index");
7741       Ops[Index] = In;
7742     }
7743
7744     // The type of the new BUILD_VECTOR node.
7745     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
7746     assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() &&
7747            "Invalid vector size");
7748     // Check if the new vector type is legal.
7749     if (!isTypeLegal(VecVT)) return SDValue();
7750
7751     // Make the new BUILD_VECTOR.
7752     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7753                                  VecVT, &Ops[0], Ops.size());
7754
7755     // The new BUILD_VECTOR node has the potential to be further optimized.
7756     AddToWorkList(BV.getNode());
7757     // Bitcast to the desired type.
7758     return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
7759   }
7760
7761   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
7762   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
7763   // at most two distinct vectors, turn this into a shuffle node.
7764
7765   // May only combine to shuffle after legalize if shuffle is legal.
7766   if (LegalOperations &&
7767       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
7768     return SDValue();
7769
7770   SDValue VecIn1, VecIn2;
7771   for (unsigned i = 0; i != NumInScalars; ++i) {
7772     // Ignore undef inputs.
7773     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
7774
7775     // If this input is something other than a EXTRACT_VECTOR_ELT with a
7776     // constant index, bail out.
7777     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7778         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
7779       VecIn1 = VecIn2 = SDValue(0, 0);
7780       break;
7781     }
7782
7783     // We allow up to two distinct input vectors.
7784     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
7785     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
7786       continue;
7787
7788     if (VecIn1.getNode() == 0) {
7789       VecIn1 = ExtractedFromVec;
7790     } else if (VecIn2.getNode() == 0) {
7791       VecIn2 = ExtractedFromVec;
7792     } else {
7793       // Too many inputs.
7794       VecIn1 = VecIn2 = SDValue(0, 0);
7795       break;
7796     }
7797   }
7798
7799     // If everything is good, we can make a shuffle operation.
7800   if (VecIn1.getNode()) {
7801     SmallVector<int, 8> Mask;
7802     for (unsigned i = 0; i != NumInScalars; ++i) {
7803       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
7804         Mask.push_back(-1);
7805         continue;
7806       }
7807
7808       // If extracting from the first vector, just use the index directly.
7809       SDValue Extract = N->getOperand(i);
7810       SDValue ExtVal = Extract.getOperand(1);
7811       if (Extract.getOperand(0) == VecIn1) {
7812         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7813         if (ExtIndex > VT.getVectorNumElements())
7814           return SDValue();
7815
7816         Mask.push_back(ExtIndex);
7817         continue;
7818       }
7819
7820       // Otherwise, use InIdx + VecSize
7821       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7822       Mask.push_back(Idx+NumInScalars);
7823     }
7824
7825     // We can't generate a shuffle node with mismatched input and output types.
7826     // Attempt to transform a single input vector to the correct type.
7827     if ((VT != VecIn1.getValueType())) {
7828       // We don't support shuffeling between TWO values of different types.
7829       if (VecIn2.getNode() != 0)
7830         return SDValue();
7831
7832       // We only support widening of vectors which are half the size of the
7833       // output registers. For example XMM->YMM widening on X86 with AVX.
7834       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
7835         return SDValue();
7836
7837       // Widen the input vector by adding undef values.
7838       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7839                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
7840     }
7841
7842     // If VecIn2 is unused then change it to undef.
7843     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7844
7845     // Check that we were able to transform all incoming values to the same type.
7846     if (VecIn2.getValueType() != VecIn1.getValueType() ||
7847         VecIn1.getValueType() != VT)
7848           return SDValue();
7849
7850     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
7851     if (!isTypeLegal(VT))
7852       return SDValue();
7853
7854     // Return the new VECTOR_SHUFFLE node.
7855     SDValue Ops[2];
7856     Ops[0] = VecIn1;
7857     Ops[1] = VecIn2;
7858     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
7859   }
7860
7861   return SDValue();
7862 }
7863
7864 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
7865   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
7866   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
7867   // inputs come from at most two distinct vectors, turn this into a shuffle
7868   // node.
7869
7870   // If we only have one input vector, we don't need to do any concatenation.
7871   if (N->getNumOperands() == 1)
7872     return N->getOperand(0);
7873
7874   // Check if all of the operands are undefs.
7875   if (ISD::allOperandsUndef(N))
7876     return DAG.getUNDEF(N->getValueType(0));
7877
7878   return SDValue();
7879 }
7880
7881 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
7882   EVT NVT = N->getValueType(0);
7883   SDValue V = N->getOperand(0);
7884
7885   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
7886     // Handle only simple case where vector being inserted and vector
7887     // being extracted are of same type, and are half size of larger vectors.
7888     EVT BigVT = V->getOperand(0).getValueType();
7889     EVT SmallVT = V->getOperand(1).getValueType();
7890     if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
7891       return SDValue();
7892
7893     // Only handle cases where both indexes are constants with the same type.
7894     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7895     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
7896
7897     if (InsIdx && ExtIdx &&
7898         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
7899         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
7900       // Combine:
7901       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
7902       // Into:
7903       //    indices are equal => V1
7904       //    otherwise => (extract_subvec V1, ExtIdx)
7905       if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
7906         return V->getOperand(1);
7907       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
7908                          V->getOperand(0), N->getOperand(1));
7909     }
7910   }
7911
7912   return SDValue();
7913 }
7914
7915 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
7916   EVT VT = N->getValueType(0);
7917   unsigned NumElts = VT.getVectorNumElements();
7918
7919   SDValue N0 = N->getOperand(0);
7920   SDValue N1 = N->getOperand(1);
7921
7922   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
7923
7924   // Canonicalize shuffle undef, undef -> undef
7925   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
7926     return DAG.getUNDEF(VT);
7927
7928   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7929
7930   // Canonicalize shuffle v, v -> v, undef
7931   if (N0 == N1) {
7932     SmallVector<int, 8> NewMask;
7933     for (unsigned i = 0; i != NumElts; ++i) {
7934       int Idx = SVN->getMaskElt(i);
7935       if (Idx >= (int)NumElts) Idx -= NumElts;
7936       NewMask.push_back(Idx);
7937     }
7938     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
7939                                 &NewMask[0]);
7940   }
7941
7942   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
7943   if (N0.getOpcode() == ISD::UNDEF) {
7944     SmallVector<int, 8> NewMask;
7945     for (unsigned i = 0; i != NumElts; ++i) {
7946       int Idx = SVN->getMaskElt(i);
7947       if (Idx >= 0) {
7948         if (Idx < (int)NumElts)
7949           Idx += NumElts;
7950         else
7951           Idx -= NumElts;
7952       }
7953       NewMask.push_back(Idx);
7954     }
7955     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
7956                                 &NewMask[0]);
7957   }
7958
7959   // Remove references to rhs if it is undef
7960   if (N1.getOpcode() == ISD::UNDEF) {
7961     bool Changed = false;
7962     SmallVector<int, 8> NewMask;
7963     for (unsigned i = 0; i != NumElts; ++i) {
7964       int Idx = SVN->getMaskElt(i);
7965       if (Idx >= (int)NumElts) {
7966         Idx = -1;
7967         Changed = true;
7968       }
7969       NewMask.push_back(Idx);
7970     }
7971     if (Changed)
7972       return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
7973   }
7974
7975   // If it is a splat, check if the argument vector is another splat or a
7976   // build_vector with all scalar elements the same.
7977   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
7978     SDNode *V = N0.getNode();
7979
7980     // If this is a bit convert that changes the element type of the vector but
7981     // not the number of vector elements, look through it.  Be careful not to
7982     // look though conversions that change things like v4f32 to v2f64.
7983     if (V->getOpcode() == ISD::BITCAST) {
7984       SDValue ConvInput = V->getOperand(0);
7985       if (ConvInput.getValueType().isVector() &&
7986           ConvInput.getValueType().getVectorNumElements() == NumElts)
7987         V = ConvInput.getNode();
7988     }
7989
7990     if (V->getOpcode() == ISD::BUILD_VECTOR) {
7991       assert(V->getNumOperands() == NumElts &&
7992              "BUILD_VECTOR has wrong number of operands");
7993       SDValue Base;
7994       bool AllSame = true;
7995       for (unsigned i = 0; i != NumElts; ++i) {
7996         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
7997           Base = V->getOperand(i);
7998           break;
7999         }
8000       }
8001       // Splat of <u, u, u, u>, return <u, u, u, u>
8002       if (!Base.getNode())
8003         return N0;
8004       for (unsigned i = 0; i != NumElts; ++i) {
8005         if (V->getOperand(i) != Base) {
8006           AllSame = false;
8007           break;
8008         }
8009       }
8010       // Splat of <x, x, x, x>, return <x, x, x, x>
8011       if (AllSame)
8012         return N0;
8013     }
8014   }
8015
8016   // If this shuffle node is simply a swizzle of another shuffle node,
8017   // and it reverses the swizzle of the previous shuffle then we can
8018   // optimize shuffle(shuffle(x, undef), undef) -> x.
8019   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
8020       N1.getOpcode() == ISD::UNDEF) {
8021
8022     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
8023
8024     // Shuffle nodes can only reverse shuffles with a single non-undef value.
8025     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
8026       return SDValue();
8027
8028     // The incoming shuffle must be of the same type as the result of the
8029     // current shuffle.
8030     assert(OtherSV->getOperand(0).getValueType() == VT &&
8031            "Shuffle types don't match");
8032
8033     for (unsigned i = 0; i != NumElts; ++i) {
8034       int Idx = SVN->getMaskElt(i);
8035       assert(Idx < (int)NumElts && "Index references undef operand");
8036       // Next, this index comes from the first value, which is the incoming
8037       // shuffle. Adopt the incoming index.
8038       if (Idx >= 0)
8039         Idx = OtherSV->getMaskElt(Idx);
8040
8041       // The combined shuffle must map each index to itself.
8042       if (Idx >= 0 && (unsigned)Idx != i)
8043         return SDValue();
8044     }
8045
8046     return OtherSV->getOperand(0);
8047   }
8048
8049   return SDValue();
8050 }
8051
8052 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
8053   if (!TLI.getShouldFoldAtomicFences())
8054     return SDValue();
8055
8056   SDValue atomic = N->getOperand(0);
8057   switch (atomic.getOpcode()) {
8058     case ISD::ATOMIC_CMP_SWAP:
8059     case ISD::ATOMIC_SWAP:
8060     case ISD::ATOMIC_LOAD_ADD:
8061     case ISD::ATOMIC_LOAD_SUB:
8062     case ISD::ATOMIC_LOAD_AND:
8063     case ISD::ATOMIC_LOAD_OR:
8064     case ISD::ATOMIC_LOAD_XOR:
8065     case ISD::ATOMIC_LOAD_NAND:
8066     case ISD::ATOMIC_LOAD_MIN:
8067     case ISD::ATOMIC_LOAD_MAX:
8068     case ISD::ATOMIC_LOAD_UMIN:
8069     case ISD::ATOMIC_LOAD_UMAX:
8070       break;
8071     default:
8072       return SDValue();
8073   }
8074
8075   SDValue fence = atomic.getOperand(0);
8076   if (fence.getOpcode() != ISD::MEMBARRIER)
8077     return SDValue();
8078
8079   switch (atomic.getOpcode()) {
8080     case ISD::ATOMIC_CMP_SWAP:
8081       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8082                                     fence.getOperand(0),
8083                                     atomic.getOperand(1), atomic.getOperand(2),
8084                                     atomic.getOperand(3)), atomic.getResNo());
8085     case ISD::ATOMIC_SWAP:
8086     case ISD::ATOMIC_LOAD_ADD:
8087     case ISD::ATOMIC_LOAD_SUB:
8088     case ISD::ATOMIC_LOAD_AND:
8089     case ISD::ATOMIC_LOAD_OR:
8090     case ISD::ATOMIC_LOAD_XOR:
8091     case ISD::ATOMIC_LOAD_NAND:
8092     case ISD::ATOMIC_LOAD_MIN:
8093     case ISD::ATOMIC_LOAD_MAX:
8094     case ISD::ATOMIC_LOAD_UMIN:
8095     case ISD::ATOMIC_LOAD_UMAX:
8096       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8097                                     fence.getOperand(0),
8098                                     atomic.getOperand(1), atomic.getOperand(2)),
8099                      atomic.getResNo());
8100     default:
8101       return SDValue();
8102   }
8103 }
8104
8105 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
8106 /// an AND to a vector_shuffle with the destination vector and a zero vector.
8107 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
8108 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
8109 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
8110   EVT VT = N->getValueType(0);
8111   DebugLoc dl = N->getDebugLoc();
8112   SDValue LHS = N->getOperand(0);
8113   SDValue RHS = N->getOperand(1);
8114   if (N->getOpcode() == ISD::AND) {
8115     if (RHS.getOpcode() == ISD::BITCAST)
8116       RHS = RHS.getOperand(0);
8117     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
8118       SmallVector<int, 8> Indices;
8119       unsigned NumElts = RHS.getNumOperands();
8120       for (unsigned i = 0; i != NumElts; ++i) {
8121         SDValue Elt = RHS.getOperand(i);
8122         if (!isa<ConstantSDNode>(Elt))
8123           return SDValue();
8124
8125         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
8126           Indices.push_back(i);
8127         else if (cast<ConstantSDNode>(Elt)->isNullValue())
8128           Indices.push_back(NumElts);
8129         else
8130           return SDValue();
8131       }
8132
8133       // Let's see if the target supports this vector_shuffle.
8134       EVT RVT = RHS.getValueType();
8135       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
8136         return SDValue();
8137
8138       // Return the new VECTOR_SHUFFLE node.
8139       EVT EltVT = RVT.getVectorElementType();
8140       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
8141                                      DAG.getConstant(0, EltVT));
8142       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8143                                  RVT, &ZeroOps[0], ZeroOps.size());
8144       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
8145       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
8146       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
8147     }
8148   }
8149
8150   return SDValue();
8151 }
8152
8153 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
8154 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
8155   // After legalize, the target may be depending on adds and other
8156   // binary ops to provide legal ways to construct constants or other
8157   // things. Simplifying them may result in a loss of legality.
8158   if (LegalOperations) return SDValue();
8159
8160   assert(N->getValueType(0).isVector() &&
8161          "SimplifyVBinOp only works on vectors!");
8162
8163   SDValue LHS = N->getOperand(0);
8164   SDValue RHS = N->getOperand(1);
8165   SDValue Shuffle = XformToShuffleWithZero(N);
8166   if (Shuffle.getNode()) return Shuffle;
8167
8168   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
8169   // this operation.
8170   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
8171       RHS.getOpcode() == ISD::BUILD_VECTOR) {
8172     SmallVector<SDValue, 8> Ops;
8173     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
8174       SDValue LHSOp = LHS.getOperand(i);
8175       SDValue RHSOp = RHS.getOperand(i);
8176       // If these two elements can't be folded, bail out.
8177       if ((LHSOp.getOpcode() != ISD::UNDEF &&
8178            LHSOp.getOpcode() != ISD::Constant &&
8179            LHSOp.getOpcode() != ISD::ConstantFP) ||
8180           (RHSOp.getOpcode() != ISD::UNDEF &&
8181            RHSOp.getOpcode() != ISD::Constant &&
8182            RHSOp.getOpcode() != ISD::ConstantFP))
8183         break;
8184
8185       // Can't fold divide by zero.
8186       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
8187           N->getOpcode() == ISD::FDIV) {
8188         if ((RHSOp.getOpcode() == ISD::Constant &&
8189              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
8190             (RHSOp.getOpcode() == ISD::ConstantFP &&
8191              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
8192           break;
8193       }
8194
8195       EVT VT = LHSOp.getValueType();
8196       EVT RVT = RHSOp.getValueType();
8197       if (RVT != VT) {
8198         // Integer BUILD_VECTOR operands may have types larger than the element
8199         // size (e.g., when the element type is not legal).  Prior to type
8200         // legalization, the types may not match between the two BUILD_VECTORS.
8201         // Truncate one of the operands to make them match.
8202         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
8203           RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
8204         } else {
8205           LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
8206           VT = RVT;
8207         }
8208       }
8209       SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
8210                                    LHSOp, RHSOp);
8211       if (FoldOp.getOpcode() != ISD::UNDEF &&
8212           FoldOp.getOpcode() != ISD::Constant &&
8213           FoldOp.getOpcode() != ISD::ConstantFP)
8214         break;
8215       Ops.push_back(FoldOp);
8216       AddToWorkList(FoldOp.getNode());
8217     }
8218
8219     if (Ops.size() == LHS.getNumOperands())
8220       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8221                          LHS.getValueType(), &Ops[0], Ops.size());
8222   }
8223
8224   return SDValue();
8225 }
8226
8227 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
8228                                     SDValue N1, SDValue N2){
8229   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
8230
8231   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
8232                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
8233
8234   // If we got a simplified select_cc node back from SimplifySelectCC, then
8235   // break it down into a new SETCC node, and a new SELECT node, and then return
8236   // the SELECT node, since we were called with a SELECT node.
8237   if (SCC.getNode()) {
8238     // Check to see if we got a select_cc back (to turn into setcc/select).
8239     // Otherwise, just return whatever node we got back, like fabs.
8240     if (SCC.getOpcode() == ISD::SELECT_CC) {
8241       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
8242                                   N0.getValueType(),
8243                                   SCC.getOperand(0), SCC.getOperand(1),
8244                                   SCC.getOperand(4));
8245       AddToWorkList(SETCC.getNode());
8246       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
8247                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
8248     }
8249
8250     return SCC;
8251   }
8252   return SDValue();
8253 }
8254
8255 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
8256 /// are the two values being selected between, see if we can simplify the
8257 /// select.  Callers of this should assume that TheSelect is deleted if this
8258 /// returns true.  As such, they should return the appropriate thing (e.g. the
8259 /// node) back to the top-level of the DAG combiner loop to avoid it being
8260 /// looked at.
8261 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
8262                                     SDValue RHS) {
8263
8264   // Cannot simplify select with vector condition
8265   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
8266
8267   // If this is a select from two identical things, try to pull the operation
8268   // through the select.
8269   if (LHS.getOpcode() != RHS.getOpcode() ||
8270       !LHS.hasOneUse() || !RHS.hasOneUse())
8271     return false;
8272
8273   // If this is a load and the token chain is identical, replace the select
8274   // of two loads with a load through a select of the address to load from.
8275   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
8276   // constants have been dropped into the constant pool.
8277   if (LHS.getOpcode() == ISD::LOAD) {
8278     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
8279     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
8280
8281     // Token chains must be identical.
8282     if (LHS.getOperand(0) != RHS.getOperand(0) ||
8283         // Do not let this transformation reduce the number of volatile loads.
8284         LLD->isVolatile() || RLD->isVolatile() ||
8285         // If this is an EXTLOAD, the VT's must match.
8286         LLD->getMemoryVT() != RLD->getMemoryVT() ||
8287         // If this is an EXTLOAD, the kind of extension must match.
8288         (LLD->getExtensionType() != RLD->getExtensionType() &&
8289          // The only exception is if one of the extensions is anyext.
8290          LLD->getExtensionType() != ISD::EXTLOAD &&
8291          RLD->getExtensionType() != ISD::EXTLOAD) ||
8292         // FIXME: this discards src value information.  This is
8293         // over-conservative. It would be beneficial to be able to remember
8294         // both potential memory locations.  Since we are discarding
8295         // src value info, don't do the transformation if the memory
8296         // locations are not in the default address space.
8297         LLD->getPointerInfo().getAddrSpace() != 0 ||
8298         RLD->getPointerInfo().getAddrSpace() != 0)
8299       return false;
8300
8301     // Check that the select condition doesn't reach either load.  If so,
8302     // folding this will induce a cycle into the DAG.  If not, this is safe to
8303     // xform, so create a select of the addresses.
8304     SDValue Addr;
8305     if (TheSelect->getOpcode() == ISD::SELECT) {
8306       SDNode *CondNode = TheSelect->getOperand(0).getNode();
8307       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
8308           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
8309         return false;
8310       Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
8311                          LLD->getBasePtr().getValueType(),
8312                          TheSelect->getOperand(0), LLD->getBasePtr(),
8313                          RLD->getBasePtr());
8314     } else {  // Otherwise SELECT_CC
8315       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
8316       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
8317
8318       if ((LLD->hasAnyUseOfValue(1) &&
8319            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
8320           (RLD->hasAnyUseOfValue(1) &&
8321            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
8322         return false;
8323
8324       Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
8325                          LLD->getBasePtr().getValueType(),
8326                          TheSelect->getOperand(0),
8327                          TheSelect->getOperand(1),
8328                          LLD->getBasePtr(), RLD->getBasePtr(),
8329                          TheSelect->getOperand(4));
8330     }
8331
8332     SDValue Load;
8333     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
8334       Load = DAG.getLoad(TheSelect->getValueType(0),
8335                          TheSelect->getDebugLoc(),
8336                          // FIXME: Discards pointer info.
8337                          LLD->getChain(), Addr, MachinePointerInfo(),
8338                          LLD->isVolatile(), LLD->isNonTemporal(),
8339                          LLD->isInvariant(), LLD->getAlignment());
8340     } else {
8341       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
8342                             RLD->getExtensionType() : LLD->getExtensionType(),
8343                             TheSelect->getDebugLoc(),
8344                             TheSelect->getValueType(0),
8345                             // FIXME: Discards pointer info.
8346                             LLD->getChain(), Addr, MachinePointerInfo(),
8347                             LLD->getMemoryVT(), LLD->isVolatile(),
8348                             LLD->isNonTemporal(), LLD->getAlignment());
8349     }
8350
8351     // Users of the select now use the result of the load.
8352     CombineTo(TheSelect, Load);
8353
8354     // Users of the old loads now use the new load's chain.  We know the
8355     // old-load value is dead now.
8356     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
8357     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
8358     return true;
8359   }
8360
8361   return false;
8362 }
8363
8364 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
8365 /// where 'cond' is the comparison specified by CC.
8366 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
8367                                       SDValue N2, SDValue N3,
8368                                       ISD::CondCode CC, bool NotExtCompare) {
8369   // (x ? y : y) -> y.
8370   if (N2 == N3) return N2;
8371
8372   EVT VT = N2.getValueType();
8373   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
8374   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
8375   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
8376
8377   // Determine if the condition we're dealing with is constant
8378   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
8379                               N0, N1, CC, DL, false);
8380   if (SCC.getNode()) AddToWorkList(SCC.getNode());
8381   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
8382
8383   // fold select_cc true, x, y -> x
8384   if (SCCC && !SCCC->isNullValue())
8385     return N2;
8386   // fold select_cc false, x, y -> y
8387   if (SCCC && SCCC->isNullValue())
8388     return N3;
8389
8390   // Check to see if we can simplify the select into an fabs node
8391   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
8392     // Allow either -0.0 or 0.0
8393     if (CFP->getValueAPF().isZero()) {
8394       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
8395       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
8396           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
8397           N2 == N3.getOperand(0))
8398         return DAG.getNode(ISD::FABS, DL, VT, N0);
8399
8400       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
8401       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
8402           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
8403           N2.getOperand(0) == N3)
8404         return DAG.getNode(ISD::FABS, DL, VT, N3);
8405     }
8406   }
8407
8408   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
8409   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
8410   // in it.  This is a win when the constant is not otherwise available because
8411   // it replaces two constant pool loads with one.  We only do this if the FP
8412   // type is known to be legal, because if it isn't, then we are before legalize
8413   // types an we want the other legalization to happen first (e.g. to avoid
8414   // messing with soft float) and if the ConstantFP is not legal, because if
8415   // it is legal, we may not need to store the FP constant in a constant pool.
8416   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
8417     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
8418       if (TLI.isTypeLegal(N2.getValueType()) &&
8419           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
8420            TargetLowering::Legal) &&
8421           // If both constants have multiple uses, then we won't need to do an
8422           // extra load, they are likely around in registers for other users.
8423           (TV->hasOneUse() || FV->hasOneUse())) {
8424         Constant *Elts[] = {
8425           const_cast<ConstantFP*>(FV->getConstantFPValue()),
8426           const_cast<ConstantFP*>(TV->getConstantFPValue())
8427         };
8428         Type *FPTy = Elts[0]->getType();
8429         const TargetData &TD = *TLI.getTargetData();
8430
8431         // Create a ConstantArray of the two constants.
8432         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
8433         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
8434                                             TD.getPrefTypeAlignment(FPTy));
8435         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8436
8437         // Get the offsets to the 0 and 1 element of the array so that we can
8438         // select between them.
8439         SDValue Zero = DAG.getIntPtrConstant(0);
8440         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
8441         SDValue One = DAG.getIntPtrConstant(EltSize);
8442
8443         SDValue Cond = DAG.getSetCC(DL,
8444                                     TLI.getSetCCResultType(N0.getValueType()),
8445                                     N0, N1, CC);
8446         AddToWorkList(Cond.getNode());
8447         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
8448                                         Cond, One, Zero);
8449         AddToWorkList(CstOffset.getNode());
8450         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
8451                             CstOffset);
8452         AddToWorkList(CPIdx.getNode());
8453         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
8454                            MachinePointerInfo::getConstantPool(), false,
8455                            false, false, Alignment);
8456
8457       }
8458     }
8459
8460   // Check to see if we can perform the "gzip trick", transforming
8461   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
8462   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
8463       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
8464        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
8465     EVT XType = N0.getValueType();
8466     EVT AType = N2.getValueType();
8467     if (XType.bitsGE(AType)) {
8468       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
8469       // single-bit constant.
8470       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
8471         unsigned ShCtV = N2C->getAPIntValue().logBase2();
8472         ShCtV = XType.getSizeInBits()-ShCtV-1;
8473         SDValue ShCt = DAG.getConstant(ShCtV,
8474                                        getShiftAmountTy(N0.getValueType()));
8475         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
8476                                     XType, N0, ShCt);
8477         AddToWorkList(Shift.getNode());
8478
8479         if (XType.bitsGT(AType)) {
8480           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8481           AddToWorkList(Shift.getNode());
8482         }
8483
8484         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8485       }
8486
8487       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
8488                                   XType, N0,
8489                                   DAG.getConstant(XType.getSizeInBits()-1,
8490                                          getShiftAmountTy(N0.getValueType())));
8491       AddToWorkList(Shift.getNode());
8492
8493       if (XType.bitsGT(AType)) {
8494         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8495         AddToWorkList(Shift.getNode());
8496       }
8497
8498       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8499     }
8500   }
8501
8502   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
8503   // where y is has a single bit set.
8504   // A plaintext description would be, we can turn the SELECT_CC into an AND
8505   // when the condition can be materialized as an all-ones register.  Any
8506   // single bit-test can be materialized as an all-ones register with
8507   // shift-left and shift-right-arith.
8508   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
8509       N0->getValueType(0) == VT &&
8510       N1C && N1C->isNullValue() &&
8511       N2C && N2C->isNullValue()) {
8512     SDValue AndLHS = N0->getOperand(0);
8513     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8514     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
8515       // Shift the tested bit over the sign bit.
8516       APInt AndMask = ConstAndRHS->getAPIntValue();
8517       SDValue ShlAmt =
8518         DAG.getConstant(AndMask.countLeadingZeros(),
8519                         getShiftAmountTy(AndLHS.getValueType()));
8520       SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
8521
8522       // Now arithmetic right shift it all the way over, so the result is either
8523       // all-ones, or zero.
8524       SDValue ShrAmt =
8525         DAG.getConstant(AndMask.getBitWidth()-1,
8526                         getShiftAmountTy(Shl.getValueType()));
8527       SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
8528
8529       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
8530     }
8531   }
8532
8533   // fold select C, 16, 0 -> shl C, 4
8534   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
8535     TLI.getBooleanContents(N0.getValueType().isVector()) ==
8536       TargetLowering::ZeroOrOneBooleanContent) {
8537
8538     // If the caller doesn't want us to simplify this into a zext of a compare,
8539     // don't do it.
8540     if (NotExtCompare && N2C->getAPIntValue() == 1)
8541       return SDValue();
8542
8543     // Get a SetCC of the condition
8544     // FIXME: Should probably make sure that setcc is legal if we ever have a
8545     // target where it isn't.
8546     SDValue Temp, SCC;
8547     // cast from setcc result type to select result type
8548     if (LegalTypes) {
8549       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
8550                           N0, N1, CC);
8551       if (N2.getValueType().bitsLT(SCC.getValueType()))
8552         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
8553       else
8554         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8555                            N2.getValueType(), SCC);
8556     } else {
8557       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
8558       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8559                          N2.getValueType(), SCC);
8560     }
8561
8562     AddToWorkList(SCC.getNode());
8563     AddToWorkList(Temp.getNode());
8564
8565     if (N2C->getAPIntValue() == 1)
8566       return Temp;
8567
8568     // shl setcc result by log2 n2c
8569     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
8570                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
8571                                        getShiftAmountTy(Temp.getValueType())));
8572   }
8573
8574   // Check to see if this is the equivalent of setcc
8575   // FIXME: Turn all of these into setcc if setcc if setcc is legal
8576   // otherwise, go ahead with the folds.
8577   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
8578     EVT XType = N0.getValueType();
8579     if (!LegalOperations ||
8580         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
8581       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
8582       if (Res.getValueType() != VT)
8583         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
8584       return Res;
8585     }
8586
8587     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
8588     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
8589         (!LegalOperations ||
8590          TLI.isOperationLegal(ISD::CTLZ, XType))) {
8591       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
8592       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
8593                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
8594                                        getShiftAmountTy(Ctlz.getValueType())));
8595     }
8596     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
8597     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
8598       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
8599                                   XType, DAG.getConstant(0, XType), N0);
8600       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
8601       return DAG.getNode(ISD::SRL, DL, XType,
8602                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
8603                          DAG.getConstant(XType.getSizeInBits()-1,
8604                                          getShiftAmountTy(XType)));
8605     }
8606     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
8607     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
8608       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
8609                                  DAG.getConstant(XType.getSizeInBits()-1,
8610                                          getShiftAmountTy(N0.getValueType())));
8611       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
8612     }
8613   }
8614
8615   // Check to see if this is an integer abs.
8616   // select_cc setg[te] X,  0,  X, -X ->
8617   // select_cc setgt    X, -1,  X, -X ->
8618   // select_cc setl[te] X,  0, -X,  X ->
8619   // select_cc setlt    X,  1, -X,  X ->
8620   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
8621   if (N1C) {
8622     ConstantSDNode *SubC = NULL;
8623     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
8624          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
8625         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
8626       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
8627     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
8628               (N1C->isOne() && CC == ISD::SETLT)) &&
8629              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
8630       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
8631
8632     EVT XType = N0.getValueType();
8633     if (SubC && SubC->isNullValue() && XType.isInteger()) {
8634       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
8635                                   N0,
8636                                   DAG.getConstant(XType.getSizeInBits()-1,
8637                                          getShiftAmountTy(N0.getValueType())));
8638       SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
8639                                 XType, N0, Shift);
8640       AddToWorkList(Shift.getNode());
8641       AddToWorkList(Add.getNode());
8642       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
8643     }
8644   }
8645
8646   return SDValue();
8647 }
8648
8649 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
8650 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
8651                                    SDValue N1, ISD::CondCode Cond,
8652                                    DebugLoc DL, bool foldBooleans) {
8653   TargetLowering::DAGCombinerInfo
8654     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
8655   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
8656 }
8657
8658 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
8659 /// return a DAG expression to select that will generate the same value by
8660 /// multiplying by a magic number.  See:
8661 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8662 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
8663   std::vector<SDNode*> Built;
8664   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
8665
8666   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8667        ii != ee; ++ii)
8668     AddToWorkList(*ii);
8669   return S;
8670 }
8671
8672 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
8673 /// return a DAG expression to select that will generate the same value by
8674 /// multiplying by a magic number.  See:
8675 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8676 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
8677   std::vector<SDNode*> Built;
8678   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
8679
8680   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8681        ii != ee; ++ii)
8682     AddToWorkList(*ii);
8683   return S;
8684 }
8685
8686 /// FindBaseOffset - Return true if base is a frame index, which is known not
8687 // to alias with anything but itself.  Provides base object and offset as
8688 // results.
8689 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
8690                            const GlobalValue *&GV, void *&CV) {
8691   // Assume it is a primitive operation.
8692   Base = Ptr; Offset = 0; GV = 0; CV = 0;
8693
8694   // If it's an adding a simple constant then integrate the offset.
8695   if (Base.getOpcode() == ISD::ADD) {
8696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
8697       Base = Base.getOperand(0);
8698       Offset += C->getZExtValue();
8699     }
8700   }
8701
8702   // Return the underlying GlobalValue, and update the Offset.  Return false
8703   // for GlobalAddressSDNode since the same GlobalAddress may be represented
8704   // by multiple nodes with different offsets.
8705   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
8706     GV = G->getGlobal();
8707     Offset += G->getOffset();
8708     return false;
8709   }
8710
8711   // Return the underlying Constant value, and update the Offset.  Return false
8712   // for ConstantSDNodes since the same constant pool entry may be represented
8713   // by multiple nodes with different offsets.
8714   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
8715     CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
8716                                          : (void *)C->getConstVal();
8717     Offset += C->getOffset();
8718     return false;
8719   }
8720   // If it's any of the following then it can't alias with anything but itself.
8721   return isa<FrameIndexSDNode>(Base);
8722 }
8723
8724 /// isAlias - Return true if there is any possibility that the two addresses
8725 /// overlap.
8726 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
8727                           const Value *SrcValue1, int SrcValueOffset1,
8728                           unsigned SrcValueAlign1,
8729                           const MDNode *TBAAInfo1,
8730                           SDValue Ptr2, int64_t Size2,
8731                           const Value *SrcValue2, int SrcValueOffset2,
8732                           unsigned SrcValueAlign2,
8733                           const MDNode *TBAAInfo2) const {
8734   // If they are the same then they must be aliases.
8735   if (Ptr1 == Ptr2) return true;
8736
8737   // Gather base node and offset information.
8738   SDValue Base1, Base2;
8739   int64_t Offset1, Offset2;
8740   const GlobalValue *GV1, *GV2;
8741   void *CV1, *CV2;
8742   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
8743   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
8744
8745   // If they have a same base address then check to see if they overlap.
8746   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
8747     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8748
8749   // It is possible for different frame indices to alias each other, mostly
8750   // when tail call optimization reuses return address slots for arguments.
8751   // To catch this case, look up the actual index of frame indices to compute
8752   // the real alias relationship.
8753   if (isFrameIndex1 && isFrameIndex2) {
8754     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8755     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
8756     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
8757     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8758   }
8759
8760   // Otherwise, if we know what the bases are, and they aren't identical, then
8761   // we know they cannot alias.
8762   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
8763     return false;
8764
8765   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
8766   // compared to the size and offset of the access, we may be able to prove they
8767   // do not alias.  This check is conservative for now to catch cases created by
8768   // splitting vector types.
8769   if ((SrcValueAlign1 == SrcValueAlign2) &&
8770       (SrcValueOffset1 != SrcValueOffset2) &&
8771       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
8772     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
8773     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
8774
8775     // There is no overlap between these relatively aligned accesses of similar
8776     // size, return no alias.
8777     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
8778       return false;
8779   }
8780
8781   if (CombinerGlobalAA) {
8782     // Use alias analysis information.
8783     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
8784     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
8785     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
8786     AliasAnalysis::AliasResult AAResult =
8787       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
8788                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
8789     if (AAResult == AliasAnalysis::NoAlias)
8790       return false;
8791   }
8792
8793   // Otherwise we have to assume they alias.
8794   return true;
8795 }
8796
8797 /// FindAliasInfo - Extracts the relevant alias information from the memory
8798 /// node.  Returns true if the operand was a load.
8799 bool DAGCombiner::FindAliasInfo(SDNode *N,
8800                                 SDValue &Ptr, int64_t &Size,
8801                                 const Value *&SrcValue,
8802                                 int &SrcValueOffset,
8803                                 unsigned &SrcValueAlign,
8804                                 const MDNode *&TBAAInfo) const {
8805   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
8806
8807   Ptr = LS->getBasePtr();
8808   Size = LS->getMemoryVT().getSizeInBits() >> 3;
8809   SrcValue = LS->getSrcValue();
8810   SrcValueOffset = LS->getSrcValueOffset();
8811   SrcValueAlign = LS->getOriginalAlignment();
8812   TBAAInfo = LS->getTBAAInfo();
8813   return isa<LoadSDNode>(LS);
8814 }
8815
8816 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
8817 /// looking for aliasing nodes and adding them to the Aliases vector.
8818 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
8819                                    SmallVector<SDValue, 8> &Aliases) {
8820   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
8821   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
8822
8823   // Get alias information for node.
8824   SDValue Ptr;
8825   int64_t Size;
8826   const Value *SrcValue;
8827   int SrcValueOffset;
8828   unsigned SrcValueAlign;
8829   const MDNode *SrcTBAAInfo;
8830   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
8831                               SrcValueAlign, SrcTBAAInfo);
8832
8833   // Starting off.
8834   Chains.push_back(OriginalChain);
8835   unsigned Depth = 0;
8836
8837   // Look at each chain and determine if it is an alias.  If so, add it to the
8838   // aliases list.  If not, then continue up the chain looking for the next
8839   // candidate.
8840   while (!Chains.empty()) {
8841     SDValue Chain = Chains.back();
8842     Chains.pop_back();
8843
8844     // For TokenFactor nodes, look at each operand and only continue up the
8845     // chain until we find two aliases.  If we've seen two aliases, assume we'll
8846     // find more and revert to original chain since the xform is unlikely to be
8847     // profitable.
8848     //
8849     // FIXME: The depth check could be made to return the last non-aliasing
8850     // chain we found before we hit a tokenfactor rather than the original
8851     // chain.
8852     if (Depth > 6 || Aliases.size() == 2) {
8853       Aliases.clear();
8854       Aliases.push_back(OriginalChain);
8855       break;
8856     }
8857
8858     // Don't bother if we've been before.
8859     if (!Visited.insert(Chain.getNode()))
8860       continue;
8861
8862     switch (Chain.getOpcode()) {
8863     case ISD::EntryToken:
8864       // Entry token is ideal chain operand, but handled in FindBetterChain.
8865       break;
8866
8867     case ISD::LOAD:
8868     case ISD::STORE: {
8869       // Get alias information for Chain.
8870       SDValue OpPtr;
8871       int64_t OpSize;
8872       const Value *OpSrcValue;
8873       int OpSrcValueOffset;
8874       unsigned OpSrcValueAlign;
8875       const MDNode *OpSrcTBAAInfo;
8876       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
8877                                     OpSrcValue, OpSrcValueOffset,
8878                                     OpSrcValueAlign,
8879                                     OpSrcTBAAInfo);
8880
8881       // If chain is alias then stop here.
8882       if (!(IsLoad && IsOpLoad) &&
8883           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
8884                   SrcTBAAInfo,
8885                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
8886                   OpSrcValueAlign, OpSrcTBAAInfo)) {
8887         Aliases.push_back(Chain);
8888       } else {
8889         // Look further up the chain.
8890         Chains.push_back(Chain.getOperand(0));
8891         ++Depth;
8892       }
8893       break;
8894     }
8895
8896     case ISD::TokenFactor:
8897       // We have to check each of the operands of the token factor for "small"
8898       // token factors, so we queue them up.  Adding the operands to the queue
8899       // (stack) in reverse order maintains the original order and increases the
8900       // likelihood that getNode will find a matching token factor (CSE.)
8901       if (Chain.getNumOperands() > 16) {
8902         Aliases.push_back(Chain);
8903         break;
8904       }
8905       for (unsigned n = Chain.getNumOperands(); n;)
8906         Chains.push_back(Chain.getOperand(--n));
8907       ++Depth;
8908       break;
8909
8910     default:
8911       // For all other instructions we will just have to take what we can get.
8912       Aliases.push_back(Chain);
8913       break;
8914     }
8915   }
8916 }
8917
8918 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
8919 /// for a better chain (aliasing node.)
8920 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
8921   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
8922
8923   // Accumulate all the aliases to this node.
8924   GatherAllAliases(N, OldChain, Aliases);
8925
8926   // If no operands then chain to entry token.
8927   if (Aliases.size() == 0)
8928     return DAG.getEntryNode();
8929
8930   // If a single operand then chain to it.  We don't need to revisit it.
8931   if (Aliases.size() == 1)
8932     return Aliases[0];
8933
8934   // Construct a custom tailored token factor.
8935   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8936                      &Aliases[0], Aliases.size());
8937 }
8938
8939 // SelectionDAG::Combine - This is the entry point for the file.
8940 //
8941 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
8942                            CodeGenOpt::Level OptLevel) {
8943   /// run - This is the main entry point to this class.
8944   ///
8945   DAGCombiner(*this, AA, OptLevel).Run(Level);
8946 }