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