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