Fix PR16360
[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/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NodesCombined   , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
45 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
46
47 namespace {
48   static cl::opt<bool>
49     CombinerAA("combiner-alias-analysis", cl::Hidden,
50                cl::desc("Turn on alias analysis during testing"));
51
52   static cl::opt<bool>
53     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54                cl::desc("Include global information in alias analysis"));
55
56 //------------------------------ DAGCombiner ---------------------------------//
57
58   class DAGCombiner {
59     SelectionDAG &DAG;
60     const TargetLowering &TLI;
61     CombineLevel Level;
62     CodeGenOpt::Level OptLevel;
63     bool LegalOperations;
64     bool LegalTypes;
65
66     // Worklist of all of the nodes that need to be simplified.
67     //
68     // This has the semantics that when adding to the worklist,
69     // the item added must be next to be processed. It should
70     // also only appear once. The naive approach to this takes
71     // linear time.
72     //
73     // To reduce the insert/remove time to logarithmic, we use
74     // a set and a vector to maintain our worklist.
75     //
76     // The set contains the items on the worklist, but does not
77     // maintain the order they should be visited.
78     //
79     // The vector maintains the order nodes should be visited, but may
80     // contain duplicate or removed nodes. When choosing a node to
81     // visit, we pop off the order stack until we find an item that is
82     // also in the contents set. All operations are O(log N).
83     SmallPtrSet<SDNode*, 64> WorkListContents;
84     SmallVector<SDNode*, 64> WorkListOrder;
85
86     // AA - Used for DAG load/store alias analysis.
87     AliasAnalysis &AA;
88
89     /// AddUsersToWorkList - When an instruction is simplified, add all users of
90     /// the instruction to the work lists because they might get more simplified
91     /// now.
92     ///
93     void AddUsersToWorkList(SDNode *N) {
94       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
95            UI != UE; ++UI)
96         AddToWorkList(*UI);
97     }
98
99     /// visit - call the node-specific routine that knows how to fold each
100     /// particular type of node.
101     SDValue visit(SDNode *N);
102
103   public:
104     /// AddToWorkList - Add to the work list making sure its instance is at the
105     /// back (next to be processed.)
106     void AddToWorkList(SDNode *N) {
107       WorkListContents.insert(N);
108       WorkListOrder.push_back(N);
109     }
110
111     /// removeFromWorkList - remove all instances of N from the worklist.
112     ///
113     void removeFromWorkList(SDNode *N) {
114       WorkListContents.erase(N);
115     }
116
117     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
118                       bool AddTo = true);
119
120     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
121       return CombineTo(N, &Res, 1, AddTo);
122     }
123
124     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
125                       bool AddTo = true) {
126       SDValue To[] = { Res0, Res1 };
127       return CombineTo(N, To, 2, AddTo);
128     }
129
130     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
131
132   private:
133
134     /// SimplifyDemandedBits - Check the specified integer node value to see if
135     /// it can be simplified or if things it uses can be simplified by bit
136     /// propagation.  If so, return true.
137     bool SimplifyDemandedBits(SDValue Op) {
138       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
139       APInt Demanded = APInt::getAllOnesValue(BitWidth);
140       return SimplifyDemandedBits(Op, Demanded);
141     }
142
143     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
144
145     bool CombineToPreIndexedLoadStore(SDNode *N);
146     bool CombineToPostIndexedLoadStore(SDNode *N);
147
148     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
149     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
150     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
151     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
152     SDValue PromoteIntBinOp(SDValue Op);
153     SDValue PromoteIntShiftOp(SDValue Op);
154     SDValue PromoteExtend(SDValue Op);
155     bool PromoteLoad(SDValue Op);
156
157     void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
158                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
159                          ISD::NodeType ExtType);
160
161     /// combine - call the node-specific routine that knows how to fold each
162     /// particular type of node. If that doesn't do anything, try the
163     /// target-specific DAG combines.
164     SDValue combine(SDNode *N);
165
166     // Visitation implementation - Implement dag node combining for different
167     // node types.  The semantics are as follows:
168     // Return Value:
169     //   SDValue.getNode() == 0 - No change was made
170     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
171     //   otherwise              - N should be replaced by the returned Operand.
172     //
173     SDValue visitTokenFactor(SDNode *N);
174     SDValue visitMERGE_VALUES(SDNode *N);
175     SDValue visitADD(SDNode *N);
176     SDValue visitSUB(SDNode *N);
177     SDValue visitADDC(SDNode *N);
178     SDValue visitSUBC(SDNode *N);
179     SDValue visitADDE(SDNode *N);
180     SDValue visitSUBE(SDNode *N);
181     SDValue visitMUL(SDNode *N);
182     SDValue visitSDIV(SDNode *N);
183     SDValue visitUDIV(SDNode *N);
184     SDValue visitSREM(SDNode *N);
185     SDValue visitUREM(SDNode *N);
186     SDValue visitMULHU(SDNode *N);
187     SDValue visitMULHS(SDNode *N);
188     SDValue visitSMUL_LOHI(SDNode *N);
189     SDValue visitUMUL_LOHI(SDNode *N);
190     SDValue visitSMULO(SDNode *N);
191     SDValue visitUMULO(SDNode *N);
192     SDValue visitSDIVREM(SDNode *N);
193     SDValue visitUDIVREM(SDNode *N);
194     SDValue visitAND(SDNode *N);
195     SDValue visitOR(SDNode *N);
196     SDValue visitXOR(SDNode *N);
197     SDValue SimplifyVBinOp(SDNode *N);
198     SDValue SimplifyVUnaryOp(SDNode *N);
199     SDValue visitSHL(SDNode *N);
200     SDValue visitSRA(SDNode *N);
201     SDValue visitSRL(SDNode *N);
202     SDValue visitCTLZ(SDNode *N);
203     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
204     SDValue visitCTTZ(SDNode *N);
205     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
206     SDValue visitCTPOP(SDNode *N);
207     SDValue visitSELECT(SDNode *N);
208     SDValue visitVSELECT(SDNode *N);
209     SDValue visitSELECT_CC(SDNode *N);
210     SDValue visitSETCC(SDNode *N);
211     SDValue visitSIGN_EXTEND(SDNode *N);
212     SDValue visitZERO_EXTEND(SDNode *N);
213     SDValue visitANY_EXTEND(SDNode *N);
214     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
215     SDValue visitTRUNCATE(SDNode *N);
216     SDValue visitBITCAST(SDNode *N);
217     SDValue visitBUILD_PAIR(SDNode *N);
218     SDValue visitFADD(SDNode *N);
219     SDValue visitFSUB(SDNode *N);
220     SDValue visitFMUL(SDNode *N);
221     SDValue visitFMA(SDNode *N);
222     SDValue visitFDIV(SDNode *N);
223     SDValue visitFREM(SDNode *N);
224     SDValue visitFCOPYSIGN(SDNode *N);
225     SDValue visitSINT_TO_FP(SDNode *N);
226     SDValue visitUINT_TO_FP(SDNode *N);
227     SDValue visitFP_TO_SINT(SDNode *N);
228     SDValue visitFP_TO_UINT(SDNode *N);
229     SDValue visitFP_ROUND(SDNode *N);
230     SDValue visitFP_ROUND_INREG(SDNode *N);
231     SDValue visitFP_EXTEND(SDNode *N);
232     SDValue visitFNEG(SDNode *N);
233     SDValue visitFABS(SDNode *N);
234     SDValue visitFCEIL(SDNode *N);
235     SDValue visitFTRUNC(SDNode *N);
236     SDValue visitFFLOOR(SDNode *N);
237     SDValue visitBRCOND(SDNode *N);
238     SDValue visitBR_CC(SDNode *N);
239     SDValue visitLOAD(SDNode *N);
240     SDValue visitSTORE(SDNode *N);
241     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
242     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
243     SDValue visitBUILD_VECTOR(SDNode *N);
244     SDValue visitCONCAT_VECTORS(SDNode *N);
245     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
246     SDValue visitVECTOR_SHUFFLE(SDNode *N);
247
248     SDValue XformToShuffleWithZero(SDNode *N);
249     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
250
251     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
252
253     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
254     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
255     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
256     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
257                              SDValue N3, ISD::CondCode CC,
258                              bool NotExtCompare = false);
259     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
260                           SDLoc DL, bool foldBooleans = true);
261     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
262                                          unsigned HiOp);
263     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
264     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
265     SDValue BuildSDIV(SDNode *N);
266     SDValue BuildUDIV(SDNode *N);
267     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
268                                bool DemandHighBits = true);
269     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
270     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
271     SDValue ReduceLoadWidth(SDNode *N);
272     SDValue ReduceLoadOpStoreWidth(SDNode *N);
273     SDValue TransformFPLoadStorePair(SDNode *N);
274     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
275     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
276
277     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
278
279     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
280     /// looking for aliasing nodes and adding them to the Aliases vector.
281     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
282                           SmallVector<SDValue, 8> &Aliases);
283
284     /// isAlias - Return true if there is any possibility that the two addresses
285     /// overlap.
286     bool isAlias(SDValue Ptr1, int64_t Size1,
287                  const Value *SrcValue1, int SrcValueOffset1,
288                  unsigned SrcValueAlign1,
289                  const MDNode *TBAAInfo1,
290                  SDValue Ptr2, int64_t Size2,
291                  const Value *SrcValue2, int SrcValueOffset2,
292                  unsigned SrcValueAlign2,
293                  const MDNode *TBAAInfo2) const;
294
295     /// isAlias - Return true if there is any possibility that the two addresses
296     /// overlap.
297     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
298
299     /// FindAliasInfo - Extracts the relevant alias information from the memory
300     /// node.  Returns true if the operand was a load.
301     bool FindAliasInfo(SDNode *N,
302                        SDValue &Ptr, int64_t &Size,
303                        const Value *&SrcValue, int &SrcValueOffset,
304                        unsigned &SrcValueAlignment,
305                        const MDNode *&TBAAInfo) const;
306
307     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
308     /// looking for a better chain (aliasing node.)
309     SDValue FindBetterChain(SDNode *N, SDValue Chain);
310
311     /// Merge consecutive store operations into a wide store.
312     /// This optimization uses wide integers or vectors when possible.
313     /// \return True if some memory operations were changed.
314     bool MergeConsecutiveStores(StoreSDNode *N);
315
316   public:
317     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
318       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
319         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
320
321     /// Run - runs the dag combiner on all nodes in the work list
322     void Run(CombineLevel AtLevel);
323
324     SelectionDAG &getDAG() const { return DAG; }
325
326     /// getShiftAmountTy - Returns a type large enough to hold any valid
327     /// shift amount - before type legalization these can be huge.
328     EVT getShiftAmountTy(EVT LHSTy) {
329       return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
330     }
331
332     /// isTypeLegal - This method returns true if we are running before type
333     /// legalization or if the specified VT is legal.
334     bool isTypeLegal(const EVT &VT) {
335       if (!LegalTypes) return true;
336       return TLI.isTypeLegal(VT);
337     }
338
339     /// getSetCCResultType - Convenience wrapper around
340     /// TargetLowering::getSetCCResultType
341     EVT getSetCCResultType(EVT VT) const {
342       return TLI.getSetCCResultType(*DAG.getContext(), VT);
343     }
344   };
345 }
346
347
348 namespace {
349 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
350 /// nodes from the worklist.
351 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
352   DAGCombiner &DC;
353 public:
354   explicit WorkListRemover(DAGCombiner &dc)
355     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
356
357   virtual void NodeDeleted(SDNode *N, SDNode *E) {
358     DC.removeFromWorkList(N);
359   }
360 };
361 }
362
363 //===----------------------------------------------------------------------===//
364 //  TargetLowering::DAGCombinerInfo implementation
365 //===----------------------------------------------------------------------===//
366
367 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
368   ((DAGCombiner*)DC)->AddToWorkList(N);
369 }
370
371 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
372   ((DAGCombiner*)DC)->removeFromWorkList(N);
373 }
374
375 SDValue TargetLowering::DAGCombinerInfo::
376 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
377   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
378 }
379
380 SDValue TargetLowering::DAGCombinerInfo::
381 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
382   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
383 }
384
385
386 SDValue TargetLowering::DAGCombinerInfo::
387 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
388   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
389 }
390
391 void TargetLowering::DAGCombinerInfo::
392 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
393   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
394 }
395
396 //===----------------------------------------------------------------------===//
397 // Helper Functions
398 //===----------------------------------------------------------------------===//
399
400 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
401 /// specified expression for the same cost as the expression itself, or 2 if we
402 /// can compute the negated form more cheaply than the expression itself.
403 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
404                                const TargetLowering &TLI,
405                                const TargetOptions *Options,
406                                unsigned Depth = 0) {
407   // fneg is removable even if it has multiple uses.
408   if (Op.getOpcode() == ISD::FNEG) return 2;
409
410   // Don't allow anything with multiple uses.
411   if (!Op.hasOneUse()) return 0;
412
413   // Don't recurse exponentially.
414   if (Depth > 6) return 0;
415
416   switch (Op.getOpcode()) {
417   default: return false;
418   case ISD::ConstantFP:
419     // Don't invert constant FP values after legalize.  The negated constant
420     // isn't necessarily legal.
421     return LegalOperations ? 0 : 1;
422   case ISD::FADD:
423     // FIXME: determine better conditions for this xform.
424     if (!Options->UnsafeFPMath) return 0;
425
426     // After operation legalization, it might not be legal to create new FSUBs.
427     if (LegalOperations &&
428         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
429       return 0;
430
431     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
432     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
433                                     Options, Depth + 1))
434       return V;
435     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
436     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
437                               Depth + 1);
438   case ISD::FSUB:
439     // We can't turn -(A-B) into B-A when we honor signed zeros.
440     if (!Options->UnsafeFPMath) return 0;
441
442     // fold (fneg (fsub A, B)) -> (fsub B, A)
443     return 1;
444
445   case ISD::FMUL:
446   case ISD::FDIV:
447     if (Options->HonorSignDependentRoundingFPMath()) return 0;
448
449     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
450     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
451                                     Options, Depth + 1))
452       return V;
453
454     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
455                               Depth + 1);
456
457   case ISD::FP_EXTEND:
458   case ISD::FP_ROUND:
459   case ISD::FSIN:
460     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
461                               Depth + 1);
462   }
463 }
464
465 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
466 /// returns the newly negated expression.
467 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
468                                     bool LegalOperations, unsigned Depth = 0) {
469   // fneg is removable even if it has multiple uses.
470   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
471
472   // Don't allow anything with multiple uses.
473   assert(Op.hasOneUse() && "Unknown reuse!");
474
475   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
476   switch (Op.getOpcode()) {
477   default: llvm_unreachable("Unknown code");
478   case ISD::ConstantFP: {
479     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
480     V.changeSign();
481     return DAG.getConstantFP(V, Op.getValueType());
482   }
483   case ISD::FADD:
484     // FIXME: determine better conditions for this xform.
485     assert(DAG.getTarget().Options.UnsafeFPMath);
486
487     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
488     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
489                            DAG.getTargetLoweringInfo(),
490                            &DAG.getTarget().Options, Depth+1))
491       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
492                          GetNegatedExpression(Op.getOperand(0), DAG,
493                                               LegalOperations, Depth+1),
494                          Op.getOperand(1));
495     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
496     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
497                        GetNegatedExpression(Op.getOperand(1), DAG,
498                                             LegalOperations, Depth+1),
499                        Op.getOperand(0));
500   case ISD::FSUB:
501     // We can't turn -(A-B) into B-A when we honor signed zeros.
502     assert(DAG.getTarget().Options.UnsafeFPMath);
503
504     // fold (fneg (fsub 0, B)) -> B
505     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
506       if (N0CFP->getValueAPF().isZero())
507         return Op.getOperand(1);
508
509     // fold (fneg (fsub A, B)) -> (fsub B, A)
510     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
511                        Op.getOperand(1), Op.getOperand(0));
512
513   case ISD::FMUL:
514   case ISD::FDIV:
515     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
516
517     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
518     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
519                            DAG.getTargetLoweringInfo(),
520                            &DAG.getTarget().Options, Depth+1))
521       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
522                          GetNegatedExpression(Op.getOperand(0), DAG,
523                                               LegalOperations, Depth+1),
524                          Op.getOperand(1));
525
526     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
527     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
528                        Op.getOperand(0),
529                        GetNegatedExpression(Op.getOperand(1), DAG,
530                                             LegalOperations, Depth+1));
531
532   case ISD::FP_EXTEND:
533   case ISD::FSIN:
534     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
535                        GetNegatedExpression(Op.getOperand(0), DAG,
536                                             LegalOperations, Depth+1));
537   case ISD::FP_ROUND:
538       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
539                          GetNegatedExpression(Op.getOperand(0), DAG,
540                                               LegalOperations, Depth+1),
541                          Op.getOperand(1));
542   }
543 }
544
545
546 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
547 // that selects between the values 1 and 0, making it equivalent to a setcc.
548 // Also, set the incoming LHS, RHS, and CC references to the appropriate
549 // nodes based on the type of node we are checking.  This simplifies life a
550 // bit for the callers.
551 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
552                               SDValue &CC) {
553   if (N.getOpcode() == ISD::SETCC) {
554     LHS = N.getOperand(0);
555     RHS = N.getOperand(1);
556     CC  = N.getOperand(2);
557     return true;
558   }
559   if (N.getOpcode() == ISD::SELECT_CC &&
560       N.getOperand(2).getOpcode() == ISD::Constant &&
561       N.getOperand(3).getOpcode() == ISD::Constant &&
562       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
563       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
564     LHS = N.getOperand(0);
565     RHS = N.getOperand(1);
566     CC  = N.getOperand(4);
567     return true;
568   }
569   return false;
570 }
571
572 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
573 // one use.  If this is true, it allows the users to invert the operation for
574 // free when it is profitable to do so.
575 static bool isOneUseSetCC(SDValue N) {
576   SDValue N0, N1, N2;
577   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
578     return true;
579   return false;
580 }
581
582 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
583                                     SDValue N0, SDValue N1) {
584   EVT VT = N0.getValueType();
585   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
586     if (isa<ConstantSDNode>(N1)) {
587       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
588       SDValue OpNode =
589         DAG.FoldConstantArithmetic(Opc, VT,
590                                    cast<ConstantSDNode>(N0.getOperand(1)),
591                                    cast<ConstantSDNode>(N1));
592       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
593     }
594     if (N0.hasOneUse()) {
595       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
596       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
597                                    N0.getOperand(0), N1);
598       AddToWorkList(OpNode.getNode());
599       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
600     }
601   }
602
603   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
604     if (isa<ConstantSDNode>(N0)) {
605       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
606       SDValue OpNode =
607         DAG.FoldConstantArithmetic(Opc, VT,
608                                    cast<ConstantSDNode>(N1.getOperand(1)),
609                                    cast<ConstantSDNode>(N0));
610       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
611     }
612     if (N1.hasOneUse()) {
613       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
614       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
615                                    N1.getOperand(0), N0);
616       AddToWorkList(OpNode.getNode());
617       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
618     }
619   }
620
621   return SDValue();
622 }
623
624 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
625                                bool AddTo) {
626   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
627   ++NodesCombined;
628   DEBUG(dbgs() << "\nReplacing.1 ";
629         N->dump(&DAG);
630         dbgs() << "\nWith: ";
631         To[0].getNode()->dump(&DAG);
632         dbgs() << " and " << NumTo-1 << " other values\n";
633         for (unsigned i = 0, e = NumTo; i != e; ++i)
634           assert((!To[i].getNode() ||
635                   N->getValueType(i) == To[i].getValueType()) &&
636                  "Cannot combine value to value of different type!"));
637   WorkListRemover DeadNodes(*this);
638   DAG.ReplaceAllUsesWith(N, To);
639   if (AddTo) {
640     // Push the new nodes and any users onto the worklist
641     for (unsigned i = 0, e = NumTo; i != e; ++i) {
642       if (To[i].getNode()) {
643         AddToWorkList(To[i].getNode());
644         AddUsersToWorkList(To[i].getNode());
645       }
646     }
647   }
648
649   // Finally, if the node is now dead, remove it from the graph.  The node
650   // may not be dead if the replacement process recursively simplified to
651   // something else needing this node.
652   if (N->use_empty()) {
653     // Nodes can be reintroduced into the worklist.  Make sure we do not
654     // process a node that has been replaced.
655     removeFromWorkList(N);
656
657     // Finally, since the node is now dead, remove it from the graph.
658     DAG.DeleteNode(N);
659   }
660   return SDValue(N, 0);
661 }
662
663 void DAGCombiner::
664 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
665   // Replace all uses.  If any nodes become isomorphic to other nodes and
666   // are deleted, make sure to remove them from our worklist.
667   WorkListRemover DeadNodes(*this);
668   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
669
670   // Push the new node and any (possibly new) users onto the worklist.
671   AddToWorkList(TLO.New.getNode());
672   AddUsersToWorkList(TLO.New.getNode());
673
674   // Finally, if the node is now dead, remove it from the graph.  The node
675   // may not be dead if the replacement process recursively simplified to
676   // something else needing this node.
677   if (TLO.Old.getNode()->use_empty()) {
678     removeFromWorkList(TLO.Old.getNode());
679
680     // If the operands of this node are only used by the node, they will now
681     // be dead.  Make sure to visit them first to delete dead nodes early.
682     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
683       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
684         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
685
686     DAG.DeleteNode(TLO.Old.getNode());
687   }
688 }
689
690 /// SimplifyDemandedBits - Check the specified integer node value to see if
691 /// it can be simplified or if things it uses can be simplified by bit
692 /// propagation.  If so, return true.
693 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
694   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
695   APInt KnownZero, KnownOne;
696   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
697     return false;
698
699   // Revisit the node.
700   AddToWorkList(Op.getNode());
701
702   // Replace the old value with the new one.
703   ++NodesCombined;
704   DEBUG(dbgs() << "\nReplacing.2 ";
705         TLO.Old.getNode()->dump(&DAG);
706         dbgs() << "\nWith: ";
707         TLO.New.getNode()->dump(&DAG);
708         dbgs() << '\n');
709
710   CommitTargetLoweringOpt(TLO);
711   return true;
712 }
713
714 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
715   SDLoc dl(Load);
716   EVT VT = Load->getValueType(0);
717   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
718
719   DEBUG(dbgs() << "\nReplacing.9 ";
720         Load->dump(&DAG);
721         dbgs() << "\nWith: ";
722         Trunc.getNode()->dump(&DAG);
723         dbgs() << '\n');
724   WorkListRemover DeadNodes(*this);
725   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
726   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
727   removeFromWorkList(Load);
728   DAG.DeleteNode(Load);
729   AddToWorkList(Trunc.getNode());
730 }
731
732 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
733   Replace = false;
734   SDLoc dl(Op);
735   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
736     EVT MemVT = LD->getMemoryVT();
737     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
738       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
739                                                   : ISD::EXTLOAD)
740       : LD->getExtensionType();
741     Replace = true;
742     return DAG.getExtLoad(ExtType, dl, PVT,
743                           LD->getChain(), LD->getBasePtr(),
744                           LD->getPointerInfo(),
745                           MemVT, LD->isVolatile(),
746                           LD->isNonTemporal(), LD->getAlignment());
747   }
748
749   unsigned Opc = Op.getOpcode();
750   switch (Opc) {
751   default: break;
752   case ISD::AssertSext:
753     return DAG.getNode(ISD::AssertSext, dl, PVT,
754                        SExtPromoteOperand(Op.getOperand(0), PVT),
755                        Op.getOperand(1));
756   case ISD::AssertZext:
757     return DAG.getNode(ISD::AssertZext, dl, PVT,
758                        ZExtPromoteOperand(Op.getOperand(0), PVT),
759                        Op.getOperand(1));
760   case ISD::Constant: {
761     unsigned ExtOpc =
762       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
763     return DAG.getNode(ExtOpc, dl, PVT, Op);
764   }
765   }
766
767   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
768     return SDValue();
769   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
770 }
771
772 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
773   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
774     return SDValue();
775   EVT OldVT = Op.getValueType();
776   SDLoc dl(Op);
777   bool Replace = false;
778   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
779   if (NewOp.getNode() == 0)
780     return SDValue();
781   AddToWorkList(NewOp.getNode());
782
783   if (Replace)
784     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
785   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
786                      DAG.getValueType(OldVT));
787 }
788
789 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
790   EVT OldVT = Op.getValueType();
791   SDLoc dl(Op);
792   bool Replace = false;
793   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
794   if (NewOp.getNode() == 0)
795     return SDValue();
796   AddToWorkList(NewOp.getNode());
797
798   if (Replace)
799     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
800   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
801 }
802
803 /// PromoteIntBinOp - Promote the specified integer binary operation if the
804 /// target indicates it is beneficial. e.g. On x86, it's usually better to
805 /// promote i16 operations to i32 since i16 instructions are longer.
806 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
807   if (!LegalOperations)
808     return SDValue();
809
810   EVT VT = Op.getValueType();
811   if (VT.isVector() || !VT.isInteger())
812     return SDValue();
813
814   // If operation type is 'undesirable', e.g. i16 on x86, consider
815   // promoting it.
816   unsigned Opc = Op.getOpcode();
817   if (TLI.isTypeDesirableForOp(Opc, VT))
818     return SDValue();
819
820   EVT PVT = VT;
821   // Consult target whether it is a good idea to promote this operation and
822   // what's the right type to promote it to.
823   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
824     assert(PVT != VT && "Don't know what type to promote to!");
825
826     bool Replace0 = false;
827     SDValue N0 = Op.getOperand(0);
828     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
829     if (NN0.getNode() == 0)
830       return SDValue();
831
832     bool Replace1 = false;
833     SDValue N1 = Op.getOperand(1);
834     SDValue NN1;
835     if (N0 == N1)
836       NN1 = NN0;
837     else {
838       NN1 = PromoteOperand(N1, PVT, Replace1);
839       if (NN1.getNode() == 0)
840         return SDValue();
841     }
842
843     AddToWorkList(NN0.getNode());
844     if (NN1.getNode())
845       AddToWorkList(NN1.getNode());
846
847     if (Replace0)
848       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
849     if (Replace1)
850       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
851
852     DEBUG(dbgs() << "\nPromoting ";
853           Op.getNode()->dump(&DAG));
854     SDLoc dl(Op);
855     return DAG.getNode(ISD::TRUNCATE, dl, VT,
856                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
857   }
858   return SDValue();
859 }
860
861 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
862 /// target indicates it is beneficial. e.g. On x86, it's usually better to
863 /// promote i16 operations to i32 since i16 instructions are longer.
864 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
865   if (!LegalOperations)
866     return SDValue();
867
868   EVT VT = Op.getValueType();
869   if (VT.isVector() || !VT.isInteger())
870     return SDValue();
871
872   // If operation type is 'undesirable', e.g. i16 on x86, consider
873   // promoting it.
874   unsigned Opc = Op.getOpcode();
875   if (TLI.isTypeDesirableForOp(Opc, VT))
876     return SDValue();
877
878   EVT PVT = VT;
879   // Consult target whether it is a good idea to promote this operation and
880   // what's the right type to promote it to.
881   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
882     assert(PVT != VT && "Don't know what type to promote to!");
883
884     bool Replace = false;
885     SDValue N0 = Op.getOperand(0);
886     if (Opc == ISD::SRA)
887       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
888     else if (Opc == ISD::SRL)
889       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
890     else
891       N0 = PromoteOperand(N0, PVT, Replace);
892     if (N0.getNode() == 0)
893       return SDValue();
894
895     AddToWorkList(N0.getNode());
896     if (Replace)
897       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
898
899     DEBUG(dbgs() << "\nPromoting ";
900           Op.getNode()->dump(&DAG));
901     SDLoc dl(Op);
902     return DAG.getNode(ISD::TRUNCATE, dl, VT,
903                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
904   }
905   return SDValue();
906 }
907
908 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
909   if (!LegalOperations)
910     return SDValue();
911
912   EVT VT = Op.getValueType();
913   if (VT.isVector() || !VT.isInteger())
914     return SDValue();
915
916   // If operation type is 'undesirable', e.g. i16 on x86, consider
917   // promoting it.
918   unsigned Opc = Op.getOpcode();
919   if (TLI.isTypeDesirableForOp(Opc, VT))
920     return SDValue();
921
922   EVT PVT = VT;
923   // Consult target whether it is a good idea to promote this operation and
924   // what's the right type to promote it to.
925   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
926     assert(PVT != VT && "Don't know what type to promote to!");
927     // fold (aext (aext x)) -> (aext x)
928     // fold (aext (zext x)) -> (zext x)
929     // fold (aext (sext x)) -> (sext x)
930     DEBUG(dbgs() << "\nPromoting ";
931           Op.getNode()->dump(&DAG));
932     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
933   }
934   return SDValue();
935 }
936
937 bool DAGCombiner::PromoteLoad(SDValue Op) {
938   if (!LegalOperations)
939     return false;
940
941   EVT VT = Op.getValueType();
942   if (VT.isVector() || !VT.isInteger())
943     return false;
944
945   // If operation type is 'undesirable', e.g. i16 on x86, consider
946   // promoting it.
947   unsigned Opc = Op.getOpcode();
948   if (TLI.isTypeDesirableForOp(Opc, VT))
949     return false;
950
951   EVT PVT = VT;
952   // Consult target whether it is a good idea to promote this operation and
953   // what's the right type to promote it to.
954   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
955     assert(PVT != VT && "Don't know what type to promote to!");
956
957     SDLoc dl(Op);
958     SDNode *N = Op.getNode();
959     LoadSDNode *LD = cast<LoadSDNode>(N);
960     EVT MemVT = LD->getMemoryVT();
961     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
962       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
963                                                   : ISD::EXTLOAD)
964       : LD->getExtensionType();
965     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
966                                    LD->getChain(), LD->getBasePtr(),
967                                    LD->getPointerInfo(),
968                                    MemVT, LD->isVolatile(),
969                                    LD->isNonTemporal(), LD->getAlignment());
970     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
971
972     DEBUG(dbgs() << "\nPromoting ";
973           N->dump(&DAG);
974           dbgs() << "\nTo: ";
975           Result.getNode()->dump(&DAG);
976           dbgs() << '\n');
977     WorkListRemover DeadNodes(*this);
978     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
979     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
980     removeFromWorkList(N);
981     DAG.DeleteNode(N);
982     AddToWorkList(Result.getNode());
983     return true;
984   }
985   return false;
986 }
987
988
989 //===----------------------------------------------------------------------===//
990 //  Main DAG Combiner implementation
991 //===----------------------------------------------------------------------===//
992
993 void DAGCombiner::Run(CombineLevel AtLevel) {
994   // set the instance variables, so that the various visit routines may use it.
995   Level = AtLevel;
996   LegalOperations = Level >= AfterLegalizeVectorOps;
997   LegalTypes = Level >= AfterLegalizeTypes;
998
999   // Add all the dag nodes to the worklist.
1000   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1001        E = DAG.allnodes_end(); I != E; ++I)
1002     AddToWorkList(I);
1003
1004   // Create a dummy node (which is not added to allnodes), that adds a reference
1005   // to the root node, preventing it from being deleted, and tracking any
1006   // changes of the root.
1007   HandleSDNode Dummy(DAG.getRoot());
1008
1009   // The root of the dag may dangle to deleted nodes until the dag combiner is
1010   // done.  Set it to null to avoid confusion.
1011   DAG.setRoot(SDValue());
1012
1013   // while the worklist isn't empty, find a node and
1014   // try and combine it.
1015   while (!WorkListContents.empty()) {
1016     SDNode *N;
1017     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1018     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1019     // worklist *should* contain, and check the node we want to visit is should
1020     // actually be visited.
1021     do {
1022       N = WorkListOrder.pop_back_val();
1023     } while (!WorkListContents.erase(N));
1024
1025     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1026     // N is deleted from the DAG, since they too may now be dead or may have a
1027     // reduced number of uses, allowing other xforms.
1028     if (N->use_empty() && N != &Dummy) {
1029       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1030         AddToWorkList(N->getOperand(i).getNode());
1031
1032       DAG.DeleteNode(N);
1033       continue;
1034     }
1035
1036     SDValue RV = combine(N);
1037
1038     if (RV.getNode() == 0)
1039       continue;
1040
1041     ++NodesCombined;
1042
1043     // If we get back the same node we passed in, rather than a new node or
1044     // zero, we know that the node must have defined multiple values and
1045     // CombineTo was used.  Since CombineTo takes care of the worklist
1046     // mechanics for us, we have no work to do in this case.
1047     if (RV.getNode() == N)
1048       continue;
1049
1050     assert(N->getOpcode() != ISD::DELETED_NODE &&
1051            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1052            "Node was deleted but visit returned new node!");
1053
1054     DEBUG(dbgs() << "\nReplacing.3 ";
1055           N->dump(&DAG);
1056           dbgs() << "\nWith: ";
1057           RV.getNode()->dump(&DAG);
1058           dbgs() << '\n');
1059
1060     // Transfer debug value.
1061     DAG.TransferDbgValues(SDValue(N, 0), RV);
1062     WorkListRemover DeadNodes(*this);
1063     if (N->getNumValues() == RV.getNode()->getNumValues())
1064       DAG.ReplaceAllUsesWith(N, RV.getNode());
1065     else {
1066       assert(N->getValueType(0) == RV.getValueType() &&
1067              N->getNumValues() == 1 && "Type mismatch");
1068       SDValue OpV = RV;
1069       DAG.ReplaceAllUsesWith(N, &OpV);
1070     }
1071
1072     // Push the new node and any users onto the worklist
1073     AddToWorkList(RV.getNode());
1074     AddUsersToWorkList(RV.getNode());
1075
1076     // Add any uses of the old node to the worklist in case this node is the
1077     // last one that uses them.  They may become dead after this node is
1078     // deleted.
1079     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1080       AddToWorkList(N->getOperand(i).getNode());
1081
1082     // Finally, if the node is now dead, remove it from the graph.  The node
1083     // may not be dead if the replacement process recursively simplified to
1084     // something else needing this node.
1085     if (N->use_empty()) {
1086       // Nodes can be reintroduced into the worklist.  Make sure we do not
1087       // process a node that has been replaced.
1088       removeFromWorkList(N);
1089
1090       // Finally, since the node is now dead, remove it from the graph.
1091       DAG.DeleteNode(N);
1092     }
1093   }
1094
1095   // If the root changed (e.g. it was a dead load, update the root).
1096   DAG.setRoot(Dummy.getValue());
1097   DAG.RemoveDeadNodes();
1098 }
1099
1100 SDValue DAGCombiner::visit(SDNode *N) {
1101   switch (N->getOpcode()) {
1102   default: break;
1103   case ISD::TokenFactor:        return visitTokenFactor(N);
1104   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1105   case ISD::ADD:                return visitADD(N);
1106   case ISD::SUB:                return visitSUB(N);
1107   case ISD::ADDC:               return visitADDC(N);
1108   case ISD::SUBC:               return visitSUBC(N);
1109   case ISD::ADDE:               return visitADDE(N);
1110   case ISD::SUBE:               return visitSUBE(N);
1111   case ISD::MUL:                return visitMUL(N);
1112   case ISD::SDIV:               return visitSDIV(N);
1113   case ISD::UDIV:               return visitUDIV(N);
1114   case ISD::SREM:               return visitSREM(N);
1115   case ISD::UREM:               return visitUREM(N);
1116   case ISD::MULHU:              return visitMULHU(N);
1117   case ISD::MULHS:              return visitMULHS(N);
1118   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1119   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1120   case ISD::SMULO:              return visitSMULO(N);
1121   case ISD::UMULO:              return visitUMULO(N);
1122   case ISD::SDIVREM:            return visitSDIVREM(N);
1123   case ISD::UDIVREM:            return visitUDIVREM(N);
1124   case ISD::AND:                return visitAND(N);
1125   case ISD::OR:                 return visitOR(N);
1126   case ISD::XOR:                return visitXOR(N);
1127   case ISD::SHL:                return visitSHL(N);
1128   case ISD::SRA:                return visitSRA(N);
1129   case ISD::SRL:                return visitSRL(N);
1130   case ISD::CTLZ:               return visitCTLZ(N);
1131   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1132   case ISD::CTTZ:               return visitCTTZ(N);
1133   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1134   case ISD::CTPOP:              return visitCTPOP(N);
1135   case ISD::SELECT:             return visitSELECT(N);
1136   case ISD::VSELECT:            return visitVSELECT(N);
1137   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1138   case ISD::SETCC:              return visitSETCC(N);
1139   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1140   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1141   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1142   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1143   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1144   case ISD::BITCAST:            return visitBITCAST(N);
1145   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1146   case ISD::FADD:               return visitFADD(N);
1147   case ISD::FSUB:               return visitFSUB(N);
1148   case ISD::FMUL:               return visitFMUL(N);
1149   case ISD::FMA:                return visitFMA(N);
1150   case ISD::FDIV:               return visitFDIV(N);
1151   case ISD::FREM:               return visitFREM(N);
1152   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1153   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1154   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1155   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1156   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1157   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1158   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1159   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1160   case ISD::FNEG:               return visitFNEG(N);
1161   case ISD::FABS:               return visitFABS(N);
1162   case ISD::FFLOOR:             return visitFFLOOR(N);
1163   case ISD::FCEIL:              return visitFCEIL(N);
1164   case ISD::FTRUNC:             return visitFTRUNC(N);
1165   case ISD::BRCOND:             return visitBRCOND(N);
1166   case ISD::BR_CC:              return visitBR_CC(N);
1167   case ISD::LOAD:               return visitLOAD(N);
1168   case ISD::STORE:              return visitSTORE(N);
1169   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1170   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1171   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1172   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1173   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1174   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1175   }
1176   return SDValue();
1177 }
1178
1179 SDValue DAGCombiner::combine(SDNode *N) {
1180   SDValue RV = visit(N);
1181
1182   // If nothing happened, try a target-specific DAG combine.
1183   if (RV.getNode() == 0) {
1184     assert(N->getOpcode() != ISD::DELETED_NODE &&
1185            "Node was deleted but visit returned NULL!");
1186
1187     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1188         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1189
1190       // Expose the DAG combiner to the target combiner impls.
1191       TargetLowering::DAGCombinerInfo
1192         DagCombineInfo(DAG, Level, false, this);
1193
1194       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1195     }
1196   }
1197
1198   // If nothing happened still, try promoting the operation.
1199   if (RV.getNode() == 0) {
1200     switch (N->getOpcode()) {
1201     default: break;
1202     case ISD::ADD:
1203     case ISD::SUB:
1204     case ISD::MUL:
1205     case ISD::AND:
1206     case ISD::OR:
1207     case ISD::XOR:
1208       RV = PromoteIntBinOp(SDValue(N, 0));
1209       break;
1210     case ISD::SHL:
1211     case ISD::SRA:
1212     case ISD::SRL:
1213       RV = PromoteIntShiftOp(SDValue(N, 0));
1214       break;
1215     case ISD::SIGN_EXTEND:
1216     case ISD::ZERO_EXTEND:
1217     case ISD::ANY_EXTEND:
1218       RV = PromoteExtend(SDValue(N, 0));
1219       break;
1220     case ISD::LOAD:
1221       if (PromoteLoad(SDValue(N, 0)))
1222         RV = SDValue(N, 0);
1223       break;
1224     }
1225   }
1226
1227   // If N is a commutative binary node, try commuting it to enable more
1228   // sdisel CSE.
1229   if (RV.getNode() == 0 &&
1230       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1231       N->getNumValues() == 1) {
1232     SDValue N0 = N->getOperand(0);
1233     SDValue N1 = N->getOperand(1);
1234
1235     // Constant operands are canonicalized to RHS.
1236     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1237       SDValue Ops[] = { N1, N0 };
1238       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1239                                             Ops, 2);
1240       if (CSENode)
1241         return SDValue(CSENode, 0);
1242     }
1243   }
1244
1245   return RV;
1246 }
1247
1248 /// getInputChainForNode - Given a node, return its input chain if it has one,
1249 /// otherwise return a null sd operand.
1250 static SDValue getInputChainForNode(SDNode *N) {
1251   if (unsigned NumOps = N->getNumOperands()) {
1252     if (N->getOperand(0).getValueType() == MVT::Other)
1253       return N->getOperand(0);
1254     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1255       return N->getOperand(NumOps-1);
1256     for (unsigned i = 1; i < NumOps-1; ++i)
1257       if (N->getOperand(i).getValueType() == MVT::Other)
1258         return N->getOperand(i);
1259   }
1260   return SDValue();
1261 }
1262
1263 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1264   // If N has two operands, where one has an input chain equal to the other,
1265   // the 'other' chain is redundant.
1266   if (N->getNumOperands() == 2) {
1267     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1268       return N->getOperand(0);
1269     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1270       return N->getOperand(1);
1271   }
1272
1273   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1274   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1275   SmallPtrSet<SDNode*, 16> SeenOps;
1276   bool Changed = false;             // If we should replace this token factor.
1277
1278   // Start out with this token factor.
1279   TFs.push_back(N);
1280
1281   // Iterate through token factors.  The TFs grows when new token factors are
1282   // encountered.
1283   for (unsigned i = 0; i < TFs.size(); ++i) {
1284     SDNode *TF = TFs[i];
1285
1286     // Check each of the operands.
1287     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1288       SDValue Op = TF->getOperand(i);
1289
1290       switch (Op.getOpcode()) {
1291       case ISD::EntryToken:
1292         // Entry tokens don't need to be added to the list. They are
1293         // rededundant.
1294         Changed = true;
1295         break;
1296
1297       case ISD::TokenFactor:
1298         if (Op.hasOneUse() &&
1299             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1300           // Queue up for processing.
1301           TFs.push_back(Op.getNode());
1302           // Clean up in case the token factor is removed.
1303           AddToWorkList(Op.getNode());
1304           Changed = true;
1305           break;
1306         }
1307         // Fall thru
1308
1309       default:
1310         // Only add if it isn't already in the list.
1311         if (SeenOps.insert(Op.getNode()))
1312           Ops.push_back(Op);
1313         else
1314           Changed = true;
1315         break;
1316       }
1317     }
1318   }
1319
1320   SDValue Result;
1321
1322   // If we've change things around then replace token factor.
1323   if (Changed) {
1324     if (Ops.empty()) {
1325       // The entry token is the only possible outcome.
1326       Result = DAG.getEntryNode();
1327     } else {
1328       // New and improved token factor.
1329       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1330                            MVT::Other, &Ops[0], Ops.size());
1331     }
1332
1333     // Don't add users to work list.
1334     return CombineTo(N, Result, false);
1335   }
1336
1337   return Result;
1338 }
1339
1340 /// MERGE_VALUES can always be eliminated.
1341 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1342   WorkListRemover DeadNodes(*this);
1343   // Replacing results may cause a different MERGE_VALUES to suddenly
1344   // be CSE'd with N, and carry its uses with it. Iterate until no
1345   // uses remain, to ensure that the node can be safely deleted.
1346   // First add the users of this node to the work list so that they
1347   // can be tried again once they have new operands.
1348   AddUsersToWorkList(N);
1349   do {
1350     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1351       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1352   } while (!N->use_empty());
1353   removeFromWorkList(N);
1354   DAG.DeleteNode(N);
1355   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1356 }
1357
1358 static
1359 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1360                               SelectionDAG &DAG) {
1361   EVT VT = N0.getValueType();
1362   SDValue N00 = N0.getOperand(0);
1363   SDValue N01 = N0.getOperand(1);
1364   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1365
1366   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1367       isa<ConstantSDNode>(N00.getOperand(1))) {
1368     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1369     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1370                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1371                                  N00.getOperand(0), N01),
1372                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1373                                  N00.getOperand(1), N01));
1374     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1375   }
1376
1377   return SDValue();
1378 }
1379
1380 SDValue DAGCombiner::visitADD(SDNode *N) {
1381   SDValue N0 = N->getOperand(0);
1382   SDValue N1 = N->getOperand(1);
1383   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1384   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1385   EVT VT = N0.getValueType();
1386
1387   // fold vector ops
1388   if (VT.isVector()) {
1389     SDValue FoldedVOp = SimplifyVBinOp(N);
1390     if (FoldedVOp.getNode()) return FoldedVOp;
1391
1392     // fold (add x, 0) -> x, vector edition
1393     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1394       return N0;
1395     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1396       return N1;
1397   }
1398
1399   // fold (add x, undef) -> undef
1400   if (N0.getOpcode() == ISD::UNDEF)
1401     return N0;
1402   if (N1.getOpcode() == ISD::UNDEF)
1403     return N1;
1404   // fold (add c1, c2) -> c1+c2
1405   if (N0C && N1C)
1406     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1407   // canonicalize constant to RHS
1408   if (N0C && !N1C)
1409     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1410   // fold (add x, 0) -> x
1411   if (N1C && N1C->isNullValue())
1412     return N0;
1413   // fold (add Sym, c) -> Sym+c
1414   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1415     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1416         GA->getOpcode() == ISD::GlobalAddress)
1417       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1418                                   GA->getOffset() +
1419                                     (uint64_t)N1C->getSExtValue());
1420   // fold ((c1-A)+c2) -> (c1+c2)-A
1421   if (N1C && N0.getOpcode() == ISD::SUB)
1422     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1423       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1424                          DAG.getConstant(N1C->getAPIntValue()+
1425                                          N0C->getAPIntValue(), VT),
1426                          N0.getOperand(1));
1427   // reassociate add
1428   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1429   if (RADD.getNode() != 0)
1430     return RADD;
1431   // fold ((0-A) + B) -> B-A
1432   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1433       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1434     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1435   // fold (A + (0-B)) -> A-B
1436   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1437       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1438     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1439   // fold (A+(B-A)) -> B
1440   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1441     return N1.getOperand(0);
1442   // fold ((B-A)+A) -> B
1443   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1444     return N0.getOperand(0);
1445   // fold (A+(B-(A+C))) to (B-C)
1446   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1447       N0 == N1.getOperand(1).getOperand(0))
1448     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1449                        N1.getOperand(1).getOperand(1));
1450   // fold (A+(B-(C+A))) to (B-C)
1451   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1452       N0 == N1.getOperand(1).getOperand(1))
1453     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1454                        N1.getOperand(1).getOperand(0));
1455   // fold (A+((B-A)+or-C)) to (B+or-C)
1456   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1457       N1.getOperand(0).getOpcode() == ISD::SUB &&
1458       N0 == N1.getOperand(0).getOperand(1))
1459     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1460                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1461
1462   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1463   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1464     SDValue N00 = N0.getOperand(0);
1465     SDValue N01 = N0.getOperand(1);
1466     SDValue N10 = N1.getOperand(0);
1467     SDValue N11 = N1.getOperand(1);
1468
1469     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1470       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1471                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1472                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1473   }
1474
1475   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1476     return SDValue(N, 0);
1477
1478   // fold (a+b) -> (a|b) iff a and b share no bits.
1479   if (VT.isInteger() && !VT.isVector()) {
1480     APInt LHSZero, LHSOne;
1481     APInt RHSZero, RHSOne;
1482     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1483
1484     if (LHSZero.getBoolValue()) {
1485       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1486
1487       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1488       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1489       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1490         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1491     }
1492   }
1493
1494   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1495   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1496     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1497     if (Result.getNode()) return Result;
1498   }
1499   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1500     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1501     if (Result.getNode()) return Result;
1502   }
1503
1504   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1505   if (N1.getOpcode() == ISD::SHL &&
1506       N1.getOperand(0).getOpcode() == ISD::SUB)
1507     if (ConstantSDNode *C =
1508           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1509       if (C->getAPIntValue() == 0)
1510         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1511                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1512                                        N1.getOperand(0).getOperand(1),
1513                                        N1.getOperand(1)));
1514   if (N0.getOpcode() == ISD::SHL &&
1515       N0.getOperand(0).getOpcode() == ISD::SUB)
1516     if (ConstantSDNode *C =
1517           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1518       if (C->getAPIntValue() == 0)
1519         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1520                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1521                                        N0.getOperand(0).getOperand(1),
1522                                        N0.getOperand(1)));
1523
1524   if (N1.getOpcode() == ISD::AND) {
1525     SDValue AndOp0 = N1.getOperand(0);
1526     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1527     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1528     unsigned DestBits = VT.getScalarType().getSizeInBits();
1529
1530     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1531     // and similar xforms where the inner op is either ~0 or 0.
1532     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1533       SDLoc DL(N);
1534       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1535     }
1536   }
1537
1538   // add (sext i1), X -> sub X, (zext i1)
1539   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1540       N0.getOperand(0).getValueType() == MVT::i1 &&
1541       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1542     SDLoc DL(N);
1543     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1544     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1545   }
1546
1547   return SDValue();
1548 }
1549
1550 SDValue DAGCombiner::visitADDC(SDNode *N) {
1551   SDValue N0 = N->getOperand(0);
1552   SDValue N1 = N->getOperand(1);
1553   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1554   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1555   EVT VT = N0.getValueType();
1556
1557   // If the flag result is dead, turn this into an ADD.
1558   if (!N->hasAnyUseOfValue(1))
1559     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1560                      DAG.getNode(ISD::CARRY_FALSE,
1561                                  SDLoc(N), MVT::Glue));
1562
1563   // canonicalize constant to RHS.
1564   if (N0C && !N1C)
1565     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1566
1567   // fold (addc x, 0) -> x + no carry out
1568   if (N1C && N1C->isNullValue())
1569     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1570                                         SDLoc(N), MVT::Glue));
1571
1572   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1573   APInt LHSZero, LHSOne;
1574   APInt RHSZero, RHSOne;
1575   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1576
1577   if (LHSZero.getBoolValue()) {
1578     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1579
1580     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1581     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1582     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1583       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1584                        DAG.getNode(ISD::CARRY_FALSE,
1585                                    SDLoc(N), MVT::Glue));
1586   }
1587
1588   return SDValue();
1589 }
1590
1591 SDValue DAGCombiner::visitADDE(SDNode *N) {
1592   SDValue N0 = N->getOperand(0);
1593   SDValue N1 = N->getOperand(1);
1594   SDValue CarryIn = N->getOperand(2);
1595   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1596   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1597
1598   // canonicalize constant to RHS
1599   if (N0C && !N1C)
1600     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1601                        N1, N0, CarryIn);
1602
1603   // fold (adde x, y, false) -> (addc x, y)
1604   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1605     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1606
1607   return SDValue();
1608 }
1609
1610 // Since it may not be valid to emit a fold to zero for vector initializers
1611 // check if we can before folding.
1612 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1613                              SelectionDAG &DAG, bool LegalOperations) {
1614   if (!VT.isVector()) {
1615     return DAG.getConstant(0, VT);
1616   }
1617   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1618     // Produce a vector of zeros.
1619     SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1620     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1621     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1622       &Ops[0], Ops.size());
1623   }
1624   return SDValue();
1625 }
1626
1627 SDValue DAGCombiner::visitSUB(SDNode *N) {
1628   SDValue N0 = N->getOperand(0);
1629   SDValue N1 = N->getOperand(1);
1630   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1631   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1632   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1633     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1634   EVT VT = N0.getValueType();
1635
1636   // fold vector ops
1637   if (VT.isVector()) {
1638     SDValue FoldedVOp = SimplifyVBinOp(N);
1639     if (FoldedVOp.getNode()) return FoldedVOp;
1640
1641     // fold (sub x, 0) -> x, vector edition
1642     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1643       return N0;
1644   }
1645
1646   // fold (sub x, x) -> 0
1647   // FIXME: Refactor this and xor and other similar operations together.
1648   if (N0 == N1)
1649     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations);
1650   // fold (sub c1, c2) -> c1-c2
1651   if (N0C && N1C)
1652     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1653   // fold (sub x, c) -> (add x, -c)
1654   if (N1C)
1655     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1656                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1657   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1658   if (N0C && N0C->isAllOnesValue())
1659     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1660   // fold A-(A-B) -> B
1661   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1662     return N1.getOperand(1);
1663   // fold (A+B)-A -> B
1664   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1665     return N0.getOperand(1);
1666   // fold (A+B)-B -> A
1667   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1668     return N0.getOperand(0);
1669   // fold C2-(A+C1) -> (C2-C1)-A
1670   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1671     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1672                                    VT);
1673     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1674                        N1.getOperand(0));
1675   }
1676   // fold ((A+(B+or-C))-B) -> A+or-C
1677   if (N0.getOpcode() == ISD::ADD &&
1678       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1679        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1680       N0.getOperand(1).getOperand(0) == N1)
1681     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1682                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1683   // fold ((A+(C+B))-B) -> A+C
1684   if (N0.getOpcode() == ISD::ADD &&
1685       N0.getOperand(1).getOpcode() == ISD::ADD &&
1686       N0.getOperand(1).getOperand(1) == N1)
1687     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1688                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1689   // fold ((A-(B-C))-C) -> A-B
1690   if (N0.getOpcode() == ISD::SUB &&
1691       N0.getOperand(1).getOpcode() == ISD::SUB &&
1692       N0.getOperand(1).getOperand(1) == N1)
1693     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1694                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1695
1696   // If either operand of a sub is undef, the result is undef
1697   if (N0.getOpcode() == ISD::UNDEF)
1698     return N0;
1699   if (N1.getOpcode() == ISD::UNDEF)
1700     return N1;
1701
1702   // If the relocation model supports it, consider symbol offsets.
1703   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1704     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1705       // fold (sub Sym, c) -> Sym-c
1706       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1707         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1708                                     GA->getOffset() -
1709                                       (uint64_t)N1C->getSExtValue());
1710       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1711       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1712         if (GA->getGlobal() == GB->getGlobal())
1713           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1714                                  VT);
1715     }
1716
1717   return SDValue();
1718 }
1719
1720 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1721   SDValue N0 = N->getOperand(0);
1722   SDValue N1 = N->getOperand(1);
1723   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1724   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1725   EVT VT = N0.getValueType();
1726
1727   // If the flag result is dead, turn this into an SUB.
1728   if (!N->hasAnyUseOfValue(1))
1729     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1730                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1731                                  MVT::Glue));
1732
1733   // fold (subc x, x) -> 0 + no borrow
1734   if (N0 == N1)
1735     return CombineTo(N, DAG.getConstant(0, VT),
1736                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1737                                  MVT::Glue));
1738
1739   // fold (subc x, 0) -> x + no borrow
1740   if (N1C && N1C->isNullValue())
1741     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1742                                         MVT::Glue));
1743
1744   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1745   if (N0C && N0C->isAllOnesValue())
1746     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1747                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1748                                  MVT::Glue));
1749
1750   return SDValue();
1751 }
1752
1753 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1754   SDValue N0 = N->getOperand(0);
1755   SDValue N1 = N->getOperand(1);
1756   SDValue CarryIn = N->getOperand(2);
1757
1758   // fold (sube x, y, false) -> (subc x, y)
1759   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1760     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1761
1762   return SDValue();
1763 }
1764
1765 SDValue DAGCombiner::visitMUL(SDNode *N) {
1766   SDValue N0 = N->getOperand(0);
1767   SDValue N1 = N->getOperand(1);
1768   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1769   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1770   EVT VT = N0.getValueType();
1771
1772   // fold vector ops
1773   if (VT.isVector()) {
1774     SDValue FoldedVOp = SimplifyVBinOp(N);
1775     if (FoldedVOp.getNode()) return FoldedVOp;
1776   }
1777
1778   // fold (mul x, undef) -> 0
1779   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1780     return DAG.getConstant(0, VT);
1781   // fold (mul c1, c2) -> c1*c2
1782   if (N0C && N1C)
1783     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1784   // canonicalize constant to RHS
1785   if (N0C && !N1C)
1786     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1787   // fold (mul x, 0) -> 0
1788   if (N1C && N1C->isNullValue())
1789     return N1;
1790   // fold (mul x, -1) -> 0-x
1791   if (N1C && N1C->isAllOnesValue())
1792     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1793                        DAG.getConstant(0, VT), N0);
1794   // fold (mul x, (1 << c)) -> x << c
1795   if (N1C && N1C->getAPIntValue().isPowerOf2())
1796     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1797                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1798                                        getShiftAmountTy(N0.getValueType())));
1799   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1800   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1801     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1802     // FIXME: If the input is something that is easily negated (e.g. a
1803     // single-use add), we should put the negate there.
1804     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1805                        DAG.getConstant(0, VT),
1806                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1807                             DAG.getConstant(Log2Val,
1808                                       getShiftAmountTy(N0.getValueType()))));
1809   }
1810   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1811   if (N1C && N0.getOpcode() == ISD::SHL &&
1812       isa<ConstantSDNode>(N0.getOperand(1))) {
1813     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1814                              N1, N0.getOperand(1));
1815     AddToWorkList(C3.getNode());
1816     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1817                        N0.getOperand(0), C3);
1818   }
1819
1820   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1821   // use.
1822   {
1823     SDValue Sh(0,0), Y(0,0);
1824     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1825     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1826         N0.getNode()->hasOneUse()) {
1827       Sh = N0; Y = N1;
1828     } else if (N1.getOpcode() == ISD::SHL &&
1829                isa<ConstantSDNode>(N1.getOperand(1)) &&
1830                N1.getNode()->hasOneUse()) {
1831       Sh = N1; Y = N0;
1832     }
1833
1834     if (Sh.getNode()) {
1835       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1836                                 Sh.getOperand(0), Y);
1837       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1838                          Mul, Sh.getOperand(1));
1839     }
1840   }
1841
1842   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1843   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1844       isa<ConstantSDNode>(N0.getOperand(1)))
1845     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1846                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1847                                    N0.getOperand(0), N1),
1848                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1849                                    N0.getOperand(1), N1));
1850
1851   // reassociate mul
1852   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1853   if (RMUL.getNode() != 0)
1854     return RMUL;
1855
1856   return SDValue();
1857 }
1858
1859 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1860   SDValue N0 = N->getOperand(0);
1861   SDValue N1 = N->getOperand(1);
1862   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1863   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1864   EVT VT = N->getValueType(0);
1865
1866   // fold vector ops
1867   if (VT.isVector()) {
1868     SDValue FoldedVOp = SimplifyVBinOp(N);
1869     if (FoldedVOp.getNode()) return FoldedVOp;
1870   }
1871
1872   // fold (sdiv c1, c2) -> c1/c2
1873   if (N0C && N1C && !N1C->isNullValue())
1874     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1875   // fold (sdiv X, 1) -> X
1876   if (N1C && N1C->getAPIntValue() == 1LL)
1877     return N0;
1878   // fold (sdiv X, -1) -> 0-X
1879   if (N1C && N1C->isAllOnesValue())
1880     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1881                        DAG.getConstant(0, VT), N0);
1882   // If we know the sign bits of both operands are zero, strength reduce to a
1883   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1884   if (!VT.isVector()) {
1885     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1886       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1887                          N0, N1);
1888   }
1889   // fold (sdiv X, pow2) -> simple ops after legalize
1890   if (N1C && !N1C->isNullValue() &&
1891       (N1C->getAPIntValue().isPowerOf2() ||
1892        (-N1C->getAPIntValue()).isPowerOf2())) {
1893     // If dividing by powers of two is cheap, then don't perform the following
1894     // fold.
1895     if (TLI.isPow2DivCheap())
1896       return SDValue();
1897
1898     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1899
1900     // Splat the sign bit into the register
1901     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1902                               DAG.getConstant(VT.getSizeInBits()-1,
1903                                        getShiftAmountTy(N0.getValueType())));
1904     AddToWorkList(SGN.getNode());
1905
1906     // Add (N0 < 0) ? abs2 - 1 : 0;
1907     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1908                               DAG.getConstant(VT.getSizeInBits() - lg2,
1909                                        getShiftAmountTy(SGN.getValueType())));
1910     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1911     AddToWorkList(SRL.getNode());
1912     AddToWorkList(ADD.getNode());    // Divide by pow2
1913     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1914                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1915
1916     // If we're dividing by a positive value, we're done.  Otherwise, we must
1917     // negate the result.
1918     if (N1C->getAPIntValue().isNonNegative())
1919       return SRA;
1920
1921     AddToWorkList(SRA.getNode());
1922     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1923                        DAG.getConstant(0, VT), SRA);
1924   }
1925
1926   // if integer divide is expensive and we satisfy the requirements, emit an
1927   // alternate sequence.
1928   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1929     SDValue Op = BuildSDIV(N);
1930     if (Op.getNode()) return Op;
1931   }
1932
1933   // undef / X -> 0
1934   if (N0.getOpcode() == ISD::UNDEF)
1935     return DAG.getConstant(0, VT);
1936   // X / undef -> undef
1937   if (N1.getOpcode() == ISD::UNDEF)
1938     return N1;
1939
1940   return SDValue();
1941 }
1942
1943 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1944   SDValue N0 = N->getOperand(0);
1945   SDValue N1 = N->getOperand(1);
1946   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1947   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1948   EVT VT = N->getValueType(0);
1949
1950   // fold vector ops
1951   if (VT.isVector()) {
1952     SDValue FoldedVOp = SimplifyVBinOp(N);
1953     if (FoldedVOp.getNode()) return FoldedVOp;
1954   }
1955
1956   // fold (udiv c1, c2) -> c1/c2
1957   if (N0C && N1C && !N1C->isNullValue())
1958     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1959   // fold (udiv x, (1 << c)) -> x >>u c
1960   if (N1C && N1C->getAPIntValue().isPowerOf2())
1961     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
1962                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1963                                        getShiftAmountTy(N0.getValueType())));
1964   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1965   if (N1.getOpcode() == ISD::SHL) {
1966     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1967       if (SHC->getAPIntValue().isPowerOf2()) {
1968         EVT ADDVT = N1.getOperand(1).getValueType();
1969         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
1970                                   N1.getOperand(1),
1971                                   DAG.getConstant(SHC->getAPIntValue()
1972                                                                   .logBase2(),
1973                                                   ADDVT));
1974         AddToWorkList(Add.getNode());
1975         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
1976       }
1977     }
1978   }
1979   // fold (udiv x, c) -> alternate
1980   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1981     SDValue Op = BuildUDIV(N);
1982     if (Op.getNode()) return Op;
1983   }
1984
1985   // undef / X -> 0
1986   if (N0.getOpcode() == ISD::UNDEF)
1987     return DAG.getConstant(0, VT);
1988   // X / undef -> undef
1989   if (N1.getOpcode() == ISD::UNDEF)
1990     return N1;
1991
1992   return SDValue();
1993 }
1994
1995 SDValue DAGCombiner::visitSREM(SDNode *N) {
1996   SDValue N0 = N->getOperand(0);
1997   SDValue N1 = N->getOperand(1);
1998   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1999   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2000   EVT VT = N->getValueType(0);
2001
2002   // fold (srem c1, c2) -> c1%c2
2003   if (N0C && N1C && !N1C->isNullValue())
2004     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2005   // If we know the sign bits of both operands are zero, strength reduce to a
2006   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2007   if (!VT.isVector()) {
2008     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2009       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2010   }
2011
2012   // If X/C can be simplified by the division-by-constant logic, lower
2013   // X%C to the equivalent of X-X/C*C.
2014   if (N1C && !N1C->isNullValue()) {
2015     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2016     AddToWorkList(Div.getNode());
2017     SDValue OptimizedDiv = combine(Div.getNode());
2018     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2019       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2020                                 OptimizedDiv, N1);
2021       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2022       AddToWorkList(Mul.getNode());
2023       return Sub;
2024     }
2025   }
2026
2027   // undef % X -> 0
2028   if (N0.getOpcode() == ISD::UNDEF)
2029     return DAG.getConstant(0, VT);
2030   // X % undef -> undef
2031   if (N1.getOpcode() == ISD::UNDEF)
2032     return N1;
2033
2034   return SDValue();
2035 }
2036
2037 SDValue DAGCombiner::visitUREM(SDNode *N) {
2038   SDValue N0 = N->getOperand(0);
2039   SDValue N1 = N->getOperand(1);
2040   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2041   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2042   EVT VT = N->getValueType(0);
2043
2044   // fold (urem c1, c2) -> c1%c2
2045   if (N0C && N1C && !N1C->isNullValue())
2046     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2047   // fold (urem x, pow2) -> (and x, pow2-1)
2048   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2049     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2050                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2051   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2052   if (N1.getOpcode() == ISD::SHL) {
2053     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2054       if (SHC->getAPIntValue().isPowerOf2()) {
2055         SDValue Add =
2056           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2057                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2058                                  VT));
2059         AddToWorkList(Add.getNode());
2060         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2061       }
2062     }
2063   }
2064
2065   // If X/C can be simplified by the division-by-constant logic, lower
2066   // X%C to the equivalent of X-X/C*C.
2067   if (N1C && !N1C->isNullValue()) {
2068     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2069     AddToWorkList(Div.getNode());
2070     SDValue OptimizedDiv = combine(Div.getNode());
2071     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2072       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2073                                 OptimizedDiv, N1);
2074       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2075       AddToWorkList(Mul.getNode());
2076       return Sub;
2077     }
2078   }
2079
2080   // undef % X -> 0
2081   if (N0.getOpcode() == ISD::UNDEF)
2082     return DAG.getConstant(0, VT);
2083   // X % undef -> undef
2084   if (N1.getOpcode() == ISD::UNDEF)
2085     return N1;
2086
2087   return SDValue();
2088 }
2089
2090 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2091   SDValue N0 = N->getOperand(0);
2092   SDValue N1 = N->getOperand(1);
2093   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2094   EVT VT = N->getValueType(0);
2095   SDLoc DL(N);
2096
2097   // fold (mulhs x, 0) -> 0
2098   if (N1C && N1C->isNullValue())
2099     return N1;
2100   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2101   if (N1C && N1C->getAPIntValue() == 1)
2102     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2103                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2104                                        getShiftAmountTy(N0.getValueType())));
2105   // fold (mulhs x, undef) -> 0
2106   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2107     return DAG.getConstant(0, VT);
2108
2109   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2110   // plus a shift.
2111   if (VT.isSimple() && !VT.isVector()) {
2112     MVT Simple = VT.getSimpleVT();
2113     unsigned SimpleSize = Simple.getSizeInBits();
2114     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2115     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2116       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2117       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2118       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2119       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2120             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2121       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2122     }
2123   }
2124
2125   return SDValue();
2126 }
2127
2128 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2129   SDValue N0 = N->getOperand(0);
2130   SDValue N1 = N->getOperand(1);
2131   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2132   EVT VT = N->getValueType(0);
2133   SDLoc DL(N);
2134
2135   // fold (mulhu x, 0) -> 0
2136   if (N1C && N1C->isNullValue())
2137     return N1;
2138   // fold (mulhu x, 1) -> 0
2139   if (N1C && N1C->getAPIntValue() == 1)
2140     return DAG.getConstant(0, N0.getValueType());
2141   // fold (mulhu x, undef) -> 0
2142   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2143     return DAG.getConstant(0, VT);
2144
2145   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2146   // plus a shift.
2147   if (VT.isSimple() && !VT.isVector()) {
2148     MVT Simple = VT.getSimpleVT();
2149     unsigned SimpleSize = Simple.getSizeInBits();
2150     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2151     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2152       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2153       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2154       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2155       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2156             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2157       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2158     }
2159   }
2160
2161   return SDValue();
2162 }
2163
2164 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2165 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2166 /// that are being performed. Return true if a simplification was made.
2167 ///
2168 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2169                                                 unsigned HiOp) {
2170   // If the high half is not needed, just compute the low half.
2171   bool HiExists = N->hasAnyUseOfValue(1);
2172   if (!HiExists &&
2173       (!LegalOperations ||
2174        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2175     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2176                               N->op_begin(), N->getNumOperands());
2177     return CombineTo(N, Res, Res);
2178   }
2179
2180   // If the low half is not needed, just compute the high half.
2181   bool LoExists = N->hasAnyUseOfValue(0);
2182   if (!LoExists &&
2183       (!LegalOperations ||
2184        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2185     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2186                               N->op_begin(), N->getNumOperands());
2187     return CombineTo(N, Res, Res);
2188   }
2189
2190   // If both halves are used, return as it is.
2191   if (LoExists && HiExists)
2192     return SDValue();
2193
2194   // If the two computed results can be simplified separately, separate them.
2195   if (LoExists) {
2196     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2197                              N->op_begin(), N->getNumOperands());
2198     AddToWorkList(Lo.getNode());
2199     SDValue LoOpt = combine(Lo.getNode());
2200     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2201         (!LegalOperations ||
2202          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2203       return CombineTo(N, LoOpt, LoOpt);
2204   }
2205
2206   if (HiExists) {
2207     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2208                              N->op_begin(), N->getNumOperands());
2209     AddToWorkList(Hi.getNode());
2210     SDValue HiOpt = combine(Hi.getNode());
2211     if (HiOpt.getNode() && HiOpt != Hi &&
2212         (!LegalOperations ||
2213          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2214       return CombineTo(N, HiOpt, HiOpt);
2215   }
2216
2217   return SDValue();
2218 }
2219
2220 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2221   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2222   if (Res.getNode()) return Res;
2223
2224   EVT VT = N->getValueType(0);
2225   SDLoc DL(N);
2226
2227   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2228   // plus a shift.
2229   if (VT.isSimple() && !VT.isVector()) {
2230     MVT Simple = VT.getSimpleVT();
2231     unsigned SimpleSize = Simple.getSizeInBits();
2232     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2233     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2234       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2235       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2236       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2237       // Compute the high part as N1.
2238       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2239             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2240       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2241       // Compute the low part as N0.
2242       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2243       return CombineTo(N, Lo, Hi);
2244     }
2245   }
2246
2247   return SDValue();
2248 }
2249
2250 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2251   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2252   if (Res.getNode()) return Res;
2253
2254   EVT VT = N->getValueType(0);
2255   SDLoc DL(N);
2256
2257   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2258   // plus a shift.
2259   if (VT.isSimple() && !VT.isVector()) {
2260     MVT Simple = VT.getSimpleVT();
2261     unsigned SimpleSize = Simple.getSizeInBits();
2262     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2263     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2264       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2265       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2266       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2267       // Compute the high part as N1.
2268       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2269             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2270       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2271       // Compute the low part as N0.
2272       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2273       return CombineTo(N, Lo, Hi);
2274     }
2275   }
2276
2277   return SDValue();
2278 }
2279
2280 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2281   // (smulo x, 2) -> (saddo x, x)
2282   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2283     if (C2->getAPIntValue() == 2)
2284       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2285                          N->getOperand(0), N->getOperand(0));
2286
2287   return SDValue();
2288 }
2289
2290 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2291   // (umulo x, 2) -> (uaddo x, x)
2292   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2293     if (C2->getAPIntValue() == 2)
2294       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2295                          N->getOperand(0), N->getOperand(0));
2296
2297   return SDValue();
2298 }
2299
2300 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2301   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2302   if (Res.getNode()) return Res;
2303
2304   return SDValue();
2305 }
2306
2307 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2308   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2309   if (Res.getNode()) return Res;
2310
2311   return SDValue();
2312 }
2313
2314 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2315 /// two operands of the same opcode, try to simplify it.
2316 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2317   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2318   EVT VT = N0.getValueType();
2319   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2320
2321   // Bail early if none of these transforms apply.
2322   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2323
2324   // For each of OP in AND/OR/XOR:
2325   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2326   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2327   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2328   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2329   //
2330   // do not sink logical op inside of a vector extend, since it may combine
2331   // into a vsetcc.
2332   EVT Op0VT = N0.getOperand(0).getValueType();
2333   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2334        N0.getOpcode() == ISD::SIGN_EXTEND ||
2335        // Avoid infinite looping with PromoteIntBinOp.
2336        (N0.getOpcode() == ISD::ANY_EXTEND &&
2337         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2338        (N0.getOpcode() == ISD::TRUNCATE &&
2339         (!TLI.isZExtFree(VT, Op0VT) ||
2340          !TLI.isTruncateFree(Op0VT, VT)) &&
2341         TLI.isTypeLegal(Op0VT))) &&
2342       !VT.isVector() &&
2343       Op0VT == N1.getOperand(0).getValueType() &&
2344       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2345     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2346                                  N0.getOperand(0).getValueType(),
2347                                  N0.getOperand(0), N1.getOperand(0));
2348     AddToWorkList(ORNode.getNode());
2349     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2350   }
2351
2352   // For each of OP in SHL/SRL/SRA/AND...
2353   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2354   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2355   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2356   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2357        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2358       N0.getOperand(1) == N1.getOperand(1)) {
2359     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2360                                  N0.getOperand(0).getValueType(),
2361                                  N0.getOperand(0), N1.getOperand(0));
2362     AddToWorkList(ORNode.getNode());
2363     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2364                        ORNode, N0.getOperand(1));
2365   }
2366
2367   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2368   // Only perform this optimization after type legalization and before
2369   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2370   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2371   // we don't want to undo this promotion.
2372   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2373   // on scalars.
2374   if ((N0.getOpcode() == ISD::BITCAST ||
2375        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2376       Level == AfterLegalizeTypes) {
2377     SDValue In0 = N0.getOperand(0);
2378     SDValue In1 = N1.getOperand(0);
2379     EVT In0Ty = In0.getValueType();
2380     EVT In1Ty = In1.getValueType();
2381     SDLoc DL(N);
2382     // If both incoming values are integers, and the original types are the
2383     // same.
2384     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2385       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2386       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2387       AddToWorkList(Op.getNode());
2388       return BC;
2389     }
2390   }
2391
2392   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2393   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2394   // If both shuffles use the same mask, and both shuffle within a single
2395   // vector, then it is worthwhile to move the swizzle after the operation.
2396   // The type-legalizer generates this pattern when loading illegal
2397   // vector types from memory. In many cases this allows additional shuffle
2398   // optimizations.
2399   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2400       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2401       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2402     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2403     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2404
2405     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2406            "Inputs to shuffles are not the same type");
2407
2408     unsigned NumElts = VT.getVectorNumElements();
2409
2410     // Check that both shuffles use the same mask. The masks are known to be of
2411     // the same length because the result vector type is the same.
2412     bool SameMask = true;
2413     for (unsigned i = 0; i != NumElts; ++i) {
2414       int Idx0 = SVN0->getMaskElt(i);
2415       int Idx1 = SVN1->getMaskElt(i);
2416       if (Idx0 != Idx1) {
2417         SameMask = false;
2418         break;
2419       }
2420     }
2421
2422     if (SameMask) {
2423       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2424                                N0.getOperand(0), N1.getOperand(0));
2425       AddToWorkList(Op.getNode());
2426       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2427                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2428     }
2429   }
2430
2431   return SDValue();
2432 }
2433
2434 SDValue DAGCombiner::visitAND(SDNode *N) {
2435   SDValue N0 = N->getOperand(0);
2436   SDValue N1 = N->getOperand(1);
2437   SDValue LL, LR, RL, RR, CC0, CC1;
2438   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2439   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2440   EVT VT = N1.getValueType();
2441   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2442
2443   // fold vector ops
2444   if (VT.isVector()) {
2445     SDValue FoldedVOp = SimplifyVBinOp(N);
2446     if (FoldedVOp.getNode()) return FoldedVOp;
2447
2448     // fold (and x, 0) -> 0, vector edition
2449     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2450       return N0;
2451     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2452       return N1;
2453
2454     // fold (and x, -1) -> x, vector edition
2455     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2456       return N1;
2457     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2458       return N0;
2459   }
2460
2461   // fold (and x, undef) -> 0
2462   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2463     return DAG.getConstant(0, VT);
2464   // fold (and c1, c2) -> c1&c2
2465   if (N0C && N1C)
2466     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2467   // canonicalize constant to RHS
2468   if (N0C && !N1C)
2469     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2470   // fold (and x, -1) -> x
2471   if (N1C && N1C->isAllOnesValue())
2472     return N0;
2473   // if (and x, c) is known to be zero, return 0
2474   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2475                                    APInt::getAllOnesValue(BitWidth)))
2476     return DAG.getConstant(0, VT);
2477   // reassociate and
2478   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2479   if (RAND.getNode() != 0)
2480     return RAND;
2481   // fold (and (or x, C), D) -> D if (C & D) == D
2482   if (N1C && N0.getOpcode() == ISD::OR)
2483     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2484       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2485         return N1;
2486   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2487   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2488     SDValue N0Op0 = N0.getOperand(0);
2489     APInt Mask = ~N1C->getAPIntValue();
2490     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2491     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2492       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2493                                  N0.getValueType(), N0Op0);
2494
2495       // Replace uses of the AND with uses of the Zero extend node.
2496       CombineTo(N, Zext);
2497
2498       // We actually want to replace all uses of the any_extend with the
2499       // zero_extend, to avoid duplicating things.  This will later cause this
2500       // AND to be folded.
2501       CombineTo(N0.getNode(), Zext);
2502       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2503     }
2504   }
2505   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 
2506   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2507   // already be zero by virtue of the width of the base type of the load.
2508   //
2509   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2510   // more cases.
2511   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2512        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2513       N0.getOpcode() == ISD::LOAD) {
2514     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2515                                          N0 : N0.getOperand(0) );
2516
2517     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2518     // This can be a pure constant or a vector splat, in which case we treat the
2519     // vector as a scalar and use the splat value.
2520     APInt Constant = APInt::getNullValue(1);
2521     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2522       Constant = C->getAPIntValue();
2523     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2524       APInt SplatValue, SplatUndef;
2525       unsigned SplatBitSize;
2526       bool HasAnyUndefs;
2527       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2528                                              SplatBitSize, HasAnyUndefs);
2529       if (IsSplat) {
2530         // Undef bits can contribute to a possible optimisation if set, so
2531         // set them.
2532         SplatValue |= SplatUndef;
2533
2534         // The splat value may be something like "0x00FFFFFF", which means 0 for
2535         // the first vector value and FF for the rest, repeating. We need a mask
2536         // that will apply equally to all members of the vector, so AND all the
2537         // lanes of the constant together.
2538         EVT VT = Vector->getValueType(0);
2539         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2540
2541         // If the splat value has been compressed to a bitlength lower
2542         // than the size of the vector lane, we need to re-expand it to
2543         // the lane size.
2544         if (BitWidth > SplatBitSize)
2545           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2546                SplatBitSize < BitWidth;
2547                SplatBitSize = SplatBitSize * 2)
2548             SplatValue |= SplatValue.shl(SplatBitSize);
2549
2550         Constant = APInt::getAllOnesValue(BitWidth);
2551         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2552           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2553       }
2554     }
2555
2556     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2557     // actually legal and isn't going to get expanded, else this is a false
2558     // optimisation.
2559     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2560                                                     Load->getMemoryVT());
2561
2562     // Resize the constant to the same size as the original memory access before
2563     // extension. If it is still the AllOnesValue then this AND is completely
2564     // unneeded.
2565     Constant =
2566       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2567
2568     bool B;
2569     switch (Load->getExtensionType()) {
2570     default: B = false; break;
2571     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2572     case ISD::ZEXTLOAD:
2573     case ISD::NON_EXTLOAD: B = true; break;
2574     }
2575
2576     if (B && Constant.isAllOnesValue()) {
2577       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2578       // preserve semantics once we get rid of the AND.
2579       SDValue NewLoad(Load, 0);
2580       if (Load->getExtensionType() == ISD::EXTLOAD) {
2581         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2582                               Load->getValueType(0), SDLoc(Load),
2583                               Load->getChain(), Load->getBasePtr(),
2584                               Load->getOffset(), Load->getMemoryVT(),
2585                               Load->getMemOperand());
2586         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2587         if (Load->getNumValues() == 3) {
2588           // PRE/POST_INC loads have 3 values.
2589           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2590                            NewLoad.getValue(2) };
2591           CombineTo(Load, To, 3, true);
2592         } else {
2593           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2594         }
2595       }
2596
2597       // Fold the AND away, taking care not to fold to the old load node if we
2598       // replaced it.
2599       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2600
2601       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2602     }
2603   }
2604   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2605   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2606     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2607     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2608
2609     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2610         LL.getValueType().isInteger()) {
2611       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2612       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2613         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2614                                      LR.getValueType(), LL, RL);
2615         AddToWorkList(ORNode.getNode());
2616         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2617       }
2618       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2619       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2620         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2621                                       LR.getValueType(), LL, RL);
2622         AddToWorkList(ANDNode.getNode());
2623         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2624       }
2625       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2626       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2627         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2628                                      LR.getValueType(), LL, RL);
2629         AddToWorkList(ORNode.getNode());
2630         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2631       }
2632     }
2633     // canonicalize equivalent to ll == rl
2634     if (LL == RR && LR == RL) {
2635       Op1 = ISD::getSetCCSwappedOperands(Op1);
2636       std::swap(RL, RR);
2637     }
2638     if (LL == RL && LR == RR) {
2639       bool isInteger = LL.getValueType().isInteger();
2640       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2641       if (Result != ISD::SETCC_INVALID &&
2642           (!LegalOperations ||
2643            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2644             TLI.isOperationLegal(ISD::SETCC,
2645                             getSetCCResultType(N0.getSimpleValueType())))))
2646         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2647                             LL, LR, Result);
2648     }
2649   }
2650
2651   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2652   if (N0.getOpcode() == N1.getOpcode()) {
2653     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2654     if (Tmp.getNode()) return Tmp;
2655   }
2656
2657   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2658   // fold (and (sra)) -> (and (srl)) when possible.
2659   if (!VT.isVector() &&
2660       SimplifyDemandedBits(SDValue(N, 0)))
2661     return SDValue(N, 0);
2662
2663   // fold (zext_inreg (extload x)) -> (zextload x)
2664   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2665     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2666     EVT MemVT = LN0->getMemoryVT();
2667     // If we zero all the possible extended bits, then we can turn this into
2668     // a zextload if we are running before legalize or the operation is legal.
2669     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2670     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2671                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2672         ((!LegalOperations && !LN0->isVolatile()) ||
2673          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2674       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2675                                        LN0->getChain(), LN0->getBasePtr(),
2676                                        LN0->getPointerInfo(), MemVT,
2677                                        LN0->isVolatile(), LN0->isNonTemporal(),
2678                                        LN0->getAlignment());
2679       AddToWorkList(N);
2680       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2681       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2682     }
2683   }
2684   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2685   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2686       N0.hasOneUse()) {
2687     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2688     EVT MemVT = LN0->getMemoryVT();
2689     // If we zero all the possible extended bits, then we can turn this into
2690     // a zextload if we are running before legalize or the operation is legal.
2691     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2692     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2693                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2694         ((!LegalOperations && !LN0->isVolatile()) ||
2695          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2696       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2697                                        LN0->getChain(),
2698                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2699                                        MemVT,
2700                                        LN0->isVolatile(), LN0->isNonTemporal(),
2701                                        LN0->getAlignment());
2702       AddToWorkList(N);
2703       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2704       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2705     }
2706   }
2707
2708   // fold (and (load x), 255) -> (zextload x, i8)
2709   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2710   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2711   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2712               (N0.getOpcode() == ISD::ANY_EXTEND &&
2713                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2714     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2715     LoadSDNode *LN0 = HasAnyExt
2716       ? cast<LoadSDNode>(N0.getOperand(0))
2717       : cast<LoadSDNode>(N0);
2718     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2719         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2720       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2721       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2722         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2723         EVT LoadedVT = LN0->getMemoryVT();
2724
2725         if (ExtVT == LoadedVT &&
2726             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2727           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2728
2729           SDValue NewLoad =
2730             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2731                            LN0->getChain(), LN0->getBasePtr(),
2732                            LN0->getPointerInfo(),
2733                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2734                            LN0->getAlignment());
2735           AddToWorkList(N);
2736           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2737           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2738         }
2739
2740         // Do not change the width of a volatile load.
2741         // Do not generate loads of non-round integer types since these can
2742         // be expensive (and would be wrong if the type is not byte sized).
2743         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2744             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2745           EVT PtrType = LN0->getOperand(1).getValueType();
2746
2747           unsigned Alignment = LN0->getAlignment();
2748           SDValue NewPtr = LN0->getBasePtr();
2749
2750           // For big endian targets, we need to add an offset to the pointer
2751           // to load the correct bytes.  For little endian systems, we merely
2752           // need to read fewer bytes from the same pointer.
2753           if (TLI.isBigEndian()) {
2754             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2755             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2756             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2757             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2758                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2759             Alignment = MinAlign(Alignment, PtrOff);
2760           }
2761
2762           AddToWorkList(NewPtr.getNode());
2763
2764           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2765           SDValue Load =
2766             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2767                            LN0->getChain(), NewPtr,
2768                            LN0->getPointerInfo(),
2769                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2770                            Alignment);
2771           AddToWorkList(N);
2772           CombineTo(LN0, Load, Load.getValue(1));
2773           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2774         }
2775       }
2776     }
2777   }
2778
2779   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2780       VT.getSizeInBits() <= 64) {
2781     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2782       APInt ADDC = ADDI->getAPIntValue();
2783       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2784         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2785         // immediate for an add, but it is legal if its top c2 bits are set,
2786         // transform the ADD so the immediate doesn't need to be materialized
2787         // in a register.
2788         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2789           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2790                                              SRLI->getZExtValue());
2791           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2792             ADDC |= Mask;
2793             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2794               SDValue NewAdd =
2795                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2796                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2797               CombineTo(N0.getNode(), NewAdd);
2798               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2799             }
2800           }
2801         }
2802       }
2803     }
2804   }
2805
2806   return SDValue();
2807 }
2808
2809 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2810 ///
2811 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2812                                         bool DemandHighBits) {
2813   if (!LegalOperations)
2814     return SDValue();
2815
2816   EVT VT = N->getValueType(0);
2817   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2818     return SDValue();
2819   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2820     return SDValue();
2821
2822   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2823   bool LookPassAnd0 = false;
2824   bool LookPassAnd1 = false;
2825   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2826       std::swap(N0, N1);
2827   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2828       std::swap(N0, N1);
2829   if (N0.getOpcode() == ISD::AND) {
2830     if (!N0.getNode()->hasOneUse())
2831       return SDValue();
2832     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2833     if (!N01C || N01C->getZExtValue() != 0xFF00)
2834       return SDValue();
2835     N0 = N0.getOperand(0);
2836     LookPassAnd0 = true;
2837   }
2838
2839   if (N1.getOpcode() == ISD::AND) {
2840     if (!N1.getNode()->hasOneUse())
2841       return SDValue();
2842     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2843     if (!N11C || N11C->getZExtValue() != 0xFF)
2844       return SDValue();
2845     N1 = N1.getOperand(0);
2846     LookPassAnd1 = true;
2847   }
2848
2849   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2850     std::swap(N0, N1);
2851   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2852     return SDValue();
2853   if (!N0.getNode()->hasOneUse() ||
2854       !N1.getNode()->hasOneUse())
2855     return SDValue();
2856
2857   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2858   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2859   if (!N01C || !N11C)
2860     return SDValue();
2861   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2862     return SDValue();
2863
2864   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2865   SDValue N00 = N0->getOperand(0);
2866   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2867     if (!N00.getNode()->hasOneUse())
2868       return SDValue();
2869     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2870     if (!N001C || N001C->getZExtValue() != 0xFF)
2871       return SDValue();
2872     N00 = N00.getOperand(0);
2873     LookPassAnd0 = true;
2874   }
2875
2876   SDValue N10 = N1->getOperand(0);
2877   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2878     if (!N10.getNode()->hasOneUse())
2879       return SDValue();
2880     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2881     if (!N101C || N101C->getZExtValue() != 0xFF00)
2882       return SDValue();
2883     N10 = N10.getOperand(0);
2884     LookPassAnd1 = true;
2885   }
2886
2887   if (N00 != N10)
2888     return SDValue();
2889
2890   // Make sure everything beyond the low halfword is zero since the SRL 16
2891   // will clear the top bits.
2892   unsigned OpSizeInBits = VT.getSizeInBits();
2893   if (DemandHighBits && OpSizeInBits > 16 &&
2894       (!LookPassAnd0 || !LookPassAnd1) &&
2895       !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2896     return SDValue();
2897
2898   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2899   if (OpSizeInBits > 16)
2900     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2901                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2902   return Res;
2903 }
2904
2905 /// isBSwapHWordElement - Return true if the specified node is an element
2906 /// that makes up a 32-bit packed halfword byteswap. i.e.
2907 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2908 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2909   if (!N.getNode()->hasOneUse())
2910     return false;
2911
2912   unsigned Opc = N.getOpcode();
2913   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2914     return false;
2915
2916   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2917   if (!N1C)
2918     return false;
2919
2920   unsigned Num;
2921   switch (N1C->getZExtValue()) {
2922   default:
2923     return false;
2924   case 0xFF:       Num = 0; break;
2925   case 0xFF00:     Num = 1; break;
2926   case 0xFF0000:   Num = 2; break;
2927   case 0xFF000000: Num = 3; break;
2928   }
2929
2930   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2931   SDValue N0 = N.getOperand(0);
2932   if (Opc == ISD::AND) {
2933     if (Num == 0 || Num == 2) {
2934       // (x >> 8) & 0xff
2935       // (x >> 8) & 0xff0000
2936       if (N0.getOpcode() != ISD::SRL)
2937         return false;
2938       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2939       if (!C || C->getZExtValue() != 8)
2940         return false;
2941     } else {
2942       // (x << 8) & 0xff00
2943       // (x << 8) & 0xff000000
2944       if (N0.getOpcode() != ISD::SHL)
2945         return false;
2946       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2947       if (!C || C->getZExtValue() != 8)
2948         return false;
2949     }
2950   } else if (Opc == ISD::SHL) {
2951     // (x & 0xff) << 8
2952     // (x & 0xff0000) << 8
2953     if (Num != 0 && Num != 2)
2954       return false;
2955     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2956     if (!C || C->getZExtValue() != 8)
2957       return false;
2958   } else { // Opc == ISD::SRL
2959     // (x & 0xff00) >> 8
2960     // (x & 0xff000000) >> 8
2961     if (Num != 1 && Num != 3)
2962       return false;
2963     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2964     if (!C || C->getZExtValue() != 8)
2965       return false;
2966   }
2967
2968   if (Parts[Num])
2969     return false;
2970
2971   Parts[Num] = N0.getOperand(0).getNode();
2972   return true;
2973 }
2974
2975 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2976 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2977 /// => (rotl (bswap x), 16)
2978 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2979   if (!LegalOperations)
2980     return SDValue();
2981
2982   EVT VT = N->getValueType(0);
2983   if (VT != MVT::i32)
2984     return SDValue();
2985   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2986     return SDValue();
2987
2988   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2989   // Look for either
2990   // (or (or (and), (and)), (or (and), (and)))
2991   // (or (or (or (and), (and)), (and)), (and))
2992   if (N0.getOpcode() != ISD::OR)
2993     return SDValue();
2994   SDValue N00 = N0.getOperand(0);
2995   SDValue N01 = N0.getOperand(1);
2996
2997   if (N1.getOpcode() == ISD::OR &&
2998       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
2999     // (or (or (and), (and)), (or (and), (and)))
3000     SDValue N000 = N00.getOperand(0);
3001     if (!isBSwapHWordElement(N000, Parts))
3002       return SDValue();
3003
3004     SDValue N001 = N00.getOperand(1);
3005     if (!isBSwapHWordElement(N001, Parts))
3006       return SDValue();
3007     SDValue N010 = N01.getOperand(0);
3008     if (!isBSwapHWordElement(N010, Parts))
3009       return SDValue();
3010     SDValue N011 = N01.getOperand(1);
3011     if (!isBSwapHWordElement(N011, Parts))
3012       return SDValue();
3013   } else {
3014     // (or (or (or (and), (and)), (and)), (and))
3015     if (!isBSwapHWordElement(N1, Parts))
3016       return SDValue();
3017     if (!isBSwapHWordElement(N01, Parts))
3018       return SDValue();
3019     if (N00.getOpcode() != ISD::OR)
3020       return SDValue();
3021     SDValue N000 = N00.getOperand(0);
3022     if (!isBSwapHWordElement(N000, Parts))
3023       return SDValue();
3024     SDValue N001 = N00.getOperand(1);
3025     if (!isBSwapHWordElement(N001, Parts))
3026       return SDValue();
3027   }
3028
3029   // Make sure the parts are all coming from the same node.
3030   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3031     return SDValue();
3032
3033   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3034                               SDValue(Parts[0],0));
3035
3036   // Result of the bswap should be rotated by 16. If it's not legal, than
3037   // do  (x << 16) | (x >> 16).
3038   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3039   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3040     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3041   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3042     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3043   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3044                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3045                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3046 }
3047
3048 SDValue DAGCombiner::visitOR(SDNode *N) {
3049   SDValue N0 = N->getOperand(0);
3050   SDValue N1 = N->getOperand(1);
3051   SDValue LL, LR, RL, RR, CC0, CC1;
3052   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3053   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3054   EVT VT = N1.getValueType();
3055
3056   // fold vector ops
3057   if (VT.isVector()) {
3058     SDValue FoldedVOp = SimplifyVBinOp(N);
3059     if (FoldedVOp.getNode()) return FoldedVOp;
3060
3061     // fold (or x, 0) -> x, vector edition
3062     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3063       return N1;
3064     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3065       return N0;
3066
3067     // fold (or x, -1) -> -1, vector edition
3068     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3069       return N0;
3070     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3071       return N1;
3072   }
3073
3074   // fold (or x, undef) -> -1
3075   if (!LegalOperations &&
3076       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3077     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3078     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3079   }
3080   // fold (or c1, c2) -> c1|c2
3081   if (N0C && N1C)
3082     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3083   // canonicalize constant to RHS
3084   if (N0C && !N1C)
3085     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3086   // fold (or x, 0) -> x
3087   if (N1C && N1C->isNullValue())
3088     return N0;
3089   // fold (or x, -1) -> -1
3090   if (N1C && N1C->isAllOnesValue())
3091     return N1;
3092   // fold (or x, c) -> c iff (x & ~c) == 0
3093   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3094     return N1;
3095
3096   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3097   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3098   if (BSwap.getNode() != 0)
3099     return BSwap;
3100   BSwap = MatchBSwapHWordLow(N, N0, N1);
3101   if (BSwap.getNode() != 0)
3102     return BSwap;
3103
3104   // reassociate or
3105   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3106   if (ROR.getNode() != 0)
3107     return ROR;
3108   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3109   // iff (c1 & c2) == 0.
3110   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3111              isa<ConstantSDNode>(N0.getOperand(1))) {
3112     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3113     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3114       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3115                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3116                                      N0.getOperand(0), N1),
3117                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3118   }
3119   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3120   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3121     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3122     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3123
3124     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3125         LL.getValueType().isInteger()) {
3126       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3127       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3128       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3129           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3130         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3131                                      LR.getValueType(), LL, RL);
3132         AddToWorkList(ORNode.getNode());
3133         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3134       }
3135       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3136       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3137       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3138           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3139         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3140                                       LR.getValueType(), LL, RL);
3141         AddToWorkList(ANDNode.getNode());
3142         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3143       }
3144     }
3145     // canonicalize equivalent to ll == rl
3146     if (LL == RR && LR == RL) {
3147       Op1 = ISD::getSetCCSwappedOperands(Op1);
3148       std::swap(RL, RR);
3149     }
3150     if (LL == RL && LR == RR) {
3151       bool isInteger = LL.getValueType().isInteger();
3152       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3153       if (Result != ISD::SETCC_INVALID &&
3154           (!LegalOperations ||
3155            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3156             TLI.isOperationLegal(ISD::SETCC,
3157               getSetCCResultType(N0.getValueType())))))
3158         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3159                             LL, LR, Result);
3160     }
3161   }
3162
3163   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3164   if (N0.getOpcode() == N1.getOpcode()) {
3165     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3166     if (Tmp.getNode()) return Tmp;
3167   }
3168
3169   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3170   if (N0.getOpcode() == ISD::AND &&
3171       N1.getOpcode() == ISD::AND &&
3172       N0.getOperand(1).getOpcode() == ISD::Constant &&
3173       N1.getOperand(1).getOpcode() == ISD::Constant &&
3174       // Don't increase # computations.
3175       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3176     // We can only do this xform if we know that bits from X that are set in C2
3177     // but not in C1 are already zero.  Likewise for Y.
3178     const APInt &LHSMask =
3179       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3180     const APInt &RHSMask =
3181       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3182
3183     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3184         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3185       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3186                               N0.getOperand(0), N1.getOperand(0));
3187       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3188                          DAG.getConstant(LHSMask | RHSMask, VT));
3189     }
3190   }
3191
3192   // See if this is some rotate idiom.
3193   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3194     return SDValue(Rot, 0);
3195
3196   // Simplify the operands using demanded-bits information.
3197   if (!VT.isVector() &&
3198       SimplifyDemandedBits(SDValue(N, 0)))
3199     return SDValue(N, 0);
3200
3201   return SDValue();
3202 }
3203
3204 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3205 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3206   if (Op.getOpcode() == ISD::AND) {
3207     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3208       Mask = Op.getOperand(1);
3209       Op = Op.getOperand(0);
3210     } else {
3211       return false;
3212     }
3213   }
3214
3215   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3216     Shift = Op;
3217     return true;
3218   }
3219
3220   return false;
3221 }
3222
3223 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3224 // idioms for rotate, and if the target supports rotation instructions, generate
3225 // a rot[lr].
3226 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3227   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3228   EVT VT = LHS.getValueType();
3229   if (!TLI.isTypeLegal(VT)) return 0;
3230
3231   // The target must have at least one rotate flavor.
3232   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3233   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3234   if (!HasROTL && !HasROTR) return 0;
3235
3236   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3237   SDValue LHSShift;   // The shift.
3238   SDValue LHSMask;    // AND value if any.
3239   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3240     return 0; // Not part of a rotate.
3241
3242   SDValue RHSShift;   // The shift.
3243   SDValue RHSMask;    // AND value if any.
3244   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3245     return 0; // Not part of a rotate.
3246
3247   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3248     return 0;   // Not shifting the same value.
3249
3250   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3251     return 0;   // Shifts must disagree.
3252
3253   // Canonicalize shl to left side in a shl/srl pair.
3254   if (RHSShift.getOpcode() == ISD::SHL) {
3255     std::swap(LHS, RHS);
3256     std::swap(LHSShift, RHSShift);
3257     std::swap(LHSMask , RHSMask );
3258   }
3259
3260   unsigned OpSizeInBits = VT.getSizeInBits();
3261   SDValue LHSShiftArg = LHSShift.getOperand(0);
3262   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3263   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3264
3265   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3266   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3267   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3268       RHSShiftAmt.getOpcode() == ISD::Constant) {
3269     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3270     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3271     if ((LShVal + RShVal) != OpSizeInBits)
3272       return 0;
3273
3274     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3275                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3276
3277     // If there is an AND of either shifted operand, apply it to the result.
3278     if (LHSMask.getNode() || RHSMask.getNode()) {
3279       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3280
3281       if (LHSMask.getNode()) {
3282         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3283         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3284       }
3285       if (RHSMask.getNode()) {
3286         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3287         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3288       }
3289
3290       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3291     }
3292
3293     return Rot.getNode();
3294   }
3295
3296   // If there is a mask here, and we have a variable shift, we can't be sure
3297   // that we're masking out the right stuff.
3298   if (LHSMask.getNode() || RHSMask.getNode())
3299     return 0;
3300
3301   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3302   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3303   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3304       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3305     if (ConstantSDNode *SUBC =
3306           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3307       if (SUBC->getAPIntValue() == OpSizeInBits) {
3308         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3309                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3310       }
3311     }
3312   }
3313
3314   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3315   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3316   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3317       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3318     if (ConstantSDNode *SUBC =
3319           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3320       if (SUBC->getAPIntValue() == OpSizeInBits) {
3321         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3322                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3323       }
3324     }
3325   }
3326
3327   // Look for sign/zext/any-extended or truncate cases:
3328   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3329        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3330        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3331        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3332       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3333        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3334        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3335        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3336     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3337     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3338     if (RExtOp0.getOpcode() == ISD::SUB &&
3339         RExtOp0.getOperand(1) == LExtOp0) {
3340       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3341       //   (rotl x, y)
3342       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3343       //   (rotr x, (sub 32, y))
3344       if (ConstantSDNode *SUBC =
3345             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3346         if (SUBC->getAPIntValue() == OpSizeInBits) {
3347           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3348                              LHSShiftArg,
3349                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3350         }
3351       }
3352     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3353                RExtOp0 == LExtOp0.getOperand(1)) {
3354       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3355       //   (rotr x, y)
3356       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3357       //   (rotl x, (sub 32, y))
3358       if (ConstantSDNode *SUBC =
3359             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3360         if (SUBC->getAPIntValue() == OpSizeInBits) {
3361           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3362                              LHSShiftArg,
3363                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3364         }
3365       }
3366     }
3367   }
3368
3369   return 0;
3370 }
3371
3372 SDValue DAGCombiner::visitXOR(SDNode *N) {
3373   SDValue N0 = N->getOperand(0);
3374   SDValue N1 = N->getOperand(1);
3375   SDValue LHS, RHS, CC;
3376   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3377   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3378   EVT VT = N0.getValueType();
3379
3380   // fold vector ops
3381   if (VT.isVector()) {
3382     SDValue FoldedVOp = SimplifyVBinOp(N);
3383     if (FoldedVOp.getNode()) return FoldedVOp;
3384
3385     // fold (xor x, 0) -> x, vector edition
3386     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3387       return N1;
3388     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3389       return N0;
3390   }
3391
3392   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3393   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3394     return DAG.getConstant(0, VT);
3395   // fold (xor x, undef) -> undef
3396   if (N0.getOpcode() == ISD::UNDEF)
3397     return N0;
3398   if (N1.getOpcode() == ISD::UNDEF)
3399     return N1;
3400   // fold (xor c1, c2) -> c1^c2
3401   if (N0C && N1C)
3402     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3403   // canonicalize constant to RHS
3404   if (N0C && !N1C)
3405     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3406   // fold (xor x, 0) -> x
3407   if (N1C && N1C->isNullValue())
3408     return N0;
3409   // reassociate xor
3410   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3411   if (RXOR.getNode() != 0)
3412     return RXOR;
3413
3414   // fold !(x cc y) -> (x !cc y)
3415   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3416     bool isInt = LHS.getValueType().isInteger();
3417     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3418                                                isInt);
3419
3420     if (!LegalOperations ||
3421         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3422       switch (N0.getOpcode()) {
3423       default:
3424         llvm_unreachable("Unhandled SetCC Equivalent!");
3425       case ISD::SETCC:
3426         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3427       case ISD::SELECT_CC:
3428         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3429                                N0.getOperand(3), NotCC);
3430       }
3431     }
3432   }
3433
3434   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3435   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3436       N0.getNode()->hasOneUse() &&
3437       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3438     SDValue V = N0.getOperand(0);
3439     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3440                     DAG.getConstant(1, V.getValueType()));
3441     AddToWorkList(V.getNode());
3442     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3443   }
3444
3445   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3446   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3447       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3448     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3449     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3450       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3451       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3452       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3453       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3454       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3455     }
3456   }
3457   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3458   if (N1C && N1C->isAllOnesValue() &&
3459       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3460     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3461     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3462       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3463       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3464       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3465       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3466       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3467     }
3468   }
3469   // fold (xor (and x, y), y) -> (and (not x), y)
3470   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3471       N0->getOperand(1) == N1) {
3472     SDValue X = N0->getOperand(0);
3473     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3474     AddToWorkList(NotX.getNode());
3475     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3476   }
3477   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3478   if (N1C && N0.getOpcode() == ISD::XOR) {
3479     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3480     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3481     if (N00C)
3482       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3483                          DAG.getConstant(N1C->getAPIntValue() ^
3484                                          N00C->getAPIntValue(), VT));
3485     if (N01C)
3486       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3487                          DAG.getConstant(N1C->getAPIntValue() ^
3488                                          N01C->getAPIntValue(), VT));
3489   }
3490   // fold (xor x, x) -> 0
3491   if (N0 == N1)
3492     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations);
3493
3494   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3495   if (N0.getOpcode() == N1.getOpcode()) {
3496     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3497     if (Tmp.getNode()) return Tmp;
3498   }
3499
3500   // Simplify the expression using non-local knowledge.
3501   if (!VT.isVector() &&
3502       SimplifyDemandedBits(SDValue(N, 0)))
3503     return SDValue(N, 0);
3504
3505   return SDValue();
3506 }
3507
3508 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3509 /// the shift amount is a constant.
3510 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3511   SDNode *LHS = N->getOperand(0).getNode();
3512   if (!LHS->hasOneUse()) return SDValue();
3513
3514   // We want to pull some binops through shifts, so that we have (and (shift))
3515   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3516   // thing happens with address calculations, so it's important to canonicalize
3517   // it.
3518   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3519
3520   switch (LHS->getOpcode()) {
3521   default: return SDValue();
3522   case ISD::OR:
3523   case ISD::XOR:
3524     HighBitSet = false; // We can only transform sra if the high bit is clear.
3525     break;
3526   case ISD::AND:
3527     HighBitSet = true;  // We can only transform sra if the high bit is set.
3528     break;
3529   case ISD::ADD:
3530     if (N->getOpcode() != ISD::SHL)
3531       return SDValue(); // only shl(add) not sr[al](add).
3532     HighBitSet = false; // We can only transform sra if the high bit is clear.
3533     break;
3534   }
3535
3536   // We require the RHS of the binop to be a constant as well.
3537   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3538   if (!BinOpCst) return SDValue();
3539
3540   // FIXME: disable this unless the input to the binop is a shift by a constant.
3541   // If it is not a shift, it pessimizes some common cases like:
3542   //
3543   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3544   //    int bar(int *X, int i) { return X[i & 255]; }
3545   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3546   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3547        BinOpLHSVal->getOpcode() != ISD::SRA &&
3548        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3549       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3550     return SDValue();
3551
3552   EVT VT = N->getValueType(0);
3553
3554   // If this is a signed shift right, and the high bit is modified by the
3555   // logical operation, do not perform the transformation. The highBitSet
3556   // boolean indicates the value of the high bit of the constant which would
3557   // cause it to be modified for this operation.
3558   if (N->getOpcode() == ISD::SRA) {
3559     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3560     if (BinOpRHSSignSet != HighBitSet)
3561       return SDValue();
3562   }
3563
3564   // Fold the constants, shifting the binop RHS by the shift amount.
3565   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3566                                N->getValueType(0),
3567                                LHS->getOperand(1), N->getOperand(1));
3568
3569   // Create the new shift.
3570   SDValue NewShift = DAG.getNode(N->getOpcode(),
3571                                  SDLoc(LHS->getOperand(0)),
3572                                  VT, LHS->getOperand(0), N->getOperand(1));
3573
3574   // Create the new binop.
3575   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3576 }
3577
3578 SDValue DAGCombiner::visitSHL(SDNode *N) {
3579   SDValue N0 = N->getOperand(0);
3580   SDValue N1 = N->getOperand(1);
3581   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3582   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3583   EVT VT = N0.getValueType();
3584   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3585
3586   // fold (shl c1, c2) -> c1<<c2
3587   if (N0C && N1C)
3588     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3589   // fold (shl 0, x) -> 0
3590   if (N0C && N0C->isNullValue())
3591     return N0;
3592   // fold (shl x, c >= size(x)) -> undef
3593   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3594     return DAG.getUNDEF(VT);
3595   // fold (shl x, 0) -> x
3596   if (N1C && N1C->isNullValue())
3597     return N0;
3598   // fold (shl undef, x) -> 0
3599   if (N0.getOpcode() == ISD::UNDEF)
3600     return DAG.getConstant(0, VT);
3601   // if (shl x, c) is known to be zero, return 0
3602   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3603                             APInt::getAllOnesValue(OpSizeInBits)))
3604     return DAG.getConstant(0, VT);
3605   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3606   if (N1.getOpcode() == ISD::TRUNCATE &&
3607       N1.getOperand(0).getOpcode() == ISD::AND &&
3608       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3609     SDValue N101 = N1.getOperand(0).getOperand(1);
3610     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3611       EVT TruncVT = N1.getValueType();
3612       SDValue N100 = N1.getOperand(0).getOperand(0);
3613       APInt TruncC = N101C->getAPIntValue();
3614       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3615       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3616                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3617                                      DAG.getNode(ISD::TRUNCATE,
3618                                                  SDLoc(N),
3619                                                  TruncVT, N100),
3620                                      DAG.getConstant(TruncC, TruncVT)));
3621     }
3622   }
3623
3624   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3625     return SDValue(N, 0);
3626
3627   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3628   if (N1C && N0.getOpcode() == ISD::SHL &&
3629       N0.getOperand(1).getOpcode() == ISD::Constant) {
3630     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3631     uint64_t c2 = N1C->getZExtValue();
3632     if (c1 + c2 >= OpSizeInBits)
3633       return DAG.getConstant(0, VT);
3634     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3635                        DAG.getConstant(c1 + c2, N1.getValueType()));
3636   }
3637
3638   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3639   // For this to be valid, the second form must not preserve any of the bits
3640   // that are shifted out by the inner shift in the first form.  This means
3641   // the outer shift size must be >= the number of bits added by the ext.
3642   // As a corollary, we don't care what kind of ext it is.
3643   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3644               N0.getOpcode() == ISD::ANY_EXTEND ||
3645               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3646       N0.getOperand(0).getOpcode() == ISD::SHL &&
3647       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3648     uint64_t c1 =
3649       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3650     uint64_t c2 = N1C->getZExtValue();
3651     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3652     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3653     if (c2 >= OpSizeInBits - InnerShiftSize) {
3654       if (c1 + c2 >= OpSizeInBits)
3655         return DAG.getConstant(0, VT);
3656       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3657                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3658                                      N0.getOperand(0)->getOperand(0)),
3659                          DAG.getConstant(c1 + c2, N1.getValueType()));
3660     }
3661   }
3662
3663   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3664   //                               (and (srl x, (sub c1, c2), MASK)
3665   // Only fold this if the inner shift has no other uses -- if it does, folding
3666   // this will increase the total number of instructions.
3667   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3668       N0.getOperand(1).getOpcode() == ISD::Constant) {
3669     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3670     if (c1 < VT.getSizeInBits()) {
3671       uint64_t c2 = N1C->getZExtValue();
3672       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3673                                          VT.getSizeInBits() - c1);
3674       SDValue Shift;
3675       if (c2 > c1) {
3676         Mask = Mask.shl(c2-c1);
3677         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3678                             DAG.getConstant(c2-c1, N1.getValueType()));
3679       } else {
3680         Mask = Mask.lshr(c1-c2);
3681         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3682                             DAG.getConstant(c1-c2, N1.getValueType()));
3683       }
3684       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3685                          DAG.getConstant(Mask, VT));
3686     }
3687   }
3688   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3689   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3690     SDValue HiBitsMask =
3691       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3692                                             VT.getSizeInBits() -
3693                                               N1C->getZExtValue()),
3694                       VT);
3695     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3696                        HiBitsMask);
3697   }
3698
3699   if (N1C) {
3700     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3701     if (NewSHL.getNode())
3702       return NewSHL;
3703   }
3704
3705   return SDValue();
3706 }
3707
3708 SDValue DAGCombiner::visitSRA(SDNode *N) {
3709   SDValue N0 = N->getOperand(0);
3710   SDValue N1 = N->getOperand(1);
3711   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3712   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3713   EVT VT = N0.getValueType();
3714   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3715
3716   // fold (sra c1, c2) -> (sra c1, c2)
3717   if (N0C && N1C)
3718     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3719   // fold (sra 0, x) -> 0
3720   if (N0C && N0C->isNullValue())
3721     return N0;
3722   // fold (sra -1, x) -> -1
3723   if (N0C && N0C->isAllOnesValue())
3724     return N0;
3725   // fold (sra x, (setge c, size(x))) -> undef
3726   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3727     return DAG.getUNDEF(VT);
3728   // fold (sra x, 0) -> x
3729   if (N1C && N1C->isNullValue())
3730     return N0;
3731   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3732   // sext_inreg.
3733   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3734     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3735     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3736     if (VT.isVector())
3737       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3738                                ExtVT, VT.getVectorNumElements());
3739     if ((!LegalOperations ||
3740          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3741       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3742                          N0.getOperand(0), DAG.getValueType(ExtVT));
3743   }
3744
3745   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3746   if (N1C && N0.getOpcode() == ISD::SRA) {
3747     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3748       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3749       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3750       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3751                          DAG.getConstant(Sum, N1C->getValueType(0)));
3752     }
3753   }
3754
3755   // fold (sra (shl X, m), (sub result_size, n))
3756   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3757   // result_size - n != m.
3758   // If truncate is free for the target sext(shl) is likely to result in better
3759   // code.
3760   if (N0.getOpcode() == ISD::SHL) {
3761     // Get the two constanst of the shifts, CN0 = m, CN = n.
3762     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3763     if (N01C && N1C) {
3764       // Determine what the truncate's result bitsize and type would be.
3765       EVT TruncVT =
3766         EVT::getIntegerVT(*DAG.getContext(),
3767                           OpSizeInBits - N1C->getZExtValue());
3768       // Determine the residual right-shift amount.
3769       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3770
3771       // If the shift is not a no-op (in which case this should be just a sign
3772       // extend already), the truncated to type is legal, sign_extend is legal
3773       // on that type, and the truncate to that type is both legal and free,
3774       // perform the transform.
3775       if ((ShiftAmt > 0) &&
3776           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3777           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3778           TLI.isTruncateFree(VT, TruncVT)) {
3779
3780           SDValue Amt = DAG.getConstant(ShiftAmt,
3781               getShiftAmountTy(N0.getOperand(0).getValueType()));
3782           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3783                                       N0.getOperand(0), Amt);
3784           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3785                                       Shift);
3786           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3787                              N->getValueType(0), Trunc);
3788       }
3789     }
3790   }
3791
3792   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3793   if (N1.getOpcode() == ISD::TRUNCATE &&
3794       N1.getOperand(0).getOpcode() == ISD::AND &&
3795       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3796     SDValue N101 = N1.getOperand(0).getOperand(1);
3797     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3798       EVT TruncVT = N1.getValueType();
3799       SDValue N100 = N1.getOperand(0).getOperand(0);
3800       APInt TruncC = N101C->getAPIntValue();
3801       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3802       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3803                          DAG.getNode(ISD::AND, SDLoc(N),
3804                                      TruncVT,
3805                                      DAG.getNode(ISD::TRUNCATE,
3806                                                  SDLoc(N),
3807                                                  TruncVT, N100),
3808                                      DAG.getConstant(TruncC, TruncVT)));
3809     }
3810   }
3811
3812   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3813   //      if c1 is equal to the number of bits the trunc removes
3814   if (N0.getOpcode() == ISD::TRUNCATE &&
3815       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3816        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3817       N0.getOperand(0).hasOneUse() &&
3818       N0.getOperand(0).getOperand(1).hasOneUse() &&
3819       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3820     EVT LargeVT = N0.getOperand(0).getValueType();
3821     ConstantSDNode *LargeShiftAmt =
3822       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3823
3824     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3825         LargeShiftAmt->getZExtValue()) {
3826       SDValue Amt =
3827         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3828               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3829       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3830                                 N0.getOperand(0).getOperand(0), Amt);
3831       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3832     }
3833   }
3834
3835   // Simplify, based on bits shifted out of the LHS.
3836   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3837     return SDValue(N, 0);
3838
3839
3840   // If the sign bit is known to be zero, switch this to a SRL.
3841   if (DAG.SignBitIsZero(N0))
3842     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3843
3844   if (N1C) {
3845     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3846     if (NewSRA.getNode())
3847       return NewSRA;
3848   }
3849
3850   return SDValue();
3851 }
3852
3853 SDValue DAGCombiner::visitSRL(SDNode *N) {
3854   SDValue N0 = N->getOperand(0);
3855   SDValue N1 = N->getOperand(1);
3856   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3857   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3858   EVT VT = N0.getValueType();
3859   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3860
3861   // fold (srl c1, c2) -> c1 >>u c2
3862   if (N0C && N1C)
3863     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3864   // fold (srl 0, x) -> 0
3865   if (N0C && N0C->isNullValue())
3866     return N0;
3867   // fold (srl x, c >= size(x)) -> undef
3868   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3869     return DAG.getUNDEF(VT);
3870   // fold (srl x, 0) -> x
3871   if (N1C && N1C->isNullValue())
3872     return N0;
3873   // if (srl x, c) is known to be zero, return 0
3874   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3875                                    APInt::getAllOnesValue(OpSizeInBits)))
3876     return DAG.getConstant(0, VT);
3877
3878   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3879   if (N1C && N0.getOpcode() == ISD::SRL &&
3880       N0.getOperand(1).getOpcode() == ISD::Constant) {
3881     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3882     uint64_t c2 = N1C->getZExtValue();
3883     if (c1 + c2 >= OpSizeInBits)
3884       return DAG.getConstant(0, VT);
3885     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3886                        DAG.getConstant(c1 + c2, N1.getValueType()));
3887   }
3888
3889   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3890   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3891       N0.getOperand(0).getOpcode() == ISD::SRL &&
3892       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3893     uint64_t c1 =
3894       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3895     uint64_t c2 = N1C->getZExtValue();
3896     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3897     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3898     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3899     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3900     if (c1 + OpSizeInBits == InnerShiftSize) {
3901       if (c1 + c2 >= InnerShiftSize)
3902         return DAG.getConstant(0, VT);
3903       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3904                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3905                                      N0.getOperand(0)->getOperand(0),
3906                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3907     }
3908   }
3909
3910   // fold (srl (shl x, c), c) -> (and x, cst2)
3911   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3912       N0.getValueSizeInBits() <= 64) {
3913     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3914     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3915                        DAG.getConstant(~0ULL >> ShAmt, VT));
3916   }
3917
3918   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
3919   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3920     // Shifting in all undef bits?
3921     EVT SmallVT = N0.getOperand(0).getValueType();
3922     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3923       return DAG.getUNDEF(VT);
3924
3925     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3926       uint64_t ShiftAmt = N1C->getZExtValue();
3927       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
3928                                        N0.getOperand(0),
3929                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3930       AddToWorkList(SmallShift.getNode());
3931       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
3932       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3933                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
3934                          DAG.getConstant(Mask, VT));
3935     }
3936   }
3937
3938   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3939   // bit, which is unmodified by sra.
3940   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3941     if (N0.getOpcode() == ISD::SRA)
3942       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
3943   }
3944
3945   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3946   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3947       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3948     APInt KnownZero, KnownOne;
3949     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3950
3951     // If any of the input bits are KnownOne, then the input couldn't be all
3952     // zeros, thus the result of the srl will always be zero.
3953     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3954
3955     // If all of the bits input the to ctlz node are known to be zero, then
3956     // the result of the ctlz is "32" and the result of the shift is one.
3957     APInt UnknownBits = ~KnownZero;
3958     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3959
3960     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3961     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3962       // Okay, we know that only that the single bit specified by UnknownBits
3963       // could be set on input to the CTLZ node. If this bit is set, the SRL
3964       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3965       // to an SRL/XOR pair, which is likely to simplify more.
3966       unsigned ShAmt = UnknownBits.countTrailingZeros();
3967       SDValue Op = N0.getOperand(0);
3968
3969       if (ShAmt) {
3970         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
3971                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3972         AddToWorkList(Op.getNode());
3973       }
3974
3975       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
3976                          Op, DAG.getConstant(1, VT));
3977     }
3978   }
3979
3980   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3981   if (N1.getOpcode() == ISD::TRUNCATE &&
3982       N1.getOperand(0).getOpcode() == ISD::AND &&
3983       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3984     SDValue N101 = N1.getOperand(0).getOperand(1);
3985     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3986       EVT TruncVT = N1.getValueType();
3987       SDValue N100 = N1.getOperand(0).getOperand(0);
3988       APInt TruncC = N101C->getAPIntValue();
3989       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3990       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
3991                          DAG.getNode(ISD::AND, SDLoc(N),
3992                                      TruncVT,
3993                                      DAG.getNode(ISD::TRUNCATE,
3994                                                  SDLoc(N),
3995                                                  TruncVT, N100),
3996                                      DAG.getConstant(TruncC, TruncVT)));
3997     }
3998   }
3999
4000   // fold operands of srl based on knowledge that the low bits are not
4001   // demanded.
4002   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4003     return SDValue(N, 0);
4004
4005   if (N1C) {
4006     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4007     if (NewSRL.getNode())
4008       return NewSRL;
4009   }
4010
4011   // Attempt to convert a srl of a load into a narrower zero-extending load.
4012   SDValue NarrowLoad = ReduceLoadWidth(N);
4013   if (NarrowLoad.getNode())
4014     return NarrowLoad;
4015
4016   // Here is a common situation. We want to optimize:
4017   //
4018   //   %a = ...
4019   //   %b = and i32 %a, 2
4020   //   %c = srl i32 %b, 1
4021   //   brcond i32 %c ...
4022   //
4023   // into
4024   //
4025   //   %a = ...
4026   //   %b = and %a, 2
4027   //   %c = setcc eq %b, 0
4028   //   brcond %c ...
4029   //
4030   // However when after the source operand of SRL is optimized into AND, the SRL
4031   // itself may not be optimized further. Look for it and add the BRCOND into
4032   // the worklist.
4033   if (N->hasOneUse()) {
4034     SDNode *Use = *N->use_begin();
4035     if (Use->getOpcode() == ISD::BRCOND)
4036       AddToWorkList(Use);
4037     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4038       // Also look pass the truncate.
4039       Use = *Use->use_begin();
4040       if (Use->getOpcode() == ISD::BRCOND)
4041         AddToWorkList(Use);
4042     }
4043   }
4044
4045   return SDValue();
4046 }
4047
4048 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4049   SDValue N0 = N->getOperand(0);
4050   EVT VT = N->getValueType(0);
4051
4052   // fold (ctlz c1) -> c2
4053   if (isa<ConstantSDNode>(N0))
4054     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4055   return SDValue();
4056 }
4057
4058 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4059   SDValue N0 = N->getOperand(0);
4060   EVT VT = N->getValueType(0);
4061
4062   // fold (ctlz_zero_undef c1) -> c2
4063   if (isa<ConstantSDNode>(N0))
4064     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4065   return SDValue();
4066 }
4067
4068 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4069   SDValue N0 = N->getOperand(0);
4070   EVT VT = N->getValueType(0);
4071
4072   // fold (cttz c1) -> c2
4073   if (isa<ConstantSDNode>(N0))
4074     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4075   return SDValue();
4076 }
4077
4078 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4079   SDValue N0 = N->getOperand(0);
4080   EVT VT = N->getValueType(0);
4081
4082   // fold (cttz_zero_undef c1) -> c2
4083   if (isa<ConstantSDNode>(N0))
4084     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4085   return SDValue();
4086 }
4087
4088 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4089   SDValue N0 = N->getOperand(0);
4090   EVT VT = N->getValueType(0);
4091
4092   // fold (ctpop c1) -> c2
4093   if (isa<ConstantSDNode>(N0))
4094     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4095   return SDValue();
4096 }
4097
4098 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4099   SDValue N0 = N->getOperand(0);
4100   SDValue N1 = N->getOperand(1);
4101   SDValue N2 = N->getOperand(2);
4102   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4103   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4104   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4105   EVT VT = N->getValueType(0);
4106   EVT VT0 = N0.getValueType();
4107
4108   // fold (select C, X, X) -> X
4109   if (N1 == N2)
4110     return N1;
4111   // fold (select true, X, Y) -> X
4112   if (N0C && !N0C->isNullValue())
4113     return N1;
4114   // fold (select false, X, Y) -> Y
4115   if (N0C && N0C->isNullValue())
4116     return N2;
4117   // fold (select C, 1, X) -> (or C, X)
4118   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4119     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4120   // fold (select C, 0, 1) -> (xor C, 1)
4121   if (VT.isInteger() &&
4122       (VT0 == MVT::i1 ||
4123        (VT0.isInteger() &&
4124         TLI.getBooleanContents(false) ==
4125         TargetLowering::ZeroOrOneBooleanContent)) &&
4126       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4127     SDValue XORNode;
4128     if (VT == VT0)
4129       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4130                          N0, DAG.getConstant(1, VT0));
4131     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4132                           N0, DAG.getConstant(1, VT0));
4133     AddToWorkList(XORNode.getNode());
4134     if (VT.bitsGT(VT0))
4135       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4136     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4137   }
4138   // fold (select C, 0, X) -> (and (not C), X)
4139   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4140     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4141     AddToWorkList(NOTNode.getNode());
4142     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4143   }
4144   // fold (select C, X, 1) -> (or (not C), X)
4145   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4146     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4147     AddToWorkList(NOTNode.getNode());
4148     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4149   }
4150   // fold (select C, X, 0) -> (and C, X)
4151   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4152     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4153   // fold (select X, X, Y) -> (or X, Y)
4154   // fold (select X, 1, Y) -> (or X, Y)
4155   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4156     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4157   // fold (select X, Y, X) -> (and X, Y)
4158   // fold (select X, Y, 0) -> (and X, Y)
4159   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4160     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4161
4162   // If we can fold this based on the true/false value, do so.
4163   if (SimplifySelectOps(N, N1, N2))
4164     return SDValue(N, 0);  // Don't revisit N.
4165
4166   // fold selects based on a setcc into other things, such as min/max/abs
4167   if (N0.getOpcode() == ISD::SETCC) {
4168     // FIXME:
4169     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4170     // having to say they don't support SELECT_CC on every type the DAG knows
4171     // about, since there is no way to mark an opcode illegal at all value types
4172     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4173         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4174       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4175                          N0.getOperand(0), N0.getOperand(1),
4176                          N1, N2, N0.getOperand(2));
4177     return SimplifySelect(SDLoc(N), N0, N1, N2);
4178   }
4179
4180   return SDValue();
4181 }
4182
4183 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4184   SDValue N0 = N->getOperand(0);
4185   SDValue N1 = N->getOperand(1);
4186   SDValue N2 = N->getOperand(2);
4187   SDLoc DL(N);
4188
4189   // Canonicalize integer abs.
4190   // vselect (setg[te] X,  0),  X, -X ->
4191   // vselect (setgt    X, -1),  X, -X ->
4192   // vselect (setl[te] X,  0), -X,  X ->
4193   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4194   if (N0.getOpcode() == ISD::SETCC) {
4195     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4196     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4197     bool isAbs = false;
4198     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4199
4200     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4201          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4202         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4203       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4204     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4205              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4206       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4207
4208     if (isAbs) {
4209       EVT VT = LHS.getValueType();
4210       SDValue Shift = DAG.getNode(
4211           ISD::SRA, DL, VT, LHS,
4212           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4213       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4214       AddToWorkList(Shift.getNode());
4215       AddToWorkList(Add.getNode());
4216       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4217     }
4218   }
4219
4220   return SDValue();
4221 }
4222
4223 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4224   SDValue N0 = N->getOperand(0);
4225   SDValue N1 = N->getOperand(1);
4226   SDValue N2 = N->getOperand(2);
4227   SDValue N3 = N->getOperand(3);
4228   SDValue N4 = N->getOperand(4);
4229   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4230
4231   // fold select_cc lhs, rhs, x, x, cc -> x
4232   if (N2 == N3)
4233     return N2;
4234
4235   // Determine if the condition we're dealing with is constant
4236   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4237                               N0, N1, CC, SDLoc(N), false);
4238   if (SCC.getNode()) {
4239     AddToWorkList(SCC.getNode());
4240
4241     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4242       if (!SCCC->isNullValue())
4243         return N2;    // cond always true -> true val
4244       else
4245         return N3;    // cond always false -> false val
4246     }
4247
4248     // Fold to a simpler select_cc
4249     if (SCC.getOpcode() == ISD::SETCC)
4250       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4251                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4252                          SCC.getOperand(2));
4253   }
4254
4255   // If we can fold this based on the true/false value, do so.
4256   if (SimplifySelectOps(N, N2, N3))
4257     return SDValue(N, 0);  // Don't revisit N.
4258
4259   // fold select_cc into other things, such as min/max/abs
4260   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4261 }
4262
4263 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4264   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4265                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4266                        SDLoc(N));
4267 }
4268
4269 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4270 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4271 // transformation. Returns true if extension are possible and the above
4272 // mentioned transformation is profitable.
4273 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4274                                     unsigned ExtOpc,
4275                                     SmallVector<SDNode*, 4> &ExtendNodes,
4276                                     const TargetLowering &TLI) {
4277   bool HasCopyToRegUses = false;
4278   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4279   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4280                             UE = N0.getNode()->use_end();
4281        UI != UE; ++UI) {
4282     SDNode *User = *UI;
4283     if (User == N)
4284       continue;
4285     if (UI.getUse().getResNo() != N0.getResNo())
4286       continue;
4287     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4288     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4289       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4290       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4291         // Sign bits will be lost after a zext.
4292         return false;
4293       bool Add = false;
4294       for (unsigned i = 0; i != 2; ++i) {
4295         SDValue UseOp = User->getOperand(i);
4296         if (UseOp == N0)
4297           continue;
4298         if (!isa<ConstantSDNode>(UseOp))
4299           return false;
4300         Add = true;
4301       }
4302       if (Add)
4303         ExtendNodes.push_back(User);
4304       continue;
4305     }
4306     // If truncates aren't free and there are users we can't
4307     // extend, it isn't worthwhile.
4308     if (!isTruncFree)
4309       return false;
4310     // Remember if this value is live-out.
4311     if (User->getOpcode() == ISD::CopyToReg)
4312       HasCopyToRegUses = true;
4313   }
4314
4315   if (HasCopyToRegUses) {
4316     bool BothLiveOut = false;
4317     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4318          UI != UE; ++UI) {
4319       SDUse &Use = UI.getUse();
4320       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4321         BothLiveOut = true;
4322         break;
4323       }
4324     }
4325     if (BothLiveOut)
4326       // Both unextended and extended values are live out. There had better be
4327       // a good reason for the transformation.
4328       return ExtendNodes.size();
4329   }
4330   return true;
4331 }
4332
4333 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4334                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4335                                   ISD::NodeType ExtType) {
4336   // Extend SetCC uses if necessary.
4337   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4338     SDNode *SetCC = SetCCs[i];
4339     SmallVector<SDValue, 4> Ops;
4340
4341     for (unsigned j = 0; j != 2; ++j) {
4342       SDValue SOp = SetCC->getOperand(j);
4343       if (SOp == Trunc)
4344         Ops.push_back(ExtLoad);
4345       else
4346         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4347     }
4348
4349     Ops.push_back(SetCC->getOperand(2));
4350     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4351                                  &Ops[0], Ops.size()));
4352   }
4353 }
4354
4355 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4356   SDValue N0 = N->getOperand(0);
4357   EVT VT = N->getValueType(0);
4358
4359   // fold (sext c1) -> c1
4360   if (isa<ConstantSDNode>(N0))
4361     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4362
4363   // fold (sext (sext x)) -> (sext x)
4364   // fold (sext (aext x)) -> (sext x)
4365   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4366     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4367                        N0.getOperand(0));
4368
4369   if (N0.getOpcode() == ISD::TRUNCATE) {
4370     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4371     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4372     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4373     if (NarrowLoad.getNode()) {
4374       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4375       if (NarrowLoad.getNode() != N0.getNode()) {
4376         CombineTo(N0.getNode(), NarrowLoad);
4377         // CombineTo deleted the truncate, if needed, but not what's under it.
4378         AddToWorkList(oye);
4379       }
4380       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4381     }
4382
4383     // See if the value being truncated is already sign extended.  If so, just
4384     // eliminate the trunc/sext pair.
4385     SDValue Op = N0.getOperand(0);
4386     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4387     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4388     unsigned DestBits = VT.getScalarType().getSizeInBits();
4389     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4390
4391     if (OpBits == DestBits) {
4392       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4393       // bits, it is already ready.
4394       if (NumSignBits > DestBits-MidBits)
4395         return Op;
4396     } else if (OpBits < DestBits) {
4397       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4398       // bits, just sext from i32.
4399       if (NumSignBits > OpBits-MidBits)
4400         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4401     } else {
4402       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4403       // bits, just truncate to i32.
4404       if (NumSignBits > OpBits-MidBits)
4405         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4406     }
4407
4408     // fold (sext (truncate x)) -> (sextinreg x).
4409     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4410                                                  N0.getValueType())) {
4411       if (OpBits < DestBits)
4412         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4413       else if (OpBits > DestBits)
4414         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4415       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4416                          DAG.getValueType(N0.getValueType()));
4417     }
4418   }
4419
4420   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4421   // None of the supported targets knows how to perform load and sign extend
4422   // on vectors in one instruction.  We only perform this transformation on
4423   // scalars.
4424   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4425       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4426        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4427     bool DoXform = true;
4428     SmallVector<SDNode*, 4> SetCCs;
4429     if (!N0.hasOneUse())
4430       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4431     if (DoXform) {
4432       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4433       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4434                                        LN0->getChain(),
4435                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4436                                        N0.getValueType(),
4437                                        LN0->isVolatile(), LN0->isNonTemporal(),
4438                                        LN0->getAlignment());
4439       CombineTo(N, ExtLoad);
4440       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4441                                   N0.getValueType(), ExtLoad);
4442       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4443       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4444                       ISD::SIGN_EXTEND);
4445       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4446     }
4447   }
4448
4449   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4450   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4451   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4452       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4453     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4454     EVT MemVT = LN0->getMemoryVT();
4455     if ((!LegalOperations && !LN0->isVolatile()) ||
4456         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4457       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4458                                        LN0->getChain(),
4459                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4460                                        MemVT,
4461                                        LN0->isVolatile(), LN0->isNonTemporal(),
4462                                        LN0->getAlignment());
4463       CombineTo(N, ExtLoad);
4464       CombineTo(N0.getNode(),
4465                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4466                             N0.getValueType(), ExtLoad),
4467                 ExtLoad.getValue(1));
4468       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4469     }
4470   }
4471
4472   // fold (sext (and/or/xor (load x), cst)) ->
4473   //      (and/or/xor (sextload x), (sext cst))
4474   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4475        N0.getOpcode() == ISD::XOR) &&
4476       isa<LoadSDNode>(N0.getOperand(0)) &&
4477       N0.getOperand(1).getOpcode() == ISD::Constant &&
4478       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4479       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4480     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4481     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4482       bool DoXform = true;
4483       SmallVector<SDNode*, 4> SetCCs;
4484       if (!N0.hasOneUse())
4485         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4486                                           SetCCs, TLI);
4487       if (DoXform) {
4488         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4489                                          LN0->getChain(), LN0->getBasePtr(),
4490                                          LN0->getPointerInfo(),
4491                                          LN0->getMemoryVT(),
4492                                          LN0->isVolatile(),
4493                                          LN0->isNonTemporal(),
4494                                          LN0->getAlignment());
4495         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4496         Mask = Mask.sext(VT.getSizeInBits());
4497         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4498                                   ExtLoad, DAG.getConstant(Mask, VT));
4499         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4500                                     SDLoc(N0.getOperand(0)),
4501                                     N0.getOperand(0).getValueType(), ExtLoad);
4502         CombineTo(N, And);
4503         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4504         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4505                         ISD::SIGN_EXTEND);
4506         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4507       }
4508     }
4509   }
4510
4511   if (N0.getOpcode() == ISD::SETCC) {
4512     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4513     // Only do this before legalize for now.
4514     if (VT.isVector() && !LegalOperations &&
4515         TLI.getBooleanContents(true) == 
4516           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4517       EVT N0VT = N0.getOperand(0).getValueType();
4518       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4519       // of the same size as the compared operands. Only optimize sext(setcc())
4520       // if this is the case.
4521       EVT SVT = getSetCCResultType(N0VT);
4522
4523       // We know that the # elements of the results is the same as the
4524       // # elements of the compare (and the # elements of the compare result
4525       // for that matter).  Check to see that they are the same size.  If so,
4526       // we know that the element size of the sext'd result matches the
4527       // element size of the compare operands.
4528       if (VT.getSizeInBits() == SVT.getSizeInBits())
4529         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4530                              N0.getOperand(1),
4531                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4532
4533       // If the desired elements are smaller or larger than the source
4534       // elements we can use a matching integer vector type and then
4535       // truncate/sign extend
4536       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4537       if (SVT == MatchingVectorType) {
4538         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4539                                N0.getOperand(0), N0.getOperand(1),
4540                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4541         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4542       }
4543     }
4544
4545     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4546     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4547     SDValue NegOne =
4548       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4549     SDValue SCC =
4550       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4551                        NegOne, DAG.getConstant(0, VT),
4552                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4553     if (SCC.getNode()) return SCC;
4554     if (!VT.isVector() &&
4555         (!LegalOperations ||
4556          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4557       return DAG.getSelect(SDLoc(N), VT,
4558                            DAG.getSetCC(SDLoc(N),
4559                                         getSetCCResultType(VT),
4560                                         N0.getOperand(0), N0.getOperand(1),
4561                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4562                            NegOne, DAG.getConstant(0, VT));
4563     }
4564   }
4565
4566   // fold (sext x) -> (zext x) if the sign bit is known zero.
4567   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4568       DAG.SignBitIsZero(N0))
4569     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4570
4571   return SDValue();
4572 }
4573
4574 // isTruncateOf - If N is a truncate of some other value, return true, record
4575 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4576 // This function computes KnownZero to avoid a duplicated call to
4577 // ComputeMaskedBits in the caller.
4578 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4579                          APInt &KnownZero) {
4580   APInt KnownOne;
4581   if (N->getOpcode() == ISD::TRUNCATE) {
4582     Op = N->getOperand(0);
4583     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4584     return true;
4585   }
4586
4587   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4588       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4589     return false;
4590
4591   SDValue Op0 = N->getOperand(0);
4592   SDValue Op1 = N->getOperand(1);
4593   assert(Op0.getValueType() == Op1.getValueType());
4594
4595   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4596   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4597   if (COp0 && COp0->isNullValue())
4598     Op = Op1;
4599   else if (COp1 && COp1->isNullValue())
4600     Op = Op0;
4601   else
4602     return false;
4603
4604   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4605
4606   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4607     return false;
4608
4609   return true;
4610 }
4611
4612 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4613   SDValue N0 = N->getOperand(0);
4614   EVT VT = N->getValueType(0);
4615
4616   // fold (zext c1) -> c1
4617   if (isa<ConstantSDNode>(N0))
4618     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4619   // fold (zext (zext x)) -> (zext x)
4620   // fold (zext (aext x)) -> (zext x)
4621   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4622     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4623                        N0.getOperand(0));
4624
4625   // fold (zext (truncate x)) -> (zext x) or
4626   //      (zext (truncate x)) -> (truncate x)
4627   // This is valid when the truncated bits of x are already zero.
4628   // FIXME: We should extend this to work for vectors too.
4629   SDValue Op;
4630   APInt KnownZero;
4631   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4632     APInt TruncatedBits =
4633       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4634       APInt(Op.getValueSizeInBits(), 0) :
4635       APInt::getBitsSet(Op.getValueSizeInBits(),
4636                         N0.getValueSizeInBits(),
4637                         std::min(Op.getValueSizeInBits(),
4638                                  VT.getSizeInBits()));
4639     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4640       if (VT.bitsGT(Op.getValueType()))
4641         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4642       if (VT.bitsLT(Op.getValueType()))
4643         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4644
4645       return Op;
4646     }
4647   }
4648
4649   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4650   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4651   if (N0.getOpcode() == ISD::TRUNCATE) {
4652     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4653     if (NarrowLoad.getNode()) {
4654       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4655       if (NarrowLoad.getNode() != N0.getNode()) {
4656         CombineTo(N0.getNode(), NarrowLoad);
4657         // CombineTo deleted the truncate, if needed, but not what's under it.
4658         AddToWorkList(oye);
4659       }
4660       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4661     }
4662   }
4663
4664   // fold (zext (truncate x)) -> (and x, mask)
4665   if (N0.getOpcode() == ISD::TRUNCATE &&
4666       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4667
4668     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4669     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4670     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4671     if (NarrowLoad.getNode()) {
4672       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4673       if (NarrowLoad.getNode() != N0.getNode()) {
4674         CombineTo(N0.getNode(), NarrowLoad);
4675         // CombineTo deleted the truncate, if needed, but not what's under it.
4676         AddToWorkList(oye);
4677       }
4678       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4679     }
4680
4681     SDValue Op = N0.getOperand(0);
4682     if (Op.getValueType().bitsLT(VT)) {
4683       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4684       AddToWorkList(Op.getNode());
4685     } else if (Op.getValueType().bitsGT(VT)) {
4686       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4687       AddToWorkList(Op.getNode());
4688     }
4689     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4690                                   N0.getValueType().getScalarType());
4691   }
4692
4693   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4694   // if either of the casts is not free.
4695   if (N0.getOpcode() == ISD::AND &&
4696       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4697       N0.getOperand(1).getOpcode() == ISD::Constant &&
4698       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4699                            N0.getValueType()) ||
4700        !TLI.isZExtFree(N0.getValueType(), VT))) {
4701     SDValue X = N0.getOperand(0).getOperand(0);
4702     if (X.getValueType().bitsLT(VT)) {
4703       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4704     } else if (X.getValueType().bitsGT(VT)) {
4705       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4706     }
4707     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4708     Mask = Mask.zext(VT.getSizeInBits());
4709     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4710                        X, DAG.getConstant(Mask, VT));
4711   }
4712
4713   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4714   // None of the supported targets knows how to perform load and vector_zext
4715   // on vectors in one instruction.  We only perform this transformation on
4716   // scalars.
4717   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4718       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4719        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4720     bool DoXform = true;
4721     SmallVector<SDNode*, 4> SetCCs;
4722     if (!N0.hasOneUse())
4723       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4724     if (DoXform) {
4725       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4726       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4727                                        LN0->getChain(),
4728                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4729                                        N0.getValueType(),
4730                                        LN0->isVolatile(), LN0->isNonTemporal(),
4731                                        LN0->getAlignment());
4732       CombineTo(N, ExtLoad);
4733       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4734                                   N0.getValueType(), ExtLoad);
4735       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4736
4737       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4738                       ISD::ZERO_EXTEND);
4739       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4740     }
4741   }
4742
4743   // fold (zext (and/or/xor (load x), cst)) ->
4744   //      (and/or/xor (zextload x), (zext cst))
4745   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4746        N0.getOpcode() == ISD::XOR) &&
4747       isa<LoadSDNode>(N0.getOperand(0)) &&
4748       N0.getOperand(1).getOpcode() == ISD::Constant &&
4749       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4750       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4751     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4752     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4753       bool DoXform = true;
4754       SmallVector<SDNode*, 4> SetCCs;
4755       if (!N0.hasOneUse())
4756         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4757                                           SetCCs, TLI);
4758       if (DoXform) {
4759         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4760                                          LN0->getChain(), LN0->getBasePtr(),
4761                                          LN0->getPointerInfo(),
4762                                          LN0->getMemoryVT(),
4763                                          LN0->isVolatile(),
4764                                          LN0->isNonTemporal(),
4765                                          LN0->getAlignment());
4766         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4767         Mask = Mask.zext(VT.getSizeInBits());
4768         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4769                                   ExtLoad, DAG.getConstant(Mask, VT));
4770         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4771                                     SDLoc(N0.getOperand(0)),
4772                                     N0.getOperand(0).getValueType(), ExtLoad);
4773         CombineTo(N, And);
4774         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4775         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4776                         ISD::ZERO_EXTEND);
4777         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4778       }
4779     }
4780   }
4781
4782   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4783   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4784   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4785       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4786     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4787     EVT MemVT = LN0->getMemoryVT();
4788     if ((!LegalOperations && !LN0->isVolatile()) ||
4789         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4790       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4791                                        LN0->getChain(),
4792                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4793                                        MemVT,
4794                                        LN0->isVolatile(), LN0->isNonTemporal(),
4795                                        LN0->getAlignment());
4796       CombineTo(N, ExtLoad);
4797       CombineTo(N0.getNode(),
4798                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4799                             ExtLoad),
4800                 ExtLoad.getValue(1));
4801       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4802     }
4803   }
4804
4805   if (N0.getOpcode() == ISD::SETCC) {
4806     if (!LegalOperations && VT.isVector()) {
4807       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4808       // Only do this before legalize for now.
4809       EVT N0VT = N0.getOperand(0).getValueType();
4810       EVT EltVT = VT.getVectorElementType();
4811       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4812                                     DAG.getConstant(1, EltVT));
4813       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4814         // We know that the # elements of the results is the same as the
4815         // # elements of the compare (and the # elements of the compare result
4816         // for that matter).  Check to see that they are the same size.  If so,
4817         // we know that the element size of the sext'd result matches the
4818         // element size of the compare operands.
4819         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4820                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4821                                          N0.getOperand(1),
4822                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4823                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4824                                        &OneOps[0], OneOps.size()));
4825
4826       // If the desired elements are smaller or larger than the source
4827       // elements we can use a matching integer vector type and then
4828       // truncate/sign extend
4829       EVT MatchingElementType =
4830         EVT::getIntegerVT(*DAG.getContext(),
4831                           N0VT.getScalarType().getSizeInBits());
4832       EVT MatchingVectorType =
4833         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4834                          N0VT.getVectorNumElements());
4835       SDValue VsetCC =
4836         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4837                       N0.getOperand(1),
4838                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4839       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4840                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4841                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4842                                      &OneOps[0], OneOps.size()));
4843     }
4844
4845     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4846     SDValue SCC =
4847       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4848                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4849                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4850     if (SCC.getNode()) return SCC;
4851   }
4852
4853   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4854   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4855       isa<ConstantSDNode>(N0.getOperand(1)) &&
4856       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4857       N0.hasOneUse()) {
4858     SDValue ShAmt = N0.getOperand(1);
4859     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4860     if (N0.getOpcode() == ISD::SHL) {
4861       SDValue InnerZExt = N0.getOperand(0);
4862       // If the original shl may be shifting out bits, do not perform this
4863       // transformation.
4864       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4865         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4866       if (ShAmtVal > KnownZeroBits)
4867         return SDValue();
4868     }
4869
4870     SDLoc DL(N);
4871
4872     // Ensure that the shift amount is wide enough for the shifted value.
4873     if (VT.getSizeInBits() >= 256)
4874       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4875
4876     return DAG.getNode(N0.getOpcode(), DL, VT,
4877                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4878                        ShAmt);
4879   }
4880
4881   return SDValue();
4882 }
4883
4884 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4885   SDValue N0 = N->getOperand(0);
4886   EVT VT = N->getValueType(0);
4887
4888   // fold (aext c1) -> c1
4889   if (isa<ConstantSDNode>(N0))
4890     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4891   // fold (aext (aext x)) -> (aext x)
4892   // fold (aext (zext x)) -> (zext x)
4893   // fold (aext (sext x)) -> (sext x)
4894   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4895       N0.getOpcode() == ISD::ZERO_EXTEND ||
4896       N0.getOpcode() == ISD::SIGN_EXTEND)
4897     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
4898
4899   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4900   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4901   if (N0.getOpcode() == ISD::TRUNCATE) {
4902     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4903     if (NarrowLoad.getNode()) {
4904       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4905       if (NarrowLoad.getNode() != N0.getNode()) {
4906         CombineTo(N0.getNode(), NarrowLoad);
4907         // CombineTo deleted the truncate, if needed, but not what's under it.
4908         AddToWorkList(oye);
4909       }
4910       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4911     }
4912   }
4913
4914   // fold (aext (truncate x))
4915   if (N0.getOpcode() == ISD::TRUNCATE) {
4916     SDValue TruncOp = N0.getOperand(0);
4917     if (TruncOp.getValueType() == VT)
4918       return TruncOp; // x iff x size == zext size.
4919     if (TruncOp.getValueType().bitsGT(VT))
4920       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
4921     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
4922   }
4923
4924   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4925   // if the trunc is not free.
4926   if (N0.getOpcode() == ISD::AND &&
4927       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4928       N0.getOperand(1).getOpcode() == ISD::Constant &&
4929       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4930                           N0.getValueType())) {
4931     SDValue X = N0.getOperand(0).getOperand(0);
4932     if (X.getValueType().bitsLT(VT)) {
4933       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
4934     } else if (X.getValueType().bitsGT(VT)) {
4935       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
4936     }
4937     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4938     Mask = Mask.zext(VT.getSizeInBits());
4939     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4940                        X, DAG.getConstant(Mask, VT));
4941   }
4942
4943   // fold (aext (load x)) -> (aext (truncate (extload x)))
4944   // None of the supported targets knows how to perform load and any_ext
4945   // on vectors in one instruction.  We only perform this transformation on
4946   // scalars.
4947   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4948       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4949        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4950     bool DoXform = true;
4951     SmallVector<SDNode*, 4> SetCCs;
4952     if (!N0.hasOneUse())
4953       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4954     if (DoXform) {
4955       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4956       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
4957                                        LN0->getChain(),
4958                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4959                                        N0.getValueType(),
4960                                        LN0->isVolatile(), LN0->isNonTemporal(),
4961                                        LN0->getAlignment());
4962       CombineTo(N, ExtLoad);
4963       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4964                                   N0.getValueType(), ExtLoad);
4965       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4966       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4967                       ISD::ANY_EXTEND);
4968       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4969     }
4970   }
4971
4972   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4973   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4974   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4975   if (N0.getOpcode() == ISD::LOAD &&
4976       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4977       N0.hasOneUse()) {
4978     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4979     EVT MemVT = LN0->getMemoryVT();
4980     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
4981                                      VT, LN0->getChain(), LN0->getBasePtr(),
4982                                      LN0->getPointerInfo(), MemVT,
4983                                      LN0->isVolatile(), LN0->isNonTemporal(),
4984                                      LN0->getAlignment());
4985     CombineTo(N, ExtLoad);
4986     CombineTo(N0.getNode(),
4987               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4988                           N0.getValueType(), ExtLoad),
4989               ExtLoad.getValue(1));
4990     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4991   }
4992
4993   if (N0.getOpcode() == ISD::SETCC) {
4994     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4995     // Only do this before legalize for now.
4996     if (VT.isVector() && !LegalOperations) {
4997       EVT N0VT = N0.getOperand(0).getValueType();
4998         // We know that the # elements of the results is the same as the
4999         // # elements of the compare (and the # elements of the compare result
5000         // for that matter).  Check to see that they are the same size.  If so,
5001         // we know that the element size of the sext'd result matches the
5002         // element size of the compare operands.
5003       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5004         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5005                              N0.getOperand(1),
5006                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5007       // If the desired elements are smaller or larger than the source
5008       // elements we can use a matching integer vector type and then
5009       // truncate/sign extend
5010       else {
5011         EVT MatchingElementType =
5012           EVT::getIntegerVT(*DAG.getContext(),
5013                             N0VT.getScalarType().getSizeInBits());
5014         EVT MatchingVectorType =
5015           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5016                            N0VT.getVectorNumElements());
5017         SDValue VsetCC =
5018           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5019                         N0.getOperand(1),
5020                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5021         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5022       }
5023     }
5024
5025     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5026     SDValue SCC =
5027       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5028                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5029                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5030     if (SCC.getNode())
5031       return SCC;
5032   }
5033
5034   return SDValue();
5035 }
5036
5037 /// GetDemandedBits - See if the specified operand can be simplified with the
5038 /// knowledge that only the bits specified by Mask are used.  If so, return the
5039 /// simpler operand, otherwise return a null SDValue.
5040 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5041   switch (V.getOpcode()) {
5042   default: break;
5043   case ISD::Constant: {
5044     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5045     assert(CV != 0 && "Const value should be ConstSDNode.");
5046     const APInt &CVal = CV->getAPIntValue();
5047     APInt NewVal = CVal & Mask;
5048     if (NewVal != CVal) {
5049       return DAG.getConstant(NewVal, V.getValueType());
5050     }
5051     break;
5052   }
5053   case ISD::OR:
5054   case ISD::XOR:
5055     // If the LHS or RHS don't contribute bits to the or, drop them.
5056     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5057       return V.getOperand(1);
5058     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5059       return V.getOperand(0);
5060     break;
5061   case ISD::SRL:
5062     // Only look at single-use SRLs.
5063     if (!V.getNode()->hasOneUse())
5064       break;
5065     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5066       // See if we can recursively simplify the LHS.
5067       unsigned Amt = RHSC->getZExtValue();
5068
5069       // Watch out for shift count overflow though.
5070       if (Amt >= Mask.getBitWidth()) break;
5071       APInt NewMask = Mask << Amt;
5072       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5073       if (SimplifyLHS.getNode())
5074         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5075                            SimplifyLHS, V.getOperand(1));
5076     }
5077   }
5078   return SDValue();
5079 }
5080
5081 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5082 /// bits and then truncated to a narrower type and where N is a multiple
5083 /// of number of bits of the narrower type, transform it to a narrower load
5084 /// from address + N / num of bits of new type. If the result is to be
5085 /// extended, also fold the extension to form a extending load.
5086 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5087   unsigned Opc = N->getOpcode();
5088
5089   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5090   SDValue N0 = N->getOperand(0);
5091   EVT VT = N->getValueType(0);
5092   EVT ExtVT = VT;
5093
5094   // This transformation isn't valid for vector loads.
5095   if (VT.isVector())
5096     return SDValue();
5097
5098   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5099   // extended to VT.
5100   if (Opc == ISD::SIGN_EXTEND_INREG) {
5101     ExtType = ISD::SEXTLOAD;
5102     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5103   } else if (Opc == ISD::SRL) {
5104     // Another special-case: SRL is basically zero-extending a narrower value.
5105     ExtType = ISD::ZEXTLOAD;
5106     N0 = SDValue(N, 0);
5107     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5108     if (!N01) return SDValue();
5109     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5110                               VT.getSizeInBits() - N01->getZExtValue());
5111   }
5112   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5113     return SDValue();
5114
5115   unsigned EVTBits = ExtVT.getSizeInBits();
5116
5117   // Do not generate loads of non-round integer types since these can
5118   // be expensive (and would be wrong if the type is not byte sized).
5119   if (!ExtVT.isRound())
5120     return SDValue();
5121
5122   unsigned ShAmt = 0;
5123   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5124     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5125       ShAmt = N01->getZExtValue();
5126       // Is the shift amount a multiple of size of VT?
5127       if ((ShAmt & (EVTBits-1)) == 0) {
5128         N0 = N0.getOperand(0);
5129         // Is the load width a multiple of size of VT?
5130         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5131           return SDValue();
5132       }
5133
5134       // At this point, we must have a load or else we can't do the transform.
5135       if (!isa<LoadSDNode>(N0)) return SDValue();
5136
5137       // Because a SRL must be assumed to *need* to zero-extend the high bits
5138       // (as opposed to anyext the high bits), we can't combine the zextload
5139       // lowering of SRL and an sextload.
5140       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5141         return SDValue();
5142
5143       // If the shift amount is larger than the input type then we're not
5144       // accessing any of the loaded bytes.  If the load was a zextload/extload
5145       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5146       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5147         return SDValue();
5148     }
5149   }
5150
5151   // If the load is shifted left (and the result isn't shifted back right),
5152   // we can fold the truncate through the shift.
5153   unsigned ShLeftAmt = 0;
5154   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5155       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5156     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5157       ShLeftAmt = N01->getZExtValue();
5158       N0 = N0.getOperand(0);
5159     }
5160   }
5161
5162   // If we haven't found a load, we can't narrow it.  Don't transform one with
5163   // multiple uses, this would require adding a new load.
5164   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5165     return SDValue();
5166
5167   // Don't change the width of a volatile load.
5168   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5169   if (LN0->isVolatile())
5170     return SDValue();
5171
5172   // Verify that we are actually reducing a load width here.
5173   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5174     return SDValue();
5175
5176   // For the transform to be legal, the load must produce only two values
5177   // (the value loaded and the chain).  Don't transform a pre-increment
5178   // load, for example, which produces an extra value.  Otherwise the 
5179   // transformation is not equivalent, and the downstream logic to replace
5180   // uses gets things wrong.
5181   if (LN0->getNumValues() > 2)
5182     return SDValue();
5183
5184   EVT PtrType = N0.getOperand(1).getValueType();
5185
5186   if (PtrType == MVT::Untyped || PtrType.isExtended())
5187     // It's not possible to generate a constant of extended or untyped type.
5188     return SDValue();
5189
5190   // For big endian targets, we need to adjust the offset to the pointer to
5191   // load the correct bytes.
5192   if (TLI.isBigEndian()) {
5193     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5194     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5195     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5196   }
5197
5198   uint64_t PtrOff = ShAmt / 8;
5199   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5200   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5201                                PtrType, LN0->getBasePtr(),
5202                                DAG.getConstant(PtrOff, PtrType));
5203   AddToWorkList(NewPtr.getNode());
5204
5205   SDValue Load;
5206   if (ExtType == ISD::NON_EXTLOAD)
5207     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5208                         LN0->getPointerInfo().getWithOffset(PtrOff),
5209                         LN0->isVolatile(), LN0->isNonTemporal(),
5210                         LN0->isInvariant(), NewAlign);
5211   else
5212     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5213                           LN0->getPointerInfo().getWithOffset(PtrOff),
5214                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5215                           NewAlign);
5216
5217   // Replace the old load's chain with the new load's chain.
5218   WorkListRemover DeadNodes(*this);
5219   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5220
5221   // Shift the result left, if we've swallowed a left shift.
5222   SDValue Result = Load;
5223   if (ShLeftAmt != 0) {
5224     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5225     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5226       ShImmTy = VT;
5227     // If the shift amount is as large as the result size (but, presumably,
5228     // no larger than the source) then the useful bits of the result are
5229     // zero; we can't simply return the shortened shift, because the result
5230     // of that operation is undefined.
5231     if (ShLeftAmt >= VT.getSizeInBits())
5232       Result = DAG.getConstant(0, VT);
5233     else
5234       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5235                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5236   }
5237
5238   // Return the new loaded value.
5239   return Result;
5240 }
5241
5242 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5243   SDValue N0 = N->getOperand(0);
5244   SDValue N1 = N->getOperand(1);
5245   EVT VT = N->getValueType(0);
5246   EVT EVT = cast<VTSDNode>(N1)->getVT();
5247   unsigned VTBits = VT.getScalarType().getSizeInBits();
5248   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5249
5250   // fold (sext_in_reg c1) -> c1
5251   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5252     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5253
5254   // If the input is already sign extended, just drop the extension.
5255   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5256     return N0;
5257
5258   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5259   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5260       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5261     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5262                        N0.getOperand(0), N1);
5263   }
5264
5265   // fold (sext_in_reg (sext x)) -> (sext x)
5266   // fold (sext_in_reg (aext x)) -> (sext x)
5267   // if x is small enough.
5268   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5269     SDValue N00 = N0.getOperand(0);
5270     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5271         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5272       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5273   }
5274
5275   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5276   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5277     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5278
5279   // fold operands of sext_in_reg based on knowledge that the top bits are not
5280   // demanded.
5281   if (SimplifyDemandedBits(SDValue(N, 0)))
5282     return SDValue(N, 0);
5283
5284   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5285   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5286   SDValue NarrowLoad = ReduceLoadWidth(N);
5287   if (NarrowLoad.getNode())
5288     return NarrowLoad;
5289
5290   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5291   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5292   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5293   if (N0.getOpcode() == ISD::SRL) {
5294     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5295       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5296         // We can turn this into an SRA iff the input to the SRL is already sign
5297         // extended enough.
5298         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5299         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5300           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5301                              N0.getOperand(0), N0.getOperand(1));
5302       }
5303   }
5304
5305   // fold (sext_inreg (extload x)) -> (sextload x)
5306   if (ISD::isEXTLoad(N0.getNode()) &&
5307       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5308       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5309       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5310        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5311     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5312     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5313                                      LN0->getChain(),
5314                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5315                                      EVT,
5316                                      LN0->isVolatile(), LN0->isNonTemporal(),
5317                                      LN0->getAlignment());
5318     CombineTo(N, ExtLoad);
5319     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5320     AddToWorkList(ExtLoad.getNode());
5321     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5322   }
5323   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5324   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5325       N0.hasOneUse() &&
5326       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5327       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5328        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5329     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5330     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5331                                      LN0->getChain(),
5332                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5333                                      EVT,
5334                                      LN0->isVolatile(), LN0->isNonTemporal(),
5335                                      LN0->getAlignment());
5336     CombineTo(N, ExtLoad);
5337     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5338     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5339   }
5340
5341   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5342   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5343     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5344                                        N0.getOperand(1), false);
5345     if (BSwap.getNode() != 0)
5346       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5347                          BSwap, N1);
5348   }
5349
5350   return SDValue();
5351 }
5352
5353 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5354   SDValue N0 = N->getOperand(0);
5355   EVT VT = N->getValueType(0);
5356   bool isLE = TLI.isLittleEndian();
5357
5358   // noop truncate
5359   if (N0.getValueType() == N->getValueType(0))
5360     return N0;
5361   // fold (truncate c1) -> c1
5362   if (isa<ConstantSDNode>(N0))
5363     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5364   // fold (truncate (truncate x)) -> (truncate x)
5365   if (N0.getOpcode() == ISD::TRUNCATE)
5366     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5367   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5368   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5369       N0.getOpcode() == ISD::SIGN_EXTEND ||
5370       N0.getOpcode() == ISD::ANY_EXTEND) {
5371     if (N0.getOperand(0).getValueType().bitsLT(VT))
5372       // if the source is smaller than the dest, we still need an extend
5373       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5374                          N0.getOperand(0));
5375     if (N0.getOperand(0).getValueType().bitsGT(VT))
5376       // if the source is larger than the dest, than we just need the truncate
5377       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5378     // if the source and dest are the same type, we can drop both the extend
5379     // and the truncate.
5380     return N0.getOperand(0);
5381   }
5382
5383   // Fold extract-and-trunc into a narrow extract. For example:
5384   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5385   //   i32 y = TRUNCATE(i64 x)
5386   //        -- becomes --
5387   //   v16i8 b = BITCAST (v2i64 val)
5388   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5389   //
5390   // Note: We only run this optimization after type legalization (which often
5391   // creates this pattern) and before operation legalization after which
5392   // we need to be more careful about the vector instructions that we generate.
5393   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5394       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5395
5396     EVT VecTy = N0.getOperand(0).getValueType();
5397     EVT ExTy = N0.getValueType();
5398     EVT TrTy = N->getValueType(0);
5399
5400     unsigned NumElem = VecTy.getVectorNumElements();
5401     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5402
5403     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5404     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5405
5406     SDValue EltNo = N0->getOperand(1);
5407     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5408       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5409       EVT IndexTy = N0->getOperand(1).getValueType();
5410       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5411
5412       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5413                               NVT, N0.getOperand(0));
5414
5415       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5416                          SDLoc(N), TrTy, V,
5417                          DAG.getConstant(Index, IndexTy));
5418     }
5419   }
5420
5421   // Fold a series of buildvector, bitcast, and truncate if possible.
5422   // For example fold
5423   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5424   //   (2xi32 (buildvector x, y)).
5425   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5426       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5427       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5428       N0.getOperand(0).hasOneUse()) {
5429
5430     SDValue BuildVect = N0.getOperand(0);
5431     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5432     EVT TruncVecEltTy = VT.getVectorElementType();
5433
5434     // Check that the element types match.
5435     if (BuildVectEltTy == TruncVecEltTy) {
5436       // Now we only need to compute the offset of the truncated elements.
5437       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5438       unsigned TruncVecNumElts = VT.getVectorNumElements();
5439       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5440
5441       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5442              "Invalid number of elements");
5443
5444       SmallVector<SDValue, 8> Opnds;
5445       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5446         Opnds.push_back(BuildVect.getOperand(i));
5447
5448       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5449                          Opnds.size());
5450     }
5451   }
5452
5453   // See if we can simplify the input to this truncate through knowledge that
5454   // only the low bits are being used.
5455   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5456   // Currently we only perform this optimization on scalars because vectors
5457   // may have different active low bits.
5458   if (!VT.isVector()) {
5459     SDValue Shorter =
5460       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5461                                                VT.getSizeInBits()));
5462     if (Shorter.getNode())
5463       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5464   }
5465   // fold (truncate (load x)) -> (smaller load x)
5466   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5467   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5468     SDValue Reduced = ReduceLoadWidth(N);
5469     if (Reduced.getNode())
5470       return Reduced;
5471   }
5472   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5473   // where ... are all 'undef'.
5474   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5475     SmallVector<EVT, 8> VTs;
5476     SDValue V;
5477     unsigned Idx = 0;
5478     unsigned NumDefs = 0;
5479
5480     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5481       SDValue X = N0.getOperand(i);
5482       if (X.getOpcode() != ISD::UNDEF) {
5483         V = X;
5484         Idx = i;
5485         NumDefs++;
5486       }
5487       // Stop if more than one members are non-undef.
5488       if (NumDefs > 1)
5489         break;
5490       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5491                                      VT.getVectorElementType(),
5492                                      X.getValueType().getVectorNumElements()));
5493     }
5494
5495     if (NumDefs == 0)
5496       return DAG.getUNDEF(VT);
5497
5498     if (NumDefs == 1) {
5499       assert(V.getNode() && "The single defined operand is empty!");
5500       SmallVector<SDValue, 8> Opnds;
5501       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5502         if (i != Idx) {
5503           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5504           continue;
5505         }
5506         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5507         AddToWorkList(NV.getNode());
5508         Opnds.push_back(NV);
5509       }
5510       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5511                          &Opnds[0], Opnds.size());
5512     }
5513   }
5514
5515   // Simplify the operands using demanded-bits information.
5516   if (!VT.isVector() &&
5517       SimplifyDemandedBits(SDValue(N, 0)))
5518     return SDValue(N, 0);
5519
5520   return SDValue();
5521 }
5522
5523 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5524   SDValue Elt = N->getOperand(i);
5525   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5526     return Elt.getNode();
5527   return Elt.getOperand(Elt.getResNo()).getNode();
5528 }
5529
5530 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5531 /// if load locations are consecutive.
5532 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5533   assert(N->getOpcode() == ISD::BUILD_PAIR);
5534
5535   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5536   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5537   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5538       LD1->getPointerInfo().getAddrSpace() !=
5539          LD2->getPointerInfo().getAddrSpace())
5540     return SDValue();
5541   EVT LD1VT = LD1->getValueType(0);
5542
5543   if (ISD::isNON_EXTLoad(LD2) &&
5544       LD2->hasOneUse() &&
5545       // If both are volatile this would reduce the number of volatile loads.
5546       // If one is volatile it might be ok, but play conservative and bail out.
5547       !LD1->isVolatile() &&
5548       !LD2->isVolatile() &&
5549       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5550     unsigned Align = LD1->getAlignment();
5551     unsigned NewAlign = TLI.getDataLayout()->
5552       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5553
5554     if (NewAlign <= Align &&
5555         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5556       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5557                          LD1->getBasePtr(), LD1->getPointerInfo(),
5558                          false, false, false, Align);
5559   }
5560
5561   return SDValue();
5562 }
5563
5564 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5565   SDValue N0 = N->getOperand(0);
5566   EVT VT = N->getValueType(0);
5567
5568   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5569   // Only do this before legalize, since afterward the target may be depending
5570   // on the bitconvert.
5571   // First check to see if this is all constant.
5572   if (!LegalTypes &&
5573       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5574       VT.isVector()) {
5575     bool isSimple = true;
5576     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5577       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5578           N0.getOperand(i).getOpcode() != ISD::Constant &&
5579           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5580         isSimple = false;
5581         break;
5582       }
5583
5584     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5585     assert(!DestEltVT.isVector() &&
5586            "Element type of vector ValueType must not be vector!");
5587     if (isSimple)
5588       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5589   }
5590
5591   // If the input is a constant, let getNode fold it.
5592   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5593     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5594     if (Res.getNode() != N) {
5595       if (!LegalOperations ||
5596           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5597         return Res;
5598
5599       // Folding it resulted in an illegal node, and it's too late to
5600       // do that. Clean up the old node and forego the transformation.
5601       // Ideally this won't happen very often, because instcombine
5602       // and the earlier dagcombine runs (where illegal nodes are
5603       // permitted) should have folded most of them already.
5604       DAG.DeleteNode(Res.getNode());
5605     }
5606   }
5607
5608   // (conv (conv x, t1), t2) -> (conv x, t2)
5609   if (N0.getOpcode() == ISD::BITCAST)
5610     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5611                        N0.getOperand(0));
5612
5613   // fold (conv (load x)) -> (load (conv*)x)
5614   // If the resultant load doesn't need a higher alignment than the original!
5615   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5616       // Do not change the width of a volatile load.
5617       !cast<LoadSDNode>(N0)->isVolatile() &&
5618       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5619     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5620     unsigned Align = TLI.getDataLayout()->
5621       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5622     unsigned OrigAlign = LN0->getAlignment();
5623
5624     if (Align <= OrigAlign) {
5625       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5626                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5627                                  LN0->isVolatile(), LN0->isNonTemporal(),
5628                                  LN0->isInvariant(), OrigAlign);
5629       AddToWorkList(N);
5630       CombineTo(N0.getNode(),
5631                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5632                             N0.getValueType(), Load),
5633                 Load.getValue(1));
5634       return Load;
5635     }
5636   }
5637
5638   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5639   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5640   // This often reduces constant pool loads.
5641   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5642        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5643       N0.getNode()->hasOneUse() && VT.isInteger() &&
5644       !VT.isVector() && !N0.getValueType().isVector()) {
5645     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5646                                   N0.getOperand(0));
5647     AddToWorkList(NewConv.getNode());
5648
5649     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5650     if (N0.getOpcode() == ISD::FNEG)
5651       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5652                          NewConv, DAG.getConstant(SignBit, VT));
5653     assert(N0.getOpcode() == ISD::FABS);
5654     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5655                        NewConv, DAG.getConstant(~SignBit, VT));
5656   }
5657
5658   // fold (bitconvert (fcopysign cst, x)) ->
5659   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5660   // Note that we don't handle (copysign x, cst) because this can always be
5661   // folded to an fneg or fabs.
5662   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5663       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5664       VT.isInteger() && !VT.isVector()) {
5665     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5666     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5667     if (isTypeLegal(IntXVT)) {
5668       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5669                               IntXVT, N0.getOperand(1));
5670       AddToWorkList(X.getNode());
5671
5672       // If X has a different width than the result/lhs, sext it or truncate it.
5673       unsigned VTWidth = VT.getSizeInBits();
5674       if (OrigXWidth < VTWidth) {
5675         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5676         AddToWorkList(X.getNode());
5677       } else if (OrigXWidth > VTWidth) {
5678         // To get the sign bit in the right place, we have to shift it right
5679         // before truncating.
5680         X = DAG.getNode(ISD::SRL, SDLoc(X),
5681                         X.getValueType(), X,
5682                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5683         AddToWorkList(X.getNode());
5684         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5685         AddToWorkList(X.getNode());
5686       }
5687
5688       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5689       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5690                       X, DAG.getConstant(SignBit, VT));
5691       AddToWorkList(X.getNode());
5692
5693       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5694                                 VT, N0.getOperand(0));
5695       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5696                         Cst, DAG.getConstant(~SignBit, VT));
5697       AddToWorkList(Cst.getNode());
5698
5699       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5700     }
5701   }
5702
5703   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5704   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5705     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5706     if (CombineLD.getNode())
5707       return CombineLD;
5708   }
5709
5710   return SDValue();
5711 }
5712
5713 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5714   EVT VT = N->getValueType(0);
5715   return CombineConsecutiveLoads(N, VT);
5716 }
5717
5718 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5719 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5720 /// destination element value type.
5721 SDValue DAGCombiner::
5722 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5723   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5724
5725   // If this is already the right type, we're done.
5726   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5727
5728   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5729   unsigned DstBitSize = DstEltVT.getSizeInBits();
5730
5731   // If this is a conversion of N elements of one type to N elements of another
5732   // type, convert each element.  This handles FP<->INT cases.
5733   if (SrcBitSize == DstBitSize) {
5734     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5735                               BV->getValueType(0).getVectorNumElements());
5736
5737     // Due to the FP element handling below calling this routine recursively,
5738     // we can end up with a scalar-to-vector node here.
5739     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5740       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5741                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5742                                      DstEltVT, BV->getOperand(0)));
5743
5744     SmallVector<SDValue, 8> Ops;
5745     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5746       SDValue Op = BV->getOperand(i);
5747       // If the vector element type is not legal, the BUILD_VECTOR operands
5748       // are promoted and implicitly truncated.  Make that explicit here.
5749       if (Op.getValueType() != SrcEltVT)
5750         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5751       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5752                                 DstEltVT, Op));
5753       AddToWorkList(Ops.back().getNode());
5754     }
5755     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5756                        &Ops[0], Ops.size());
5757   }
5758
5759   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5760   // handle annoying details of growing/shrinking FP values, we convert them to
5761   // int first.
5762   if (SrcEltVT.isFloatingPoint()) {
5763     // Convert the input float vector to a int vector where the elements are the
5764     // same sizes.
5765     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5766     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5767     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5768     SrcEltVT = IntVT;
5769   }
5770
5771   // Now we know the input is an integer vector.  If the output is a FP type,
5772   // convert to integer first, then to FP of the right size.
5773   if (DstEltVT.isFloatingPoint()) {
5774     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5775     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5776     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5777
5778     // Next, convert to FP elements of the same size.
5779     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5780   }
5781
5782   // Okay, we know the src/dst types are both integers of differing types.
5783   // Handling growing first.
5784   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5785   if (SrcBitSize < DstBitSize) {
5786     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5787
5788     SmallVector<SDValue, 8> Ops;
5789     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5790          i += NumInputsPerOutput) {
5791       bool isLE = TLI.isLittleEndian();
5792       APInt NewBits = APInt(DstBitSize, 0);
5793       bool EltIsUndef = true;
5794       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5795         // Shift the previously computed bits over.
5796         NewBits <<= SrcBitSize;
5797         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5798         if (Op.getOpcode() == ISD::UNDEF) continue;
5799         EltIsUndef = false;
5800
5801         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5802                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5803       }
5804
5805       if (EltIsUndef)
5806         Ops.push_back(DAG.getUNDEF(DstEltVT));
5807       else
5808         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5809     }
5810
5811     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5812     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5813                        &Ops[0], Ops.size());
5814   }
5815
5816   // Finally, this must be the case where we are shrinking elements: each input
5817   // turns into multiple outputs.
5818   bool isS2V = ISD::isScalarToVector(BV);
5819   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5820   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5821                             NumOutputsPerInput*BV->getNumOperands());
5822   SmallVector<SDValue, 8> Ops;
5823
5824   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5825     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5826       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5827         Ops.push_back(DAG.getUNDEF(DstEltVT));
5828       continue;
5829     }
5830
5831     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5832                   getAPIntValue().zextOrTrunc(SrcBitSize);
5833
5834     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5835       APInt ThisVal = OpVal.trunc(DstBitSize);
5836       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5837       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5838         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5839         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5840                            Ops[0]);
5841       OpVal = OpVal.lshr(DstBitSize);
5842     }
5843
5844     // For big endian targets, swap the order of the pieces of each element.
5845     if (TLI.isBigEndian())
5846       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5847   }
5848
5849   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5850                      &Ops[0], Ops.size());
5851 }
5852
5853 SDValue DAGCombiner::visitFADD(SDNode *N) {
5854   SDValue N0 = N->getOperand(0);
5855   SDValue N1 = N->getOperand(1);
5856   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5857   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5858   EVT VT = N->getValueType(0);
5859
5860   // fold vector ops
5861   if (VT.isVector()) {
5862     SDValue FoldedVOp = SimplifyVBinOp(N);
5863     if (FoldedVOp.getNode()) return FoldedVOp;
5864   }
5865
5866   // fold (fadd c1, c2) -> c1 + c2
5867   if (N0CFP && N1CFP)
5868     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5869   // canonicalize constant to RHS
5870   if (N0CFP && !N1CFP)
5871     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5872   // fold (fadd A, 0) -> A
5873   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5874       N1CFP->getValueAPF().isZero())
5875     return N0;
5876   // fold (fadd A, (fneg B)) -> (fsub A, B)
5877   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5878     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5879     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5880                        GetNegatedExpression(N1, DAG, LegalOperations));
5881   // fold (fadd (fneg A), B) -> (fsub B, A)
5882   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5883     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5884     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5885                        GetNegatedExpression(N0, DAG, LegalOperations));
5886
5887   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5888   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5889       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5890       isa<ConstantFPSDNode>(N0.getOperand(1)))
5891     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
5892                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
5893                                    N0.getOperand(1), N1));
5894
5895   // No FP constant should be created after legalization as Instruction
5896   // Selection pass has hard time in dealing with FP constant.
5897   //
5898   // We don't need test this condition for transformation like following, as
5899   // the DAG being transformed implies it is legal to take FP constant as
5900   // operand.
5901   // 
5902   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
5903   // 
5904   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5905
5906   // If allow, fold (fadd (fneg x), x) -> 0.0
5907   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5908       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) {
5909     return DAG.getConstantFP(0.0, VT);
5910   }
5911
5912     // If allow, fold (fadd x, (fneg x)) -> 0.0
5913   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5914       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) {
5915     return DAG.getConstantFP(0.0, VT);
5916   }
5917
5918   // In unsafe math mode, we can fold chains of FADD's of the same value
5919   // into multiplications.  This transform is not safe in general because
5920   // we are reducing the number of rounding steps.
5921   if (DAG.getTarget().Options.UnsafeFPMath &&
5922       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5923       !N0CFP && !N1CFP) {
5924     if (N0.getOpcode() == ISD::FMUL) {
5925       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5926       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5927
5928       // (fadd (fmul c, x), x) -> (fmul x, c+1)
5929       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5930         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5931                                      SDValue(CFP00, 0),
5932                                      DAG.getConstantFP(1.0, VT));
5933         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5934                            N1, NewCFP);
5935       }
5936
5937       // (fadd (fmul x, c), x) -> (fmul x, c+1)
5938       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5939         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5940                                      SDValue(CFP01, 0),
5941                                      DAG.getConstantFP(1.0, VT));
5942         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5943                            N1, NewCFP);
5944       }
5945
5946       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
5947       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5948           N1.getOperand(0) == N1.getOperand(1) &&
5949           N0.getOperand(1) == N1.getOperand(0)) {
5950         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5951                                      SDValue(CFP00, 0),
5952                                      DAG.getConstantFP(2.0, VT));
5953         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5954                            N0.getOperand(1), NewCFP);
5955       }
5956
5957       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
5958       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5959           N1.getOperand(0) == N1.getOperand(1) &&
5960           N0.getOperand(0) == N1.getOperand(0)) {
5961         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5962                                      SDValue(CFP01, 0),
5963                                      DAG.getConstantFP(2.0, VT));
5964         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5965                            N0.getOperand(0), NewCFP);
5966       }
5967     }
5968
5969     if (N1.getOpcode() == ISD::FMUL) {
5970       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5971       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
5972
5973       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
5974       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
5975         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5976                                      SDValue(CFP10, 0),
5977                                      DAG.getConstantFP(1.0, VT));
5978         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5979                            N0, NewCFP);
5980       }
5981
5982       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
5983       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
5984         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5985                                      SDValue(CFP11, 0),
5986                                      DAG.getConstantFP(1.0, VT));
5987         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5988                            N0, NewCFP);
5989       }
5990
5991
5992       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
5993       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
5994           N0.getOperand(0) == N0.getOperand(1) &&
5995           N1.getOperand(1) == N0.getOperand(0)) {
5996         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5997                                      SDValue(CFP10, 0),
5998                                      DAG.getConstantFP(2.0, VT));
5999         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6000                            N1.getOperand(1), NewCFP);
6001       }
6002
6003       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6004       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6005           N0.getOperand(0) == N0.getOperand(1) &&
6006           N1.getOperand(0) == N0.getOperand(0)) {
6007         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6008                                      SDValue(CFP11, 0),
6009                                      DAG.getConstantFP(2.0, VT));
6010         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6011                            N1.getOperand(0), NewCFP);
6012       }
6013     }
6014
6015     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6016       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6017       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6018       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6019           (N0.getOperand(0) == N1)) {
6020         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6021                            N1, DAG.getConstantFP(3.0, VT));
6022       }
6023     }
6024
6025     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6026       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6027       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6028       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6029           N1.getOperand(0) == N0) {
6030         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6031                            N0, DAG.getConstantFP(3.0, VT));
6032       }
6033     }
6034
6035     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6036     if (AllowNewFpConst &&
6037         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6038         N0.getOperand(0) == N0.getOperand(1) &&
6039         N1.getOperand(0) == N1.getOperand(1) &&
6040         N0.getOperand(0) == N1.getOperand(0)) {
6041       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6042                          N0.getOperand(0),
6043                          DAG.getConstantFP(4.0, VT));
6044     }
6045   }
6046
6047   // FADD -> FMA combines:
6048   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6049        DAG.getTarget().Options.UnsafeFPMath) &&
6050       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6051       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6052
6053     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6054     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6055       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6056                          N0.getOperand(0), N0.getOperand(1), N1);
6057     }
6058
6059     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6060     // Note: Commutes FADD operands.
6061     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6062       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6063                          N1.getOperand(0), N1.getOperand(1), N0);
6064     }
6065   }
6066
6067   return SDValue();
6068 }
6069
6070 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6071   SDValue N0 = N->getOperand(0);
6072   SDValue N1 = N->getOperand(1);
6073   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6074   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6075   EVT VT = N->getValueType(0);
6076   SDLoc dl(N);
6077
6078   // fold vector ops
6079   if (VT.isVector()) {
6080     SDValue FoldedVOp = SimplifyVBinOp(N);
6081     if (FoldedVOp.getNode()) return FoldedVOp;
6082   }
6083
6084   // fold (fsub c1, c2) -> c1-c2
6085   if (N0CFP && N1CFP)
6086     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6087   // fold (fsub A, 0) -> A
6088   if (DAG.getTarget().Options.UnsafeFPMath &&
6089       N1CFP && N1CFP->getValueAPF().isZero())
6090     return N0;
6091   // fold (fsub 0, B) -> -B
6092   if (DAG.getTarget().Options.UnsafeFPMath &&
6093       N0CFP && N0CFP->getValueAPF().isZero()) {
6094     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6095       return GetNegatedExpression(N1, DAG, LegalOperations);
6096     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6097       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6098   }
6099   // fold (fsub A, (fneg B)) -> (fadd A, B)
6100   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6101     return DAG.getNode(ISD::FADD, dl, VT, N0,
6102                        GetNegatedExpression(N1, DAG, LegalOperations));
6103
6104   // If 'unsafe math' is enabled, fold
6105   //    (fsub x, x) -> 0.0 &
6106   //    (fsub x, (fadd x, y)) -> (fneg y) &
6107   //    (fsub x, (fadd y, x)) -> (fneg y)
6108   if (DAG.getTarget().Options.UnsafeFPMath) {
6109     if (N0 == N1)
6110       return DAG.getConstantFP(0.0f, VT);
6111
6112     if (N1.getOpcode() == ISD::FADD) {
6113       SDValue N10 = N1->getOperand(0);
6114       SDValue N11 = N1->getOperand(1);
6115
6116       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6117                                           &DAG.getTarget().Options))
6118         return GetNegatedExpression(N11, DAG, LegalOperations);
6119       else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6120                                                &DAG.getTarget().Options))
6121         return GetNegatedExpression(N10, DAG, LegalOperations);
6122     }
6123   }
6124
6125   // FSUB -> FMA combines:
6126   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6127        DAG.getTarget().Options.UnsafeFPMath) &&
6128       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6129       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6130
6131     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6132     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6133       return DAG.getNode(ISD::FMA, dl, VT,
6134                          N0.getOperand(0), N0.getOperand(1),
6135                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6136     }
6137
6138     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6139     // Note: Commutes FSUB operands.
6140     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6141       return DAG.getNode(ISD::FMA, dl, VT,
6142                          DAG.getNode(ISD::FNEG, dl, VT,
6143                          N1.getOperand(0)),
6144                          N1.getOperand(1), N0);
6145     }
6146
6147     // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6148     if (N0.getOpcode() == ISD::FNEG && 
6149         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6150         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6151       SDValue N00 = N0.getOperand(0).getOperand(0);
6152       SDValue N01 = N0.getOperand(0).getOperand(1);
6153       return DAG.getNode(ISD::FMA, dl, VT,
6154                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6155                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6156     }
6157   }
6158
6159   return SDValue();
6160 }
6161
6162 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6163   SDValue N0 = N->getOperand(0);
6164   SDValue N1 = N->getOperand(1);
6165   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6166   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6167   EVT VT = N->getValueType(0);
6168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6169
6170   // fold vector ops
6171   if (VT.isVector()) {
6172     SDValue FoldedVOp = SimplifyVBinOp(N);
6173     if (FoldedVOp.getNode()) return FoldedVOp;
6174   }
6175
6176   // fold (fmul c1, c2) -> c1*c2
6177   if (N0CFP && N1CFP)
6178     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6179   // canonicalize constant to RHS
6180   if (N0CFP && !N1CFP)
6181     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6182   // fold (fmul A, 0) -> 0
6183   if (DAG.getTarget().Options.UnsafeFPMath &&
6184       N1CFP && N1CFP->getValueAPF().isZero())
6185     return N1;
6186   // fold (fmul A, 0) -> 0, vector edition.
6187   if (DAG.getTarget().Options.UnsafeFPMath &&
6188       ISD::isBuildVectorAllZeros(N1.getNode()))
6189     return N1;
6190   // fold (fmul A, 1.0) -> A
6191   if (N1CFP && N1CFP->isExactlyValue(1.0))
6192     return N0;
6193   // fold (fmul X, 2.0) -> (fadd X, X)
6194   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6195     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6196   // fold (fmul X, -1.0) -> (fneg X)
6197   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6198     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6199       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6200
6201   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6202   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6203                                        &DAG.getTarget().Options)) {
6204     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 
6205                                          &DAG.getTarget().Options)) {
6206       // Both can be negated for free, check to see if at least one is cheaper
6207       // negated.
6208       if (LHSNeg == 2 || RHSNeg == 2)
6209         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6210                            GetNegatedExpression(N0, DAG, LegalOperations),
6211                            GetNegatedExpression(N1, DAG, LegalOperations));
6212     }
6213   }
6214
6215   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6216   if (DAG.getTarget().Options.UnsafeFPMath &&
6217       N1CFP && N0.getOpcode() == ISD::FMUL &&
6218       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6219     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6220                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6221                                    N0.getOperand(1), N1));
6222
6223   return SDValue();
6224 }
6225
6226 SDValue DAGCombiner::visitFMA(SDNode *N) {
6227   SDValue N0 = N->getOperand(0);
6228   SDValue N1 = N->getOperand(1);
6229   SDValue N2 = N->getOperand(2);
6230   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6231   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6232   EVT VT = N->getValueType(0);
6233   SDLoc dl(N);
6234
6235   if (DAG.getTarget().Options.UnsafeFPMath) {
6236     if (N0CFP && N0CFP->isZero())
6237       return N2;
6238     if (N1CFP && N1CFP->isZero())
6239       return N2;
6240   }
6241   if (N0CFP && N0CFP->isExactlyValue(1.0))
6242     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6243   if (N1CFP && N1CFP->isExactlyValue(1.0))
6244     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6245
6246   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6247   if (N0CFP && !N1CFP)
6248     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6249
6250   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6251   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6252       N2.getOpcode() == ISD::FMUL &&
6253       N0 == N2.getOperand(0) &&
6254       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6255     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6256                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6257   }
6258
6259
6260   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6261   if (DAG.getTarget().Options.UnsafeFPMath &&
6262       N0.getOpcode() == ISD::FMUL && N1CFP &&
6263       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6264     return DAG.getNode(ISD::FMA, dl, VT,
6265                        N0.getOperand(0),
6266                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6267                        N2);
6268   }
6269
6270   // (fma x, 1, y) -> (fadd x, y)
6271   // (fma x, -1, y) -> (fadd (fneg x), y)
6272   if (N1CFP) {
6273     if (N1CFP->isExactlyValue(1.0))
6274       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6275
6276     if (N1CFP->isExactlyValue(-1.0) &&
6277         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6278       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6279       AddToWorkList(RHSNeg.getNode());
6280       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6281     }
6282   }
6283
6284   // (fma x, c, x) -> (fmul x, (c+1))
6285   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6286     return DAG.getNode(ISD::FMUL, dl, VT,
6287                        N0,
6288                        DAG.getNode(ISD::FADD, dl, VT,
6289                                    N1, DAG.getConstantFP(1.0, VT)));
6290   }
6291
6292   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6293   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6294       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6295     return DAG.getNode(ISD::FMUL, dl, VT,
6296                        N0,
6297                        DAG.getNode(ISD::FADD, dl, VT,
6298                                    N1, DAG.getConstantFP(-1.0, VT)));
6299   }
6300
6301
6302   return SDValue();
6303 }
6304
6305 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6306   SDValue N0 = N->getOperand(0);
6307   SDValue N1 = N->getOperand(1);
6308   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6309   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6310   EVT VT = N->getValueType(0);
6311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6312
6313   // fold vector ops
6314   if (VT.isVector()) {
6315     SDValue FoldedVOp = SimplifyVBinOp(N);
6316     if (FoldedVOp.getNode()) return FoldedVOp;
6317   }
6318
6319   // fold (fdiv c1, c2) -> c1/c2
6320   if (N0CFP && N1CFP)
6321     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6322
6323   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6324   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6325     // Compute the reciprocal 1.0 / c2.
6326     APFloat N1APF = N1CFP->getValueAPF();
6327     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6328     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6329     // Only do the transform if the reciprocal is a legal fp immediate that
6330     // isn't too nasty (eg NaN, denormal, ...).
6331     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6332         (!LegalOperations ||
6333          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6334          // backend)... we should handle this gracefully after Legalize.
6335          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6336          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6337          TLI.isFPImmLegal(Recip, VT)))
6338       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6339                          DAG.getConstantFP(Recip, VT));
6340   }
6341
6342   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6343   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6344                                        &DAG.getTarget().Options)) {
6345     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6346                                          &DAG.getTarget().Options)) {
6347       // Both can be negated for free, check to see if at least one is cheaper
6348       // negated.
6349       if (LHSNeg == 2 || RHSNeg == 2)
6350         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6351                            GetNegatedExpression(N0, DAG, LegalOperations),
6352                            GetNegatedExpression(N1, DAG, LegalOperations));
6353     }
6354   }
6355
6356   return SDValue();
6357 }
6358
6359 SDValue DAGCombiner::visitFREM(SDNode *N) {
6360   SDValue N0 = N->getOperand(0);
6361   SDValue N1 = N->getOperand(1);
6362   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6363   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6364   EVT VT = N->getValueType(0);
6365
6366   // fold (frem c1, c2) -> fmod(c1,c2)
6367   if (N0CFP && N1CFP)
6368     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6369
6370   return SDValue();
6371 }
6372
6373 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6374   SDValue N0 = N->getOperand(0);
6375   SDValue N1 = N->getOperand(1);
6376   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6377   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6378   EVT VT = N->getValueType(0);
6379
6380   if (N0CFP && N1CFP)  // Constant fold
6381     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6382
6383   if (N1CFP) {
6384     const APFloat& V = N1CFP->getValueAPF();
6385     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6386     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6387     if (!V.isNegative()) {
6388       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6389         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6390     } else {
6391       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6392         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6393                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6394     }
6395   }
6396
6397   // copysign(fabs(x), y) -> copysign(x, y)
6398   // copysign(fneg(x), y) -> copysign(x, y)
6399   // copysign(copysign(x,z), y) -> copysign(x, y)
6400   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6401       N0.getOpcode() == ISD::FCOPYSIGN)
6402     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6403                        N0.getOperand(0), N1);
6404
6405   // copysign(x, abs(y)) -> abs(x)
6406   if (N1.getOpcode() == ISD::FABS)
6407     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6408
6409   // copysign(x, copysign(y,z)) -> copysign(x, z)
6410   if (N1.getOpcode() == ISD::FCOPYSIGN)
6411     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6412                        N0, N1.getOperand(1));
6413
6414   // copysign(x, fp_extend(y)) -> copysign(x, y)
6415   // copysign(x, fp_round(y)) -> copysign(x, y)
6416   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6417     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6418                        N0, N1.getOperand(0));
6419
6420   return SDValue();
6421 }
6422
6423 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6424   SDValue N0 = N->getOperand(0);
6425   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6426   EVT VT = N->getValueType(0);
6427   EVT OpVT = N0.getValueType();
6428
6429   // fold (sint_to_fp c1) -> c1fp
6430   if (N0C &&
6431       // ...but only if the target supports immediate floating-point values
6432       (!LegalOperations ||
6433        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6434     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6435
6436   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6437   // but UINT_TO_FP is legal on this target, try to convert.
6438   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6439       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6440     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6441     if (DAG.SignBitIsZero(N0))
6442       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6443   }
6444
6445   // The next optimizations are desireable only if SELECT_CC can be lowered.
6446   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6447   // having to say they don't support SELECT_CC on every type the DAG knows
6448   // about, since there is no way to mark an opcode illegal at all value types
6449   // (See also visitSELECT)
6450   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6451     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6452     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6453         !VT.isVector() &&
6454         (!LegalOperations ||
6455          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6456       SDValue Ops[] =
6457         { N0.getOperand(0), N0.getOperand(1),
6458           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6459           N0.getOperand(2) };
6460       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6461     }
6462
6463     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6464     //      (select_cc x, y, 1.0, 0.0,, cc)
6465     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6466         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6467         (!LegalOperations ||
6468          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6469       SDValue Ops[] =
6470         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6471           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6472           N0.getOperand(0).getOperand(2) };
6473       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6474     }
6475   }
6476
6477   return SDValue();
6478 }
6479
6480 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6481   SDValue N0 = N->getOperand(0);
6482   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6483   EVT VT = N->getValueType(0);
6484   EVT OpVT = N0.getValueType();
6485
6486   // fold (uint_to_fp c1) -> c1fp
6487   if (N0C &&
6488       // ...but only if the target supports immediate floating-point values
6489       (!LegalOperations ||
6490        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6491     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6492
6493   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6494   // but SINT_TO_FP is legal on this target, try to convert.
6495   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6496       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6497     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6498     if (DAG.SignBitIsZero(N0))
6499       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6500   }
6501
6502   // The next optimizations are desireable only if SELECT_CC can be lowered.
6503   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6504   // having to say they don't support SELECT_CC on every type the DAG knows
6505   // about, since there is no way to mark an opcode illegal at all value types
6506   // (See also visitSELECT)
6507   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6508     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6509
6510     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6511         (!LegalOperations ||
6512          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6513       SDValue Ops[] =
6514         { N0.getOperand(0), N0.getOperand(1),
6515           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6516           N0.getOperand(2) };
6517       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6518     }
6519   }
6520
6521   return SDValue();
6522 }
6523
6524 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6525   SDValue N0 = N->getOperand(0);
6526   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6527   EVT VT = N->getValueType(0);
6528
6529   // fold (fp_to_sint c1fp) -> c1
6530   if (N0CFP)
6531     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6532
6533   return SDValue();
6534 }
6535
6536 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6537   SDValue N0 = N->getOperand(0);
6538   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6539   EVT VT = N->getValueType(0);
6540
6541   // fold (fp_to_uint c1fp) -> c1
6542   if (N0CFP)
6543     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6544
6545   return SDValue();
6546 }
6547
6548 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6549   SDValue N0 = N->getOperand(0);
6550   SDValue N1 = N->getOperand(1);
6551   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6552   EVT VT = N->getValueType(0);
6553
6554   // fold (fp_round c1fp) -> c1fp
6555   if (N0CFP)
6556     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6557
6558   // fold (fp_round (fp_extend x)) -> x
6559   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6560     return N0.getOperand(0);
6561
6562   // fold (fp_round (fp_round x)) -> (fp_round x)
6563   if (N0.getOpcode() == ISD::FP_ROUND) {
6564     // This is a value preserving truncation if both round's are.
6565     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6566                    N0.getNode()->getConstantOperandVal(1) == 1;
6567     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6568                        DAG.getIntPtrConstant(IsTrunc));
6569   }
6570
6571   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6572   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6573     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6574                               N0.getOperand(0), N1);
6575     AddToWorkList(Tmp.getNode());
6576     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6577                        Tmp, N0.getOperand(1));
6578   }
6579
6580   return SDValue();
6581 }
6582
6583 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6584   SDValue N0 = N->getOperand(0);
6585   EVT VT = N->getValueType(0);
6586   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6587   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6588
6589   // fold (fp_round_inreg c1fp) -> c1fp
6590   if (N0CFP && isTypeLegal(EVT)) {
6591     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6592     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6593   }
6594
6595   return SDValue();
6596 }
6597
6598 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6599   SDValue N0 = N->getOperand(0);
6600   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6601   EVT VT = N->getValueType(0);
6602
6603   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6604   if (N->hasOneUse() &&
6605       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6606     return SDValue();
6607
6608   // fold (fp_extend c1fp) -> c1fp
6609   if (N0CFP)
6610     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6611
6612   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6613   // value of X.
6614   if (N0.getOpcode() == ISD::FP_ROUND
6615       && N0.getNode()->getConstantOperandVal(1) == 1) {
6616     SDValue In = N0.getOperand(0);
6617     if (In.getValueType() == VT) return In;
6618     if (VT.bitsLT(In.getValueType()))
6619       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6620                          In, N0.getOperand(1));
6621     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6622   }
6623
6624   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6625   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6626       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6627        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6628     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6629     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6630                                      LN0->getChain(),
6631                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6632                                      N0.getValueType(),
6633                                      LN0->isVolatile(), LN0->isNonTemporal(),
6634                                      LN0->getAlignment());
6635     CombineTo(N, ExtLoad);
6636     CombineTo(N0.getNode(),
6637               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6638                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6639               ExtLoad.getValue(1));
6640     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6641   }
6642
6643   return SDValue();
6644 }
6645
6646 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6647   SDValue N0 = N->getOperand(0);
6648   EVT VT = N->getValueType(0);
6649
6650   if (VT.isVector()) {
6651     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6652     if (FoldedVOp.getNode()) return FoldedVOp;
6653   }
6654
6655   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6656                          &DAG.getTarget().Options))
6657     return GetNegatedExpression(N0, DAG, LegalOperations);
6658
6659   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6660   // constant pool values.
6661   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6662       !VT.isVector() &&
6663       N0.getNode()->hasOneUse() &&
6664       N0.getOperand(0).getValueType().isInteger()) {
6665     SDValue Int = N0.getOperand(0);
6666     EVT IntVT = Int.getValueType();
6667     if (IntVT.isInteger() && !IntVT.isVector()) {
6668       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6669               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6670       AddToWorkList(Int.getNode());
6671       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6672                          VT, Int);
6673     }
6674   }
6675
6676   // (fneg (fmul c, x)) -> (fmul -c, x)
6677   if (N0.getOpcode() == ISD::FMUL) {
6678     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6679     if (CFP1) {
6680       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6681                          N0.getOperand(0),
6682                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6683                                      N0.getOperand(1)));
6684     }
6685   }
6686
6687   return SDValue();
6688 }
6689
6690 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6691   SDValue N0 = N->getOperand(0);
6692   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6693   EVT VT = N->getValueType(0);
6694
6695   // fold (fceil c1) -> fceil(c1)
6696   if (N0CFP)
6697     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6698
6699   return SDValue();
6700 }
6701
6702 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6703   SDValue N0 = N->getOperand(0);
6704   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6705   EVT VT = N->getValueType(0);
6706
6707   // fold (ftrunc c1) -> ftrunc(c1)
6708   if (N0CFP)
6709     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6710
6711   return SDValue();
6712 }
6713
6714 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6715   SDValue N0 = N->getOperand(0);
6716   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6717   EVT VT = N->getValueType(0);
6718
6719   // fold (ffloor c1) -> ffloor(c1)
6720   if (N0CFP)
6721     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6722
6723   return SDValue();
6724 }
6725
6726 SDValue DAGCombiner::visitFABS(SDNode *N) {
6727   SDValue N0 = N->getOperand(0);
6728   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6729   EVT VT = N->getValueType(0);
6730
6731   if (VT.isVector()) {
6732     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6733     if (FoldedVOp.getNode()) return FoldedVOp;
6734   }
6735
6736   // fold (fabs c1) -> fabs(c1)
6737   if (N0CFP)
6738     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6739   // fold (fabs (fabs x)) -> (fabs x)
6740   if (N0.getOpcode() == ISD::FABS)
6741     return N->getOperand(0);
6742   // fold (fabs (fneg x)) -> (fabs x)
6743   // fold (fabs (fcopysign x, y)) -> (fabs x)
6744   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6745     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6746
6747   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6748   // constant pool values.
6749   if (!TLI.isFAbsFree(VT) && 
6750       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6751       N0.getOperand(0).getValueType().isInteger() &&
6752       !N0.getOperand(0).getValueType().isVector()) {
6753     SDValue Int = N0.getOperand(0);
6754     EVT IntVT = Int.getValueType();
6755     if (IntVT.isInteger() && !IntVT.isVector()) {
6756       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6757              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6758       AddToWorkList(Int.getNode());
6759       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6760                          N->getValueType(0), Int);
6761     }
6762   }
6763
6764   return SDValue();
6765 }
6766
6767 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6768   SDValue Chain = N->getOperand(0);
6769   SDValue N1 = N->getOperand(1);
6770   SDValue N2 = N->getOperand(2);
6771
6772   // If N is a constant we could fold this into a fallthrough or unconditional
6773   // branch. However that doesn't happen very often in normal code, because
6774   // Instcombine/SimplifyCFG should have handled the available opportunities.
6775   // If we did this folding here, it would be necessary to update the
6776   // MachineBasicBlock CFG, which is awkward.
6777
6778   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6779   // on the target.
6780   if (N1.getOpcode() == ISD::SETCC &&
6781       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6782                                    N1.getOperand(0).getValueType())) {
6783     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6784                        Chain, N1.getOperand(2),
6785                        N1.getOperand(0), N1.getOperand(1), N2);
6786   }
6787
6788   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6789       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6790        (N1.getOperand(0).hasOneUse() &&
6791         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6792     SDNode *Trunc = 0;
6793     if (N1.getOpcode() == ISD::TRUNCATE) {
6794       // Look pass the truncate.
6795       Trunc = N1.getNode();
6796       N1 = N1.getOperand(0);
6797     }
6798
6799     // Match this pattern so that we can generate simpler code:
6800     //
6801     //   %a = ...
6802     //   %b = and i32 %a, 2
6803     //   %c = srl i32 %b, 1
6804     //   brcond i32 %c ...
6805     //
6806     // into
6807     //
6808     //   %a = ...
6809     //   %b = and i32 %a, 2
6810     //   %c = setcc eq %b, 0
6811     //   brcond %c ...
6812     //
6813     // This applies only when the AND constant value has one bit set and the
6814     // SRL constant is equal to the log2 of the AND constant. The back-end is
6815     // smart enough to convert the result into a TEST/JMP sequence.
6816     SDValue Op0 = N1.getOperand(0);
6817     SDValue Op1 = N1.getOperand(1);
6818
6819     if (Op0.getOpcode() == ISD::AND &&
6820         Op1.getOpcode() == ISD::Constant) {
6821       SDValue AndOp1 = Op0.getOperand(1);
6822
6823       if (AndOp1.getOpcode() == ISD::Constant) {
6824         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6825
6826         if (AndConst.isPowerOf2() &&
6827             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6828           SDValue SetCC =
6829             DAG.getSetCC(SDLoc(N),
6830                          getSetCCResultType(Op0.getValueType()),
6831                          Op0, DAG.getConstant(0, Op0.getValueType()),
6832                          ISD::SETNE);
6833
6834           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6835                                           MVT::Other, Chain, SetCC, N2);
6836           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6837           // will convert it back to (X & C1) >> C2.
6838           CombineTo(N, NewBRCond, false);
6839           // Truncate is dead.
6840           if (Trunc) {
6841             removeFromWorkList(Trunc);
6842             DAG.DeleteNode(Trunc);
6843           }
6844           // Replace the uses of SRL with SETCC
6845           WorkListRemover DeadNodes(*this);
6846           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6847           removeFromWorkList(N1.getNode());
6848           DAG.DeleteNode(N1.getNode());
6849           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6850         }
6851       }
6852     }
6853
6854     if (Trunc)
6855       // Restore N1 if the above transformation doesn't match.
6856       N1 = N->getOperand(1);
6857   }
6858
6859   // Transform br(xor(x, y)) -> br(x != y)
6860   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6861   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6862     SDNode *TheXor = N1.getNode();
6863     SDValue Op0 = TheXor->getOperand(0);
6864     SDValue Op1 = TheXor->getOperand(1);
6865     if (Op0.getOpcode() == Op1.getOpcode()) {
6866       // Avoid missing important xor optimizations.
6867       SDValue Tmp = visitXOR(TheXor);
6868       if (Tmp.getNode()) {
6869         if (Tmp.getNode() != TheXor) {
6870           DEBUG(dbgs() << "\nReplacing.8 ";
6871                 TheXor->dump(&DAG);
6872                 dbgs() << "\nWith: ";
6873                 Tmp.getNode()->dump(&DAG);
6874                 dbgs() << '\n');
6875           WorkListRemover DeadNodes(*this);
6876           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6877           removeFromWorkList(TheXor);
6878           DAG.DeleteNode(TheXor);
6879           return DAG.getNode(ISD::BRCOND, SDLoc(N),
6880                              MVT::Other, Chain, Tmp, N2);
6881         }
6882
6883         // visitXOR has changed XOR's operands or replaced the XOR completely,
6884         // bail out.
6885         return SDValue(N, 0);
6886       }
6887     }
6888
6889     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6890       bool Equal = false;
6891       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6892         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6893             Op0.getOpcode() == ISD::XOR) {
6894           TheXor = Op0.getNode();
6895           Equal = true;
6896         }
6897
6898       EVT SetCCVT = N1.getValueType();
6899       if (LegalTypes)
6900         SetCCVT = getSetCCResultType(SetCCVT);
6901       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
6902                                    SetCCVT,
6903                                    Op0, Op1,
6904                                    Equal ? ISD::SETEQ : ISD::SETNE);
6905       // Replace the uses of XOR with SETCC
6906       WorkListRemover DeadNodes(*this);
6907       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6908       removeFromWorkList(N1.getNode());
6909       DAG.DeleteNode(N1.getNode());
6910       return DAG.getNode(ISD::BRCOND, SDLoc(N),
6911                          MVT::Other, Chain, SetCC, N2);
6912     }
6913   }
6914
6915   return SDValue();
6916 }
6917
6918 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6919 //
6920 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6921   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6922   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6923
6924   // If N is a constant we could fold this into a fallthrough or unconditional
6925   // branch. However that doesn't happen very often in normal code, because
6926   // Instcombine/SimplifyCFG should have handled the available opportunities.
6927   // If we did this folding here, it would be necessary to update the
6928   // MachineBasicBlock CFG, which is awkward.
6929
6930   // Use SimplifySetCC to simplify SETCC's.
6931   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
6932                                CondLHS, CondRHS, CC->get(), SDLoc(N),
6933                                false);
6934   if (Simp.getNode()) AddToWorkList(Simp.getNode());
6935
6936   // fold to a simpler setcc
6937   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6938     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6939                        N->getOperand(0), Simp.getOperand(2),
6940                        Simp.getOperand(0), Simp.getOperand(1),
6941                        N->getOperand(4));
6942
6943   return SDValue();
6944 }
6945
6946 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6947 /// uses N as its base pointer and that N may be folded in the load / store
6948 /// addressing mode.
6949 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6950                                     SelectionDAG &DAG,
6951                                     const TargetLowering &TLI) {
6952   EVT VT;
6953   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6954     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6955       return false;
6956     VT = Use->getValueType(0);
6957   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6958     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6959       return false;
6960     VT = ST->getValue().getValueType();
6961   } else
6962     return false;
6963
6964   TargetLowering::AddrMode AM;
6965   if (N->getOpcode() == ISD::ADD) {
6966     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6967     if (Offset)
6968       // [reg +/- imm]
6969       AM.BaseOffs = Offset->getSExtValue();
6970     else
6971       // [reg +/- reg]
6972       AM.Scale = 1;
6973   } else if (N->getOpcode() == ISD::SUB) {
6974     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6975     if (Offset)
6976       // [reg +/- imm]
6977       AM.BaseOffs = -Offset->getSExtValue();
6978     else
6979       // [reg +/- reg]
6980       AM.Scale = 1;
6981   } else
6982     return false;
6983
6984   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6985 }
6986
6987 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6988 /// pre-indexed load / store when the base pointer is an add or subtract
6989 /// and it has other uses besides the load / store. After the
6990 /// transformation, the new indexed load / store has effectively folded
6991 /// the add / subtract in and all of its other uses are redirected to the
6992 /// new load / store.
6993 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6994   if (Level < AfterLegalizeDAG)
6995     return false;
6996
6997   bool isLoad = true;
6998   SDValue Ptr;
6999   EVT VT;
7000   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7001     if (LD->isIndexed())
7002       return false;
7003     VT = LD->getMemoryVT();
7004     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7005         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7006       return false;
7007     Ptr = LD->getBasePtr();
7008   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7009     if (ST->isIndexed())
7010       return false;
7011     VT = ST->getMemoryVT();
7012     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7013         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7014       return false;
7015     Ptr = ST->getBasePtr();
7016     isLoad = false;
7017   } else {
7018     return false;
7019   }
7020
7021   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7022   // out.  There is no reason to make this a preinc/predec.
7023   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7024       Ptr.getNode()->hasOneUse())
7025     return false;
7026
7027   // Ask the target to do addressing mode selection.
7028   SDValue BasePtr;
7029   SDValue Offset;
7030   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7031   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7032     return false;
7033
7034   // Backends without true r+i pre-indexed forms may need to pass a
7035   // constant base with a variable offset so that constant coercion
7036   // will work with the patterns in canonical form.
7037   bool Swapped = false;
7038   if (isa<ConstantSDNode>(BasePtr)) {
7039     std::swap(BasePtr, Offset);
7040     Swapped = true;
7041   }
7042
7043   // Don't create a indexed load / store with zero offset.
7044   if (isa<ConstantSDNode>(Offset) &&
7045       cast<ConstantSDNode>(Offset)->isNullValue())
7046     return false;
7047
7048   // Try turning it into a pre-indexed load / store except when:
7049   // 1) The new base ptr is a frame index.
7050   // 2) If N is a store and the new base ptr is either the same as or is a
7051   //    predecessor of the value being stored.
7052   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7053   //    that would create a cycle.
7054   // 4) All uses are load / store ops that use it as old base ptr.
7055
7056   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7057   // (plus the implicit offset) to a register to preinc anyway.
7058   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7059     return false;
7060
7061   // Check #2.
7062   if (!isLoad) {
7063     SDValue Val = cast<StoreSDNode>(N)->getValue();
7064     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7065       return false;
7066   }
7067
7068   // If the offset is a constant, there may be other adds of constants that
7069   // can be folded with this one. We should do this to avoid having to keep
7070   // a copy of the original base pointer.
7071   SmallVector<SDNode *, 16> OtherUses;
7072   if (isa<ConstantSDNode>(Offset))
7073     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7074          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7075       SDNode *Use = *I;
7076       if (Use == Ptr.getNode())
7077         continue;
7078
7079       if (Use->isPredecessorOf(N))
7080         continue;
7081
7082       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7083         OtherUses.clear();
7084         break;
7085       }
7086
7087       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7088       if (Op1.getNode() == BasePtr.getNode())
7089         std::swap(Op0, Op1);
7090       assert(Op0.getNode() == BasePtr.getNode() &&
7091              "Use of ADD/SUB but not an operand");
7092
7093       if (!isa<ConstantSDNode>(Op1)) {
7094         OtherUses.clear();
7095         break;
7096       }
7097
7098       // FIXME: In some cases, we can be smarter about this.
7099       if (Op1.getValueType() != Offset.getValueType()) {
7100         OtherUses.clear();
7101         break;
7102       }
7103
7104       OtherUses.push_back(Use);
7105     }
7106
7107   if (Swapped)
7108     std::swap(BasePtr, Offset);
7109
7110   // Now check for #3 and #4.
7111   bool RealUse = false;
7112
7113   // Caches for hasPredecessorHelper
7114   SmallPtrSet<const SDNode *, 32> Visited;
7115   SmallVector<const SDNode *, 16> Worklist;
7116
7117   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7118          E = Ptr.getNode()->use_end(); I != E; ++I) {
7119     SDNode *Use = *I;
7120     if (Use == N)
7121       continue;
7122     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7123       return false;
7124
7125     // If Ptr may be folded in addressing mode of other use, then it's
7126     // not profitable to do this transformation.
7127     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7128       RealUse = true;
7129   }
7130
7131   if (!RealUse)
7132     return false;
7133
7134   SDValue Result;
7135   if (isLoad)
7136     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7137                                 BasePtr, Offset, AM);
7138   else
7139     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7140                                  BasePtr, Offset, AM);
7141   ++PreIndexedNodes;
7142   ++NodesCombined;
7143   DEBUG(dbgs() << "\nReplacing.4 ";
7144         N->dump(&DAG);
7145         dbgs() << "\nWith: ";
7146         Result.getNode()->dump(&DAG);
7147         dbgs() << '\n');
7148   WorkListRemover DeadNodes(*this);
7149   if (isLoad) {
7150     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7151     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7152   } else {
7153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7154   }
7155
7156   // Finally, since the node is now dead, remove it from the graph.
7157   DAG.DeleteNode(N);
7158
7159   if (Swapped)
7160     std::swap(BasePtr, Offset);
7161
7162   // Replace other uses of BasePtr that can be updated to use Ptr
7163   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7164     unsigned OffsetIdx = 1;
7165     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7166       OffsetIdx = 0;
7167     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7168            BasePtr.getNode() && "Expected BasePtr operand");
7169
7170     // We need to replace ptr0 in the following expression:
7171     //   x0 * offset0 + y0 * ptr0 = t0
7172     // knowing that
7173     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7174     // 
7175     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7176     // indexed load/store and the expresion that needs to be re-written.
7177     //
7178     // Therefore, we have:
7179     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7180
7181     ConstantSDNode *CN =
7182       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7183     int X0, X1, Y0, Y1;
7184     APInt Offset0 = CN->getAPIntValue();
7185     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7186
7187     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7188     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7189     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7190     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7191
7192     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7193
7194     APInt CNV = Offset0;
7195     if (X0 < 0) CNV = -CNV;
7196     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7197     else CNV = CNV - Offset1;
7198
7199     // We can now generate the new expression.
7200     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7201     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7202
7203     SDValue NewUse = DAG.getNode(Opcode,
7204                                  SDLoc(OtherUses[i]),
7205                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7206     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7207     removeFromWorkList(OtherUses[i]);
7208     DAG.DeleteNode(OtherUses[i]);
7209   }
7210
7211   // Replace the uses of Ptr with uses of the updated base value.
7212   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7213   removeFromWorkList(Ptr.getNode());
7214   DAG.DeleteNode(Ptr.getNode());
7215
7216   return true;
7217 }
7218
7219 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7220 /// add / sub of the base pointer node into a post-indexed load / store.
7221 /// The transformation folded the add / subtract into the new indexed
7222 /// load / store effectively and all of its uses are redirected to the
7223 /// new load / store.
7224 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7225   if (Level < AfterLegalizeDAG)
7226     return false;
7227
7228   bool isLoad = true;
7229   SDValue Ptr;
7230   EVT VT;
7231   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7232     if (LD->isIndexed())
7233       return false;
7234     VT = LD->getMemoryVT();
7235     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7236         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7237       return false;
7238     Ptr = LD->getBasePtr();
7239   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7240     if (ST->isIndexed())
7241       return false;
7242     VT = ST->getMemoryVT();
7243     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7244         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7245       return false;
7246     Ptr = ST->getBasePtr();
7247     isLoad = false;
7248   } else {
7249     return false;
7250   }
7251
7252   if (Ptr.getNode()->hasOneUse())
7253     return false;
7254
7255   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7256          E = Ptr.getNode()->use_end(); I != E; ++I) {
7257     SDNode *Op = *I;
7258     if (Op == N ||
7259         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7260       continue;
7261
7262     SDValue BasePtr;
7263     SDValue Offset;
7264     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7265     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7266       // Don't create a indexed load / store with zero offset.
7267       if (isa<ConstantSDNode>(Offset) &&
7268           cast<ConstantSDNode>(Offset)->isNullValue())
7269         continue;
7270
7271       // Try turning it into a post-indexed load / store except when
7272       // 1) All uses are load / store ops that use it as base ptr (and
7273       //    it may be folded as addressing mmode).
7274       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7275       //    nor a successor of N. Otherwise, if Op is folded that would
7276       //    create a cycle.
7277
7278       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7279         continue;
7280
7281       // Check for #1.
7282       bool TryNext = false;
7283       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7284              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7285         SDNode *Use = *II;
7286         if (Use == Ptr.getNode())
7287           continue;
7288
7289         // If all the uses are load / store addresses, then don't do the
7290         // transformation.
7291         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7292           bool RealUse = false;
7293           for (SDNode::use_iterator III = Use->use_begin(),
7294                  EEE = Use->use_end(); III != EEE; ++III) {
7295             SDNode *UseUse = *III;
7296             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 
7297               RealUse = true;
7298           }
7299
7300           if (!RealUse) {
7301             TryNext = true;
7302             break;
7303           }
7304         }
7305       }
7306
7307       if (TryNext)
7308         continue;
7309
7310       // Check for #2
7311       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7312         SDValue Result = isLoad
7313           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7314                                BasePtr, Offset, AM)
7315           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7316                                 BasePtr, Offset, AM);
7317         ++PostIndexedNodes;
7318         ++NodesCombined;
7319         DEBUG(dbgs() << "\nReplacing.5 ";
7320               N->dump(&DAG);
7321               dbgs() << "\nWith: ";
7322               Result.getNode()->dump(&DAG);
7323               dbgs() << '\n');
7324         WorkListRemover DeadNodes(*this);
7325         if (isLoad) {
7326           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7327           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7328         } else {
7329           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7330         }
7331
7332         // Finally, since the node is now dead, remove it from the graph.
7333         DAG.DeleteNode(N);
7334
7335         // Replace the uses of Use with uses of the updated base value.
7336         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7337                                       Result.getValue(isLoad ? 1 : 0));
7338         removeFromWorkList(Op);
7339         DAG.DeleteNode(Op);
7340         return true;
7341       }
7342     }
7343   }
7344
7345   return false;
7346 }
7347
7348 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7349   LoadSDNode *LD  = cast<LoadSDNode>(N);
7350   SDValue Chain = LD->getChain();
7351   SDValue Ptr   = LD->getBasePtr();
7352
7353   // If load is not volatile and there are no uses of the loaded value (and
7354   // the updated indexed value in case of indexed loads), change uses of the
7355   // chain value into uses of the chain input (i.e. delete the dead load).
7356   if (!LD->isVolatile()) {
7357     if (N->getValueType(1) == MVT::Other) {
7358       // Unindexed loads.
7359       if (!N->hasAnyUseOfValue(0)) {
7360         // It's not safe to use the two value CombineTo variant here. e.g.
7361         // v1, chain2 = load chain1, loc
7362         // v2, chain3 = load chain2, loc
7363         // v3         = add v2, c
7364         // Now we replace use of chain2 with chain1.  This makes the second load
7365         // isomorphic to the one we are deleting, and thus makes this load live.
7366         DEBUG(dbgs() << "\nReplacing.6 ";
7367               N->dump(&DAG);
7368               dbgs() << "\nWith chain: ";
7369               Chain.getNode()->dump(&DAG);
7370               dbgs() << "\n");
7371         WorkListRemover DeadNodes(*this);
7372         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7373
7374         if (N->use_empty()) {
7375           removeFromWorkList(N);
7376           DAG.DeleteNode(N);
7377         }
7378
7379         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7380       }
7381     } else {
7382       // Indexed loads.
7383       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7384       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7385         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7386         DEBUG(dbgs() << "\nReplacing.7 ";
7387               N->dump(&DAG);
7388               dbgs() << "\nWith: ";
7389               Undef.getNode()->dump(&DAG);
7390               dbgs() << " and 2 other values\n");
7391         WorkListRemover DeadNodes(*this);
7392         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7393         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7394                                       DAG.getUNDEF(N->getValueType(1)));
7395         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7396         removeFromWorkList(N);
7397         DAG.DeleteNode(N);
7398         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7399       }
7400     }
7401   }
7402
7403   // If this load is directly stored, replace the load value with the stored
7404   // value.
7405   // TODO: Handle store large -> read small portion.
7406   // TODO: Handle TRUNCSTORE/LOADEXT
7407   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7408     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7409       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7410       if (PrevST->getBasePtr() == Ptr &&
7411           PrevST->getValue().getValueType() == N->getValueType(0))
7412       return CombineTo(N, Chain.getOperand(1), Chain);
7413     }
7414   }
7415
7416   // Try to infer better alignment information than the load already has.
7417   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7418     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7419       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7420         SDValue NewLoad =
7421                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7422                               LD->getValueType(0),
7423                               Chain, Ptr, LD->getPointerInfo(),
7424                               LD->getMemoryVT(),
7425                               LD->isVolatile(), LD->isNonTemporal(), Align);
7426         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7427       }
7428     }
7429   }
7430
7431   if (CombinerAA) {
7432     // Walk up chain skipping non-aliasing memory nodes.
7433     SDValue BetterChain = FindBetterChain(N, Chain);
7434
7435     // If there is a better chain.
7436     if (Chain != BetterChain) {
7437       SDValue ReplLoad;
7438
7439       // Replace the chain to void dependency.
7440       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7441         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7442                                BetterChain, Ptr, LD->getPointerInfo(),
7443                                LD->isVolatile(), LD->isNonTemporal(),
7444                                LD->isInvariant(), LD->getAlignment());
7445       } else {
7446         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7447                                   LD->getValueType(0),
7448                                   BetterChain, Ptr, LD->getPointerInfo(),
7449                                   LD->getMemoryVT(),
7450                                   LD->isVolatile(),
7451                                   LD->isNonTemporal(),
7452                                   LD->getAlignment());
7453       }
7454
7455       // Create token factor to keep old chain connected.
7456       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7457                                   MVT::Other, Chain, ReplLoad.getValue(1));
7458
7459       // Make sure the new and old chains are cleaned up.
7460       AddToWorkList(Token.getNode());
7461
7462       // Replace uses with load result and token factor. Don't add users
7463       // to work list.
7464       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7465     }
7466   }
7467
7468   // Try transforming N to an indexed load.
7469   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7470     return SDValue(N, 0);
7471
7472   return SDValue();
7473 }
7474
7475 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7476 /// load is having specific bytes cleared out.  If so, return the byte size
7477 /// being masked out and the shift amount.
7478 static std::pair<unsigned, unsigned>
7479 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7480   std::pair<unsigned, unsigned> Result(0, 0);
7481
7482   // Check for the structure we're looking for.
7483   if (V->getOpcode() != ISD::AND ||
7484       !isa<ConstantSDNode>(V->getOperand(1)) ||
7485       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7486     return Result;
7487
7488   // Check the chain and pointer.
7489   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7490   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7491
7492   // The store should be chained directly to the load or be an operand of a
7493   // tokenfactor.
7494   if (LD == Chain.getNode())
7495     ; // ok.
7496   else if (Chain->getOpcode() != ISD::TokenFactor)
7497     return Result; // Fail.
7498   else {
7499     bool isOk = false;
7500     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7501       if (Chain->getOperand(i).getNode() == LD) {
7502         isOk = true;
7503         break;
7504       }
7505     if (!isOk) return Result;
7506   }
7507
7508   // This only handles simple types.
7509   if (V.getValueType() != MVT::i16 &&
7510       V.getValueType() != MVT::i32 &&
7511       V.getValueType() != MVT::i64)
7512     return Result;
7513
7514   // Check the constant mask.  Invert it so that the bits being masked out are
7515   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7516   // follow the sign bit for uniformity.
7517   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7518   unsigned NotMaskLZ = countLeadingZeros(NotMask);
7519   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7520   unsigned NotMaskTZ = countTrailingZeros(NotMask);
7521   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7522   if (NotMaskLZ == 64) return Result;  // All zero mask.
7523
7524   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7525   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7526     return Result;
7527
7528   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7529   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7530     NotMaskLZ -= 64-V.getValueSizeInBits();
7531
7532   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7533   switch (MaskedBytes) {
7534   case 1:
7535   case 2:
7536   case 4: break;
7537   default: return Result; // All one mask, or 5-byte mask.
7538   }
7539
7540   // Verify that the first bit starts at a multiple of mask so that the access
7541   // is aligned the same as the access width.
7542   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7543
7544   Result.first = MaskedBytes;
7545   Result.second = NotMaskTZ/8;
7546   return Result;
7547 }
7548
7549
7550 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7551 /// provides a value as specified by MaskInfo.  If so, replace the specified
7552 /// store with a narrower store of truncated IVal.
7553 static SDNode *
7554 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7555                                 SDValue IVal, StoreSDNode *St,
7556                                 DAGCombiner *DC) {
7557   unsigned NumBytes = MaskInfo.first;
7558   unsigned ByteShift = MaskInfo.second;
7559   SelectionDAG &DAG = DC->getDAG();
7560
7561   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7562   // that uses this.  If not, this is not a replacement.
7563   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7564                                   ByteShift*8, (ByteShift+NumBytes)*8);
7565   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7566
7567   // Check that it is legal on the target to do this.  It is legal if the new
7568   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7569   // legalization.
7570   MVT VT = MVT::getIntegerVT(NumBytes*8);
7571   if (!DC->isTypeLegal(VT))
7572     return 0;
7573
7574   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7575   // shifted by ByteShift and truncated down to NumBytes.
7576   if (ByteShift)
7577     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7578                        DAG.getConstant(ByteShift*8,
7579                                     DC->getShiftAmountTy(IVal.getValueType())));
7580
7581   // Figure out the offset for the store and the alignment of the access.
7582   unsigned StOffset;
7583   unsigned NewAlign = St->getAlignment();
7584
7585   if (DAG.getTargetLoweringInfo().isLittleEndian())
7586     StOffset = ByteShift;
7587   else
7588     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7589
7590   SDValue Ptr = St->getBasePtr();
7591   if (StOffset) {
7592     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7593                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7594     NewAlign = MinAlign(NewAlign, StOffset);
7595   }
7596
7597   // Truncate down to the new size.
7598   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7599
7600   ++OpsNarrowed;
7601   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7602                       St->getPointerInfo().getWithOffset(StOffset),
7603                       false, false, NewAlign).getNode();
7604 }
7605
7606
7607 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7608 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7609 /// of the loaded bits, try narrowing the load and store if it would end up
7610 /// being a win for performance or code size.
7611 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7612   StoreSDNode *ST  = cast<StoreSDNode>(N);
7613   if (ST->isVolatile())
7614     return SDValue();
7615
7616   SDValue Chain = ST->getChain();
7617   SDValue Value = ST->getValue();
7618   SDValue Ptr   = ST->getBasePtr();
7619   EVT VT = Value.getValueType();
7620
7621   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7622     return SDValue();
7623
7624   unsigned Opc = Value.getOpcode();
7625
7626   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7627   // is a byte mask indicating a consecutive number of bytes, check to see if
7628   // Y is known to provide just those bytes.  If so, we try to replace the
7629   // load + replace + store sequence with a single (narrower) store, which makes
7630   // the load dead.
7631   if (Opc == ISD::OR) {
7632     std::pair<unsigned, unsigned> MaskedLoad;
7633     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7634     if (MaskedLoad.first)
7635       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7636                                                   Value.getOperand(1), ST,this))
7637         return SDValue(NewST, 0);
7638
7639     // Or is commutative, so try swapping X and Y.
7640     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7641     if (MaskedLoad.first)
7642       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7643                                                   Value.getOperand(0), ST,this))
7644         return SDValue(NewST, 0);
7645   }
7646
7647   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7648       Value.getOperand(1).getOpcode() != ISD::Constant)
7649     return SDValue();
7650
7651   SDValue N0 = Value.getOperand(0);
7652   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7653       Chain == SDValue(N0.getNode(), 1)) {
7654     LoadSDNode *LD = cast<LoadSDNode>(N0);
7655     if (LD->getBasePtr() != Ptr ||
7656         LD->getPointerInfo().getAddrSpace() !=
7657         ST->getPointerInfo().getAddrSpace())
7658       return SDValue();
7659
7660     // Find the type to narrow it the load / op / store to.
7661     SDValue N1 = Value.getOperand(1);
7662     unsigned BitWidth = N1.getValueSizeInBits();
7663     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7664     if (Opc == ISD::AND)
7665       Imm ^= APInt::getAllOnesValue(BitWidth);
7666     if (Imm == 0 || Imm.isAllOnesValue())
7667       return SDValue();
7668     unsigned ShAmt = Imm.countTrailingZeros();
7669     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7670     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7671     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7672     while (NewBW < BitWidth &&
7673            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7674              TLI.isNarrowingProfitable(VT, NewVT))) {
7675       NewBW = NextPowerOf2(NewBW);
7676       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7677     }
7678     if (NewBW >= BitWidth)
7679       return SDValue();
7680
7681     // If the lsb changed does not start at the type bitwidth boundary,
7682     // start at the previous one.
7683     if (ShAmt % NewBW)
7684       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7685     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7686                                    std::min(BitWidth, ShAmt + NewBW));
7687     if ((Imm & Mask) == Imm) {
7688       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7689       if (Opc == ISD::AND)
7690         NewImm ^= APInt::getAllOnesValue(NewBW);
7691       uint64_t PtrOff = ShAmt / 8;
7692       // For big endian targets, we need to adjust the offset to the pointer to
7693       // load the correct bytes.
7694       if (TLI.isBigEndian())
7695         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7696
7697       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7698       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7699       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7700         return SDValue();
7701
7702       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7703                                    Ptr.getValueType(), Ptr,
7704                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7705       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7706                                   LD->getChain(), NewPtr,
7707                                   LD->getPointerInfo().getWithOffset(PtrOff),
7708                                   LD->isVolatile(), LD->isNonTemporal(),
7709                                   LD->isInvariant(), NewAlign);
7710       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7711                                    DAG.getConstant(NewImm, NewVT));
7712       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7713                                    NewVal, NewPtr,
7714                                    ST->getPointerInfo().getWithOffset(PtrOff),
7715                                    false, false, NewAlign);
7716
7717       AddToWorkList(NewPtr.getNode());
7718       AddToWorkList(NewLD.getNode());
7719       AddToWorkList(NewVal.getNode());
7720       WorkListRemover DeadNodes(*this);
7721       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7722       ++OpsNarrowed;
7723       return NewST;
7724     }
7725   }
7726
7727   return SDValue();
7728 }
7729
7730 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7731 /// if the load value isn't used by any other operations, then consider
7732 /// transforming the pair to integer load / store operations if the target
7733 /// deems the transformation profitable.
7734 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7735   StoreSDNode *ST  = cast<StoreSDNode>(N);
7736   SDValue Chain = ST->getChain();
7737   SDValue Value = ST->getValue();
7738   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7739       Value.hasOneUse() &&
7740       Chain == SDValue(Value.getNode(), 1)) {
7741     LoadSDNode *LD = cast<LoadSDNode>(Value);
7742     EVT VT = LD->getMemoryVT();
7743     if (!VT.isFloatingPoint() ||
7744         VT != ST->getMemoryVT() ||
7745         LD->isNonTemporal() ||
7746         ST->isNonTemporal() ||
7747         LD->getPointerInfo().getAddrSpace() != 0 ||
7748         ST->getPointerInfo().getAddrSpace() != 0)
7749       return SDValue();
7750
7751     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7752     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7753         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7754         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7755         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7756       return SDValue();
7757
7758     unsigned LDAlign = LD->getAlignment();
7759     unsigned STAlign = ST->getAlignment();
7760     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7761     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7762     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7763       return SDValue();
7764
7765     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7766                                 LD->getChain(), LD->getBasePtr(),
7767                                 LD->getPointerInfo(),
7768                                 false, false, false, LDAlign);
7769
7770     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7771                                  NewLD, ST->getBasePtr(),
7772                                  ST->getPointerInfo(),
7773                                  false, false, STAlign);
7774
7775     AddToWorkList(NewLD.getNode());
7776     AddToWorkList(NewST.getNode());
7777     WorkListRemover DeadNodes(*this);
7778     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7779     ++LdStFP2Int;
7780     return NewST;
7781   }
7782
7783   return SDValue();
7784 }
7785
7786 /// Helper struct to parse and store a memory address as base + index + offset.
7787 /// We ignore sign extensions when it is safe to do so.
7788 /// The following two expressions are not equivalent. To differentiate we need
7789 /// to store whether there was a sign extension involved in the index
7790 /// computation.
7791 ///  (load (i64 add (i64 copyfromreg %c)
7792 ///                 (i64 signextend (add (i8 load %index)
7793 ///                                      (i8 1))))
7794 /// vs
7795 ///
7796 /// (load (i64 add (i64 copyfromreg %c)
7797 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7798 ///                                         (i32 1)))))
7799 struct BaseIndexOffset {
7800   SDValue Base;
7801   SDValue Index;
7802   int64_t Offset;
7803   bool IsIndexSignExt;
7804
7805   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7806
7807   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7808                   bool IsIndexSignExt) :
7809     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7810
7811   bool equalBaseIndex(const BaseIndexOffset &Other) {
7812     return Other.Base == Base && Other.Index == Index &&
7813       Other.IsIndexSignExt == IsIndexSignExt;
7814   }
7815
7816   /// Parses tree in Ptr for base, index, offset addresses.
7817   static BaseIndexOffset match(SDValue Ptr) {
7818     bool IsIndexSignExt = false;
7819
7820     // Just Base or possibly anything else.
7821     if (Ptr->getOpcode() != ISD::ADD)
7822       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7823
7824     // Base + offset.
7825     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7826       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7827       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7828                               IsIndexSignExt);
7829     }
7830
7831     // Look at Base + Index + Offset cases.
7832     SDValue Base = Ptr->getOperand(0);
7833     SDValue IndexOffset = Ptr->getOperand(1);
7834
7835     // Skip signextends.
7836     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7837       IndexOffset = IndexOffset->getOperand(0);
7838       IsIndexSignExt = true;
7839     }
7840
7841     // Either the case of Base + Index (no offset) or something else.
7842     if (IndexOffset->getOpcode() != ISD::ADD)
7843       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7844
7845     // Now we have the case of Base + Index + offset.
7846     SDValue Index = IndexOffset->getOperand(0);
7847     SDValue Offset = IndexOffset->getOperand(1);
7848
7849     if (!isa<ConstantSDNode>(Offset))
7850       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7851
7852     // Ignore signextends.
7853     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7854       Index = Index->getOperand(0);
7855       IsIndexSignExt = true;
7856     } else IsIndexSignExt = false;
7857
7858     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7859     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7860   }
7861 };
7862
7863 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7864 /// is located in a sequence of memory operations connected by a chain.
7865 struct MemOpLink {
7866   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7867     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7868   // Ptr to the mem node.
7869   LSBaseSDNode *MemNode;
7870   // Offset from the base ptr.
7871   int64_t OffsetFromBase;
7872   // What is the sequence number of this mem node.
7873   // Lowest mem operand in the DAG starts at zero.
7874   unsigned SequenceNum;
7875 };
7876
7877 /// Sorts store nodes in a link according to their offset from a shared
7878 // base ptr.
7879 struct ConsecutiveMemoryChainSorter {
7880   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7881     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7882   }
7883 };
7884
7885 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7886   EVT MemVT = St->getMemoryVT();
7887   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7888   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7889     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7890
7891   // Don't merge vectors into wider inputs.
7892   if (MemVT.isVector() || !MemVT.isSimple())
7893     return false;
7894
7895   // Perform an early exit check. Do not bother looking at stored values that
7896   // are not constants or loads.
7897   SDValue StoredVal = St->getValue();
7898   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7899   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7900       !IsLoadSrc)
7901     return false;
7902
7903   // Only look at ends of store sequences.
7904   SDValue Chain = SDValue(St, 1);
7905   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7906     return false;
7907
7908   // This holds the base pointer, index, and the offset in bytes from the base
7909   // pointer.
7910   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7911
7912   // We must have a base and an offset.
7913   if (!BasePtr.Base.getNode())
7914     return false;
7915
7916   // Do not handle stores to undef base pointers.
7917   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7918     return false;
7919
7920   // Save the LoadSDNodes that we find in the chain.
7921   // We need to make sure that these nodes do not interfere with
7922   // any of the store nodes.
7923   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7924
7925   // Save the StoreSDNodes that we find in the chain.
7926   SmallVector<MemOpLink, 8> StoreNodes;
7927
7928   // Walk up the chain and look for nodes with offsets from the same
7929   // base pointer. Stop when reaching an instruction with a different kind
7930   // or instruction which has a different base pointer.
7931   unsigned Seq = 0;
7932   StoreSDNode *Index = St;
7933   while (Index) {
7934     // If the chain has more than one use, then we can't reorder the mem ops.
7935     if (Index != St && !SDValue(Index, 1)->hasOneUse())
7936       break;
7937
7938     // Find the base pointer and offset for this memory node.
7939     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
7940
7941     // Check that the base pointer is the same as the original one.
7942     if (!Ptr.equalBaseIndex(BasePtr))
7943       break;
7944
7945     // Check that the alignment is the same.
7946     if (Index->getAlignment() != St->getAlignment())
7947       break;
7948
7949     // The memory operands must not be volatile.
7950     if (Index->isVolatile() || Index->isIndexed())
7951       break;
7952
7953     // No truncation.
7954     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7955       if (St->isTruncatingStore())
7956         break;
7957
7958     // The stored memory type must be the same.
7959     if (Index->getMemoryVT() != MemVT)
7960       break;
7961
7962     // We do not allow unaligned stores because we want to prevent overriding
7963     // stores.
7964     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
7965       break;
7966
7967     // We found a potential memory operand to merge.
7968     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
7969
7970     // Find the next memory operand in the chain. If the next operand in the
7971     // chain is a store then move up and continue the scan with the next
7972     // memory operand. If the next operand is a load save it and use alias
7973     // information to check if it interferes with anything.
7974     SDNode *NextInChain = Index->getChain().getNode();
7975     while (1) {
7976       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
7977         // We found a store node. Use it for the next iteration.
7978         Index = STn;
7979         break;
7980       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
7981         // Save the load node for later. Continue the scan.
7982         AliasLoadNodes.push_back(Ldn);
7983         NextInChain = Ldn->getChain().getNode();
7984         continue;
7985       } else {
7986         Index = NULL;
7987         break;
7988       }
7989     }
7990   }
7991
7992   // Check if there is anything to merge.
7993   if (StoreNodes.size() < 2)
7994     return false;
7995
7996   // Sort the memory operands according to their distance from the base pointer.
7997   std::sort(StoreNodes.begin(), StoreNodes.end(),
7998             ConsecutiveMemoryChainSorter());
7999
8000   // Scan the memory operations on the chain and find the first non-consecutive
8001   // store memory address.
8002   unsigned LastConsecutiveStore = 0;
8003   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8004   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8005
8006     // Check that the addresses are consecutive starting from the second
8007     // element in the list of stores.
8008     if (i > 0) {
8009       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8010       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8011         break;
8012     }
8013
8014     bool Alias = false;
8015     // Check if this store interferes with any of the loads that we found.
8016     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8017       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8018         Alias = true;
8019         break;
8020       }
8021     // We found a load that alias with this store. Stop the sequence.
8022     if (Alias)
8023       break;
8024
8025     // Mark this node as useful.
8026     LastConsecutiveStore = i;
8027   }
8028
8029   // The node with the lowest store address.
8030   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8031
8032   // Store the constants into memory as one consecutive store.
8033   if (!IsLoadSrc) {
8034     unsigned LastLegalType = 0;
8035     unsigned LastLegalVectorType = 0;
8036     bool NonZero = false;
8037     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8038       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8039       SDValue StoredVal = St->getValue();
8040
8041       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8042         NonZero |= !C->isNullValue();
8043       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8044         NonZero |= !C->getConstantFPValue()->isNullValue();
8045       } else {
8046         // Non constant.
8047         break;
8048       }
8049
8050       // Find a legal type for the constant store.
8051       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8052       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8053       if (TLI.isTypeLegal(StoreTy))
8054         LastLegalType = i+1;
8055       // Or check whether a truncstore is legal.
8056       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8057                TargetLowering::TypePromoteInteger) {
8058         EVT LegalizedStoredValueTy =
8059           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8060         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8061           LastLegalType = i+1;
8062       }
8063
8064       // Find a legal type for the vector store.
8065       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8066       if (TLI.isTypeLegal(Ty))
8067         LastLegalVectorType = i + 1;
8068     }
8069
8070     // We only use vectors if the constant is known to be zero and the
8071     // function is not marked with the noimplicitfloat attribute.
8072     if (NonZero || NoVectors)
8073       LastLegalVectorType = 0;
8074
8075     // Check if we found a legal integer type to store.
8076     if (LastLegalType == 0 && LastLegalVectorType == 0)
8077       return false;
8078
8079     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8080     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8081
8082     // Make sure we have something to merge.
8083     if (NumElem < 2)
8084       return false;
8085
8086     unsigned EarliestNodeUsed = 0;
8087     for (unsigned i=0; i < NumElem; ++i) {
8088       // Find a chain for the new wide-store operand. Notice that some
8089       // of the store nodes that we found may not be selected for inclusion
8090       // in the wide store. The chain we use needs to be the chain of the
8091       // earliest store node which is *used* and replaced by the wide store.
8092       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8093         EarliestNodeUsed = i;
8094     }
8095
8096     // The earliest Node in the DAG.
8097     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8098     SDLoc DL(StoreNodes[0].MemNode);
8099
8100     SDValue StoredVal;
8101     if (UseVector) {
8102       // Find a legal type for the vector store.
8103       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8104       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8105       StoredVal = DAG.getConstant(0, Ty);
8106     } else {
8107       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8108       APInt StoreInt(StoreBW, 0);
8109
8110       // Construct a single integer constant which is made of the smaller
8111       // constant inputs.
8112       bool IsLE = TLI.isLittleEndian();
8113       for (unsigned i = 0; i < NumElem ; ++i) {
8114         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8115         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8116         SDValue Val = St->getValue();
8117         StoreInt<<=ElementSizeBytes*8;
8118         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8119           StoreInt|=C->getAPIntValue().zext(StoreBW);
8120         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8121           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8122         } else {
8123           assert(false && "Invalid constant element type");
8124         }
8125       }
8126
8127       // Create the new Load and Store operations.
8128       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8129       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8130     }
8131
8132     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8133                                     FirstInChain->getBasePtr(),
8134                                     FirstInChain->getPointerInfo(),
8135                                     false, false,
8136                                     FirstInChain->getAlignment());
8137
8138     // Replace the first store with the new store
8139     CombineTo(EarliestOp, NewStore);
8140     // Erase all other stores.
8141     for (unsigned i = 0; i < NumElem ; ++i) {
8142       if (StoreNodes[i].MemNode == EarliestOp)
8143         continue;
8144       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8145       // ReplaceAllUsesWith will replace all uses that existed when it was
8146       // called, but graph optimizations may cause new ones to appear. For
8147       // example, the case in pr14333 looks like
8148       //
8149       //  St's chain -> St -> another store -> X
8150       //
8151       // And the only difference from St to the other store is the chain.
8152       // When we change it's chain to be St's chain they become identical,
8153       // get CSEed and the net result is that X is now a use of St.
8154       // Since we know that St is redundant, just iterate.
8155       while (!St->use_empty())
8156         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8157       removeFromWorkList(St);
8158       DAG.DeleteNode(St);
8159     }
8160
8161     return true;
8162   }
8163
8164   // Below we handle the case of multiple consecutive stores that
8165   // come from multiple consecutive loads. We merge them into a single
8166   // wide load and a single wide store.
8167
8168   // Look for load nodes which are used by the stored values.
8169   SmallVector<MemOpLink, 8> LoadNodes;
8170
8171   // Find acceptable loads. Loads need to have the same chain (token factor),
8172   // must not be zext, volatile, indexed, and they must be consecutive.
8173   BaseIndexOffset LdBasePtr;
8174   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8175     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8176     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8177     if (!Ld) break;
8178
8179     // Loads must only have one use.
8180     if (!Ld->hasNUsesOfValue(1, 0))
8181       break;
8182
8183     // Check that the alignment is the same as the stores.
8184     if (Ld->getAlignment() != St->getAlignment())
8185       break;
8186
8187     // The memory operands must not be volatile.
8188     if (Ld->isVolatile() || Ld->isIndexed())
8189       break;
8190
8191     // We do not accept ext loads.
8192     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8193       break;
8194
8195     // The stored memory type must be the same.
8196     if (Ld->getMemoryVT() != MemVT)
8197       break;
8198
8199     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8200     // If this is not the first ptr that we check.
8201     if (LdBasePtr.Base.getNode()) {
8202       // The base ptr must be the same.
8203       if (!LdPtr.equalBaseIndex(LdBasePtr))
8204         break;
8205     } else {
8206       // Check that all other base pointers are the same as this one.
8207       LdBasePtr = LdPtr;
8208     }
8209
8210     // We found a potential memory operand to merge.
8211     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8212   }
8213
8214   if (LoadNodes.size() < 2)
8215     return false;
8216
8217   // Scan the memory operations on the chain and find the first non-consecutive
8218   // load memory address. These variables hold the index in the store node
8219   // array.
8220   unsigned LastConsecutiveLoad = 0;
8221   // This variable refers to the size and not index in the array.
8222   unsigned LastLegalVectorType = 0;
8223   unsigned LastLegalIntegerType = 0;
8224   StartAddress = LoadNodes[0].OffsetFromBase;
8225   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8226   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8227     // All loads much share the same chain.
8228     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8229       break;
8230
8231     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8232     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8233       break;
8234     LastConsecutiveLoad = i;
8235
8236     // Find a legal type for the vector store.
8237     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8238     if (TLI.isTypeLegal(StoreTy))
8239       LastLegalVectorType = i + 1;
8240
8241     // Find a legal type for the integer store.
8242     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8243     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8244     if (TLI.isTypeLegal(StoreTy))
8245       LastLegalIntegerType = i + 1;
8246     // Or check whether a truncstore and extload is legal.
8247     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8248              TargetLowering::TypePromoteInteger) {
8249       EVT LegalizedStoredValueTy =
8250         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8251       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8252           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8253           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8254           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8255         LastLegalIntegerType = i+1;
8256     }
8257   }
8258
8259   // Only use vector types if the vector type is larger than the integer type.
8260   // If they are the same, use integers.
8261   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8262   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8263
8264   // We add +1 here because the LastXXX variables refer to location while
8265   // the NumElem refers to array/index size.
8266   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8267   NumElem = std::min(LastLegalType, NumElem);
8268
8269   if (NumElem < 2)
8270     return false;
8271
8272   // The earliest Node in the DAG.
8273   unsigned EarliestNodeUsed = 0;
8274   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8275   for (unsigned i=1; i<NumElem; ++i) {
8276     // Find a chain for the new wide-store operand. Notice that some
8277     // of the store nodes that we found may not be selected for inclusion
8278     // in the wide store. The chain we use needs to be the chain of the
8279     // earliest store node which is *used* and replaced by the wide store.
8280     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8281       EarliestNodeUsed = i;
8282   }
8283
8284   // Find if it is better to use vectors or integers to load and store
8285   // to memory.
8286   EVT JointMemOpVT;
8287   if (UseVectorTy) {
8288     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8289   } else {
8290     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8291     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8292   }
8293
8294   SDLoc LoadDL(LoadNodes[0].MemNode);
8295   SDLoc StoreDL(StoreNodes[0].MemNode);
8296
8297   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8298   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8299                                 FirstLoad->getChain(),
8300                                 FirstLoad->getBasePtr(),
8301                                 FirstLoad->getPointerInfo(),
8302                                 false, false, false,
8303                                 FirstLoad->getAlignment());
8304
8305   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8306                                   FirstInChain->getBasePtr(),
8307                                   FirstInChain->getPointerInfo(), false, false,
8308                                   FirstInChain->getAlignment());
8309
8310   // Replace one of the loads with the new load.
8311   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8312   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8313                                 SDValue(NewLoad.getNode(), 1));
8314
8315   // Remove the rest of the load chains.
8316   for (unsigned i = 1; i < NumElem ; ++i) {
8317     // Replace all chain users of the old load nodes with the chain of the new
8318     // load node.
8319     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8320     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8321   }
8322
8323   // Replace the first store with the new store.
8324   CombineTo(EarliestOp, NewStore);
8325   // Erase all other stores.
8326   for (unsigned i = 0; i < NumElem ; ++i) {
8327     // Remove all Store nodes.
8328     if (StoreNodes[i].MemNode == EarliestOp)
8329       continue;
8330     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8331     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8332     removeFromWorkList(St);
8333     DAG.DeleteNode(St);
8334   }
8335
8336   return true;
8337 }
8338
8339 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8340   StoreSDNode *ST  = cast<StoreSDNode>(N);
8341   SDValue Chain = ST->getChain();
8342   SDValue Value = ST->getValue();
8343   SDValue Ptr   = ST->getBasePtr();
8344
8345   // If this is a store of a bit convert, store the input value if the
8346   // resultant store does not need a higher alignment than the original.
8347   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8348       ST->isUnindexed()) {
8349     unsigned OrigAlign = ST->getAlignment();
8350     EVT SVT = Value.getOperand(0).getValueType();
8351     unsigned Align = TLI.getDataLayout()->
8352       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8353     if (Align <= OrigAlign &&
8354         ((!LegalOperations && !ST->isVolatile()) ||
8355          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8356       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8357                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8358                           ST->isNonTemporal(), OrigAlign);
8359   }
8360
8361   // Turn 'store undef, Ptr' -> nothing.
8362   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8363     return Chain;
8364
8365   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8366   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8367     // NOTE: If the original store is volatile, this transform must not increase
8368     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8369     // processor operation but an i64 (which is not legal) requires two.  So the
8370     // transform should not be done in this case.
8371     if (Value.getOpcode() != ISD::TargetConstantFP) {
8372       SDValue Tmp;
8373       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
8374       default: llvm_unreachable("Unknown FP type");
8375       case MVT::f16:    // We don't do this for these yet.
8376       case MVT::f80:
8377       case MVT::f128:
8378       case MVT::ppcf128:
8379         break;
8380       case MVT::f32:
8381         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8382             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8383           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8384                               bitcastToAPInt().getZExtValue(), MVT::i32);
8385           return DAG.getStore(Chain, SDLoc(N), Tmp,
8386                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8387                               ST->isNonTemporal(), ST->getAlignment());
8388         }
8389         break;
8390       case MVT::f64:
8391         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8392              !ST->isVolatile()) ||
8393             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8394           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8395                                 getZExtValue(), MVT::i64);
8396           return DAG.getStore(Chain, SDLoc(N), Tmp,
8397                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8398                               ST->isNonTemporal(), ST->getAlignment());
8399         }
8400
8401         if (!ST->isVolatile() &&
8402             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8403           // Many FP stores are not made apparent until after legalize, e.g. for
8404           // argument passing.  Since this is so common, custom legalize the
8405           // 64-bit integer store into two 32-bit stores.
8406           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8407           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8408           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8409           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8410
8411           unsigned Alignment = ST->getAlignment();
8412           bool isVolatile = ST->isVolatile();
8413           bool isNonTemporal = ST->isNonTemporal();
8414
8415           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8416                                      Ptr, ST->getPointerInfo(),
8417                                      isVolatile, isNonTemporal,
8418                                      ST->getAlignment());
8419           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8420                             DAG.getConstant(4, Ptr.getValueType()));
8421           Alignment = MinAlign(Alignment, 4U);
8422           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8423                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8424                                      isVolatile, isNonTemporal,
8425                                      Alignment);
8426           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8427                              St0, St1);
8428         }
8429
8430         break;
8431       }
8432     }
8433   }
8434
8435   // Try to infer better alignment information than the store already has.
8436   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8437     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8438       if (Align > ST->getAlignment())
8439         return DAG.getTruncStore(Chain, SDLoc(N), Value,
8440                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8441                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8442     }
8443   }
8444
8445   // Try transforming a pair floating point load / store ops to integer
8446   // load / store ops.
8447   SDValue NewST = TransformFPLoadStorePair(N);
8448   if (NewST.getNode())
8449     return NewST;
8450
8451   if (CombinerAA) {
8452     // Walk up chain skipping non-aliasing memory nodes.
8453     SDValue BetterChain = FindBetterChain(N, Chain);
8454
8455     // If there is a better chain.
8456     if (Chain != BetterChain) {
8457       SDValue ReplStore;
8458
8459       // Replace the chain to avoid dependency.
8460       if (ST->isTruncatingStore()) {
8461         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8462                                       ST->getPointerInfo(),
8463                                       ST->getMemoryVT(), ST->isVolatile(),
8464                                       ST->isNonTemporal(), ST->getAlignment());
8465       } else {
8466         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8467                                  ST->getPointerInfo(),
8468                                  ST->isVolatile(), ST->isNonTemporal(),
8469                                  ST->getAlignment());
8470       }
8471
8472       // Create token to keep both nodes around.
8473       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8474                                   MVT::Other, Chain, ReplStore);
8475
8476       // Make sure the new and old chains are cleaned up.
8477       AddToWorkList(Token.getNode());
8478
8479       // Don't add users to work list.
8480       return CombineTo(N, Token, false);
8481     }
8482   }
8483
8484   // Try transforming N to an indexed store.
8485   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8486     return SDValue(N, 0);
8487
8488   // FIXME: is there such a thing as a truncating indexed store?
8489   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8490       Value.getValueType().isInteger()) {
8491     // See if we can simplify the input to this truncstore with knowledge that
8492     // only the low bits are being used.  For example:
8493     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8494     SDValue Shorter =
8495       GetDemandedBits(Value,
8496                       APInt::getLowBitsSet(
8497                         Value.getValueType().getScalarType().getSizeInBits(),
8498                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8499     AddToWorkList(Value.getNode());
8500     if (Shorter.getNode())
8501       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8502                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8503                                ST->isVolatile(), ST->isNonTemporal(),
8504                                ST->getAlignment());
8505
8506     // Otherwise, see if we can simplify the operation with
8507     // SimplifyDemandedBits, which only works if the value has a single use.
8508     if (SimplifyDemandedBits(Value,
8509                         APInt::getLowBitsSet(
8510                           Value.getValueType().getScalarType().getSizeInBits(),
8511                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8512       return SDValue(N, 0);
8513   }
8514
8515   // If this is a load followed by a store to the same location, then the store
8516   // is dead/noop.
8517   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8518     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8519         ST->isUnindexed() && !ST->isVolatile() &&
8520         // There can't be any side effects between the load and store, such as
8521         // a call or store.
8522         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8523       // The store is dead, remove it.
8524       return Chain;
8525     }
8526   }
8527
8528   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8529   // truncating store.  We can do this even if this is already a truncstore.
8530   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8531       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8532       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8533                             ST->getMemoryVT())) {
8534     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8535                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8536                              ST->isVolatile(), ST->isNonTemporal(),
8537                              ST->getAlignment());
8538   }
8539
8540   // Only perform this optimization before the types are legal, because we
8541   // don't want to perform this optimization on every DAGCombine invocation.
8542   if (!LegalTypes) {
8543     bool EverChanged = false;
8544
8545     do {
8546       // There can be multiple store sequences on the same chain.
8547       // Keep trying to merge store sequences until we are unable to do so
8548       // or until we merge the last store on the chain.
8549       bool Changed = MergeConsecutiveStores(ST);
8550       EverChanged |= Changed;
8551       if (!Changed) break;
8552     } while (ST->getOpcode() != ISD::DELETED_NODE);
8553
8554     if (EverChanged)
8555       return SDValue(N, 0);
8556   }
8557
8558   return ReduceLoadOpStoreWidth(N);
8559 }
8560
8561 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8562   SDValue InVec = N->getOperand(0);
8563   SDValue InVal = N->getOperand(1);
8564   SDValue EltNo = N->getOperand(2);
8565   SDLoc dl(N);
8566
8567   // If the inserted element is an UNDEF, just use the input vector.
8568   if (InVal.getOpcode() == ISD::UNDEF)
8569     return InVec;
8570
8571   EVT VT = InVec.getValueType();
8572
8573   // If we can't generate a legal BUILD_VECTOR, exit
8574   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8575     return SDValue();
8576
8577   // Check that we know which element is being inserted
8578   if (!isa<ConstantSDNode>(EltNo))
8579     return SDValue();
8580   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8581
8582   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8583   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8584   // vector elements.
8585   SmallVector<SDValue, 8> Ops;
8586   if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8587     Ops.append(InVec.getNode()->op_begin(),
8588                InVec.getNode()->op_end());
8589   } else if (InVec.getOpcode() == ISD::UNDEF) {
8590     unsigned NElts = VT.getVectorNumElements();
8591     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8592   } else {
8593     return SDValue();
8594   }
8595
8596   // Insert the element
8597   if (Elt < Ops.size()) {
8598     // All the operands of BUILD_VECTOR must have the same type;
8599     // we enforce that here.
8600     EVT OpVT = Ops[0].getValueType();
8601     if (InVal.getValueType() != OpVT)
8602       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8603                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8604                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8605     Ops[Elt] = InVal;
8606   }
8607
8608   // Return the new vector
8609   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8610                      VT, &Ops[0], Ops.size());
8611 }
8612
8613 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8614   // (vextract (scalar_to_vector val, 0) -> val
8615   SDValue InVec = N->getOperand(0);
8616   EVT VT = InVec.getValueType();
8617   EVT NVT = N->getValueType(0);
8618
8619   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8620     // Check if the result type doesn't match the inserted element type. A
8621     // SCALAR_TO_VECTOR may truncate the inserted element and the
8622     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8623     SDValue InOp = InVec.getOperand(0);
8624     if (InOp.getValueType() != NVT) {
8625       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8626       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8627     }
8628     return InOp;
8629   }
8630
8631   SDValue EltNo = N->getOperand(1);
8632   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8633
8634   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8635   // We only perform this optimization before the op legalization phase because
8636   // we may introduce new vector instructions which are not backed by TD
8637   // patterns. For example on AVX, extracting elements from a wide vector
8638   // without using extract_subvector.
8639   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8640       && ConstEltNo && !LegalOperations) {
8641     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8642     int NumElem = VT.getVectorNumElements();
8643     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8644     // Find the new index to extract from.
8645     int OrigElt = SVOp->getMaskElt(Elt);
8646
8647     // Extracting an undef index is undef.
8648     if (OrigElt == -1)
8649       return DAG.getUNDEF(NVT);
8650
8651     // Select the right vector half to extract from.
8652     if (OrigElt < NumElem) {
8653       InVec = InVec->getOperand(0);
8654     } else {
8655       InVec = InVec->getOperand(1);
8656       OrigElt -= NumElem;
8657     }
8658
8659     EVT IndexTy = N->getOperand(1).getValueType();
8660     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8661                        InVec, DAG.getConstant(OrigElt, IndexTy));
8662   }
8663
8664   // Perform only after legalization to ensure build_vector / vector_shuffle
8665   // optimizations have already been done.
8666   if (!LegalOperations) return SDValue();
8667
8668   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8669   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8670   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8671
8672   if (ConstEltNo) {
8673     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8674     bool NewLoad = false;
8675     bool BCNumEltsChanged = false;
8676     EVT ExtVT = VT.getVectorElementType();
8677     EVT LVT = ExtVT;
8678
8679     // If the result of load has to be truncated, then it's not necessarily
8680     // profitable.
8681     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8682       return SDValue();
8683
8684     if (InVec.getOpcode() == ISD::BITCAST) {
8685       // Don't duplicate a load with other uses.
8686       if (!InVec.hasOneUse())
8687         return SDValue();
8688
8689       EVT BCVT = InVec.getOperand(0).getValueType();
8690       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8691         return SDValue();
8692       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8693         BCNumEltsChanged = true;
8694       InVec = InVec.getOperand(0);
8695       ExtVT = BCVT.getVectorElementType();
8696       NewLoad = true;
8697     }
8698
8699     LoadSDNode *LN0 = NULL;
8700     const ShuffleVectorSDNode *SVN = NULL;
8701     if (ISD::isNormalLoad(InVec.getNode())) {
8702       LN0 = cast<LoadSDNode>(InVec);
8703     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8704                InVec.getOperand(0).getValueType() == ExtVT &&
8705                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8706       // Don't duplicate a load with other uses.
8707       if (!InVec.hasOneUse())
8708         return SDValue();
8709
8710       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8711     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8712       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8713       // =>
8714       // (load $addr+1*size)
8715
8716       // Don't duplicate a load with other uses.
8717       if (!InVec.hasOneUse())
8718         return SDValue();
8719
8720       // If the bit convert changed the number of elements, it is unsafe
8721       // to examine the mask.
8722       if (BCNumEltsChanged)
8723         return SDValue();
8724
8725       // Select the input vector, guarding against out of range extract vector.
8726       unsigned NumElems = VT.getVectorNumElements();
8727       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8728       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8729
8730       if (InVec.getOpcode() == ISD::BITCAST) {
8731         // Don't duplicate a load with other uses.
8732         if (!InVec.hasOneUse())
8733           return SDValue();
8734
8735         InVec = InVec.getOperand(0);
8736       }
8737       if (ISD::isNormalLoad(InVec.getNode())) {
8738         LN0 = cast<LoadSDNode>(InVec);
8739         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8740       }
8741     }
8742
8743     // Make sure we found a non-volatile load and the extractelement is
8744     // the only use.
8745     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8746       return SDValue();
8747
8748     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8749     if (Elt == -1)
8750       return DAG.getUNDEF(LVT);
8751
8752     unsigned Align = LN0->getAlignment();
8753     if (NewLoad) {
8754       // Check the resultant load doesn't need a higher alignment than the
8755       // original load.
8756       unsigned NewAlign =
8757         TLI.getDataLayout()
8758             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8759
8760       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8761         return SDValue();
8762
8763       Align = NewAlign;
8764     }
8765
8766     SDValue NewPtr = LN0->getBasePtr();
8767     unsigned PtrOff = 0;
8768
8769     if (Elt) {
8770       PtrOff = LVT.getSizeInBits() * Elt / 8;
8771       EVT PtrType = NewPtr.getValueType();
8772       if (TLI.isBigEndian())
8773         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8774       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8775                            DAG.getConstant(PtrOff, PtrType));
8776     }
8777
8778     // The replacement we need to do here is a little tricky: we need to
8779     // replace an extractelement of a load with a load.
8780     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8781     // Note that this replacement assumes that the extractvalue is the only
8782     // use of the load; that's okay because we don't want to perform this
8783     // transformation in other cases anyway.
8784     SDValue Load;
8785     SDValue Chain;
8786     if (NVT.bitsGT(LVT)) {
8787       // If the result type of vextract is wider than the load, then issue an
8788       // extending load instead.
8789       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8790         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8791       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8792                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8793                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8794       Chain = Load.getValue(1);
8795     } else {
8796       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8797                          LN0->getPointerInfo().getWithOffset(PtrOff),
8798                          LN0->isVolatile(), LN0->isNonTemporal(), 
8799                          LN0->isInvariant(), Align);
8800       Chain = Load.getValue(1);
8801       if (NVT.bitsLT(LVT))
8802         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8803       else
8804         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8805     }
8806     WorkListRemover DeadNodes(*this);
8807     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8808     SDValue To[] = { Load, Chain };
8809     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8810     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8811     // worklist explicitly as well.
8812     AddToWorkList(Load.getNode());
8813     AddUsersToWorkList(Load.getNode()); // Add users too
8814     // Make sure to revisit this node to clean it up; it will usually be dead.
8815     AddToWorkList(N);
8816     return SDValue(N, 0);
8817   }
8818
8819   return SDValue();
8820 }
8821
8822 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8823 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8824   // We perform this optimization post type-legalization because
8825   // the type-legalizer often scalarizes integer-promoted vectors.
8826   // Performing this optimization before may create bit-casts which
8827   // will be type-legalized to complex code sequences.
8828   // We perform this optimization only before the operation legalizer because we
8829   // may introduce illegal operations.
8830   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8831     return SDValue();
8832
8833   unsigned NumInScalars = N->getNumOperands();
8834   SDLoc dl(N);
8835   EVT VT = N->getValueType(0);
8836
8837   // Check to see if this is a BUILD_VECTOR of a bunch of values
8838   // which come from any_extend or zero_extend nodes. If so, we can create
8839   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8840   // optimizations. We do not handle sign-extend because we can't fill the sign
8841   // using shuffles.
8842   EVT SourceType = MVT::Other;
8843   bool AllAnyExt = true;
8844
8845   for (unsigned i = 0; i != NumInScalars; ++i) {
8846     SDValue In = N->getOperand(i);
8847     // Ignore undef inputs.
8848     if (In.getOpcode() == ISD::UNDEF) continue;
8849
8850     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8851     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8852
8853     // Abort if the element is not an extension.
8854     if (!ZeroExt && !AnyExt) {
8855       SourceType = MVT::Other;
8856       break;
8857     }
8858
8859     // The input is a ZeroExt or AnyExt. Check the original type.
8860     EVT InTy = In.getOperand(0).getValueType();
8861
8862     // Check that all of the widened source types are the same.
8863     if (SourceType == MVT::Other)
8864       // First time.
8865       SourceType = InTy;
8866     else if (InTy != SourceType) {
8867       // Multiple income types. Abort.
8868       SourceType = MVT::Other;
8869       break;
8870     }
8871
8872     // Check if all of the extends are ANY_EXTENDs.
8873     AllAnyExt &= AnyExt;
8874   }
8875
8876   // In order to have valid types, all of the inputs must be extended from the
8877   // same source type and all of the inputs must be any or zero extend.
8878   // Scalar sizes must be a power of two.
8879   EVT OutScalarTy = VT.getScalarType();
8880   bool ValidTypes = SourceType != MVT::Other &&
8881                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8882                  isPowerOf2_32(SourceType.getSizeInBits());
8883
8884   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8885   // turn into a single shuffle instruction.
8886   if (!ValidTypes)
8887     return SDValue();
8888
8889   bool isLE = TLI.isLittleEndian();
8890   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8891   assert(ElemRatio > 1 && "Invalid element size ratio");
8892   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8893                                DAG.getConstant(0, SourceType);
8894
8895   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8896   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8897
8898   // Populate the new build_vector
8899   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8900     SDValue Cast = N->getOperand(i);
8901     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8902             Cast.getOpcode() == ISD::ZERO_EXTEND ||
8903             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8904     SDValue In;
8905     if (Cast.getOpcode() == ISD::UNDEF)
8906       In = DAG.getUNDEF(SourceType);
8907     else
8908       In = Cast->getOperand(0);
8909     unsigned Index = isLE ? (i * ElemRatio) :
8910                             (i * ElemRatio + (ElemRatio - 1));
8911
8912     assert(Index < Ops.size() && "Invalid index");
8913     Ops[Index] = In;
8914   }
8915
8916   // The type of the new BUILD_VECTOR node.
8917   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8918   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8919          "Invalid vector size");
8920   // Check if the new vector type is legal.
8921   if (!isTypeLegal(VecVT)) return SDValue();
8922
8923   // Make the new BUILD_VECTOR.
8924   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8925
8926   // The new BUILD_VECTOR node has the potential to be further optimized.
8927   AddToWorkList(BV.getNode());
8928   // Bitcast to the desired type.
8929   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8930 }
8931
8932 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8933   EVT VT = N->getValueType(0);
8934
8935   unsigned NumInScalars = N->getNumOperands();
8936   SDLoc dl(N);
8937
8938   EVT SrcVT = MVT::Other;
8939   unsigned Opcode = ISD::DELETED_NODE;
8940   unsigned NumDefs = 0;
8941
8942   for (unsigned i = 0; i != NumInScalars; ++i) {
8943     SDValue In = N->getOperand(i);
8944     unsigned Opc = In.getOpcode();
8945
8946     if (Opc == ISD::UNDEF)
8947       continue;
8948
8949     // If all scalar values are floats and converted from integers.
8950     if (Opcode == ISD::DELETED_NODE &&
8951         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8952       Opcode = Opc;
8953     }
8954
8955     if (Opc != Opcode)
8956       return SDValue();
8957
8958     EVT InVT = In.getOperand(0).getValueType();
8959
8960     // If all scalar values are typed differently, bail out. It's chosen to
8961     // simplify BUILD_VECTOR of integer types.
8962     if (SrcVT == MVT::Other)
8963       SrcVT = InVT;
8964     if (SrcVT != InVT)
8965       return SDValue();
8966     NumDefs++;
8967   }
8968
8969   // If the vector has just one element defined, it's not worth to fold it into
8970   // a vectorized one.
8971   if (NumDefs < 2)
8972     return SDValue();
8973
8974   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
8975          && "Should only handle conversion from integer to float.");
8976   assert(SrcVT != MVT::Other && "Cannot determine source type!");
8977
8978   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
8979
8980   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
8981     return SDValue();
8982
8983   SmallVector<SDValue, 8> Opnds;
8984   for (unsigned i = 0; i != NumInScalars; ++i) {
8985     SDValue In = N->getOperand(i);
8986
8987     if (In.getOpcode() == ISD::UNDEF)
8988       Opnds.push_back(DAG.getUNDEF(SrcVT));
8989     else
8990       Opnds.push_back(In.getOperand(0));
8991   }
8992   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
8993                            &Opnds[0], Opnds.size());
8994   AddToWorkList(BV.getNode());
8995
8996   return DAG.getNode(Opcode, dl, VT, BV);
8997 }
8998
8999 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9000   unsigned NumInScalars = N->getNumOperands();
9001   SDLoc dl(N);
9002   EVT VT = N->getValueType(0);
9003
9004   // A vector built entirely of undefs is undef.
9005   if (ISD::allOperandsUndef(N))
9006     return DAG.getUNDEF(VT);
9007
9008   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9009   if (V.getNode())
9010     return V;
9011
9012   V = reduceBuildVecConvertToConvertBuildVec(N);
9013   if (V.getNode())
9014     return V;
9015
9016   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9017   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9018   // at most two distinct vectors, turn this into a shuffle node.
9019
9020   // May only combine to shuffle after legalize if shuffle is legal.
9021   if (LegalOperations &&
9022       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9023     return SDValue();
9024
9025   SDValue VecIn1, VecIn2;
9026   for (unsigned i = 0; i != NumInScalars; ++i) {
9027     // Ignore undef inputs.
9028     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9029
9030     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9031     // constant index, bail out.
9032     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9033         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9034       VecIn1 = VecIn2 = SDValue(0, 0);
9035       break;
9036     }
9037
9038     // We allow up to two distinct input vectors.
9039     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9040     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9041       continue;
9042
9043     if (VecIn1.getNode() == 0) {
9044       VecIn1 = ExtractedFromVec;
9045     } else if (VecIn2.getNode() == 0) {
9046       VecIn2 = ExtractedFromVec;
9047     } else {
9048       // Too many inputs.
9049       VecIn1 = VecIn2 = SDValue(0, 0);
9050       break;
9051     }
9052   }
9053
9054     // If everything is good, we can make a shuffle operation.
9055   if (VecIn1.getNode()) {
9056     SmallVector<int, 8> Mask;
9057     for (unsigned i = 0; i != NumInScalars; ++i) {
9058       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9059         Mask.push_back(-1);
9060         continue;
9061       }
9062
9063       // If extracting from the first vector, just use the index directly.
9064       SDValue Extract = N->getOperand(i);
9065       SDValue ExtVal = Extract.getOperand(1);
9066       if (Extract.getOperand(0) == VecIn1) {
9067         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9068         if (ExtIndex > VT.getVectorNumElements())
9069           return SDValue();
9070
9071         Mask.push_back(ExtIndex);
9072         continue;
9073       }
9074
9075       // Otherwise, use InIdx + VecSize
9076       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9077       Mask.push_back(Idx+NumInScalars);
9078     }
9079
9080     // We can't generate a shuffle node with mismatched input and output types.
9081     // Attempt to transform a single input vector to the correct type.
9082     if ((VT != VecIn1.getValueType())) {
9083       // We don't support shuffeling between TWO values of different types.
9084       if (VecIn2.getNode() != 0)
9085         return SDValue();
9086
9087       // We only support widening of vectors which are half the size of the
9088       // output registers. For example XMM->YMM widening on X86 with AVX.
9089       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9090         return SDValue();
9091
9092       // If the input vector type has a different base type to the output
9093       // vector type, bail out.
9094       if (VecIn1.getValueType().getVectorElementType() !=
9095           VT.getVectorElementType())
9096         return SDValue();
9097
9098       // Widen the input vector by adding undef values.
9099       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9100                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9101     }
9102
9103     // If VecIn2 is unused then change it to undef.
9104     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9105
9106     // Check that we were able to transform all incoming values to the same
9107     // type.
9108     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9109         VecIn1.getValueType() != VT)
9110           return SDValue();
9111
9112     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9113     if (!isTypeLegal(VT))
9114       return SDValue();
9115
9116     // Return the new VECTOR_SHUFFLE node.
9117     SDValue Ops[2];
9118     Ops[0] = VecIn1;
9119     Ops[1] = VecIn2;
9120     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9121   }
9122
9123   return SDValue();
9124 }
9125
9126 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9127   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9128   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9129   // inputs come from at most two distinct vectors, turn this into a shuffle
9130   // node.
9131
9132   // If we only have one input vector, we don't need to do any concatenation.
9133   if (N->getNumOperands() == 1)
9134     return N->getOperand(0);
9135
9136   // Check if all of the operands are undefs.
9137   if (ISD::allOperandsUndef(N))
9138     return DAG.getUNDEF(N->getValueType(0));
9139
9140   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9141   // nodes often generate nop CONCAT_VECTOR nodes.
9142   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9143   // place the incoming vectors at the exact same location.
9144   SDValue SingleSource = SDValue();
9145   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9146
9147   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9148     SDValue Op = N->getOperand(i);
9149
9150     if (Op.getOpcode() == ISD::UNDEF)
9151       continue;
9152
9153     // Check if this is the identity extract:
9154     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9155       return SDValue();
9156
9157     // Find the single incoming vector for the extract_subvector.
9158     if (SingleSource.getNode()) {
9159       if (Op.getOperand(0) != SingleSource)
9160         return SDValue();
9161     } else {
9162       SingleSource = Op.getOperand(0);
9163
9164       // Check the source type is the same as the type of the result.
9165       // If not, this concat may extend the vector, so we can not
9166       // optimize it away.
9167       if (SingleSource.getValueType() != N->getValueType(0))
9168         return SDValue();
9169     }
9170
9171     unsigned IdentityIndex = i * PartNumElem;
9172     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9173     // The extract index must be constant.
9174     if (!CS)
9175       return SDValue();
9176     
9177     // Check that we are reading from the identity index.
9178     if (CS->getZExtValue() != IdentityIndex)
9179       return SDValue();
9180   }
9181
9182   if (SingleSource.getNode())
9183     return SingleSource;
9184   
9185   return SDValue();
9186 }
9187
9188 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9189   EVT NVT = N->getValueType(0);
9190   SDValue V = N->getOperand(0);
9191
9192   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9193     // Combine:
9194     //    (extract_subvec (concat V1, V2, ...), i)
9195     // Into:
9196     //    Vi if possible
9197     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9198     if (V->getOperand(0).getValueType() != NVT)
9199       return SDValue();
9200     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9201     unsigned NumElems = NVT.getVectorNumElements();
9202     assert((Idx % NumElems) == 0 &&
9203            "IDX in concat is not a multiple of the result vector length.");
9204     return V->getOperand(Idx / NumElems);
9205   }
9206
9207   // Skip bitcasting
9208   if (V->getOpcode() == ISD::BITCAST)
9209     V = V.getOperand(0);
9210
9211   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9212     SDLoc dl(N);
9213     // Handle only simple case where vector being inserted and vector
9214     // being extracted are of same type, and are half size of larger vectors.
9215     EVT BigVT = V->getOperand(0).getValueType();
9216     EVT SmallVT = V->getOperand(1).getValueType();
9217     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9218       return SDValue();
9219
9220     // Only handle cases where both indexes are constants with the same type.
9221     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9222     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9223
9224     if (InsIdx && ExtIdx &&
9225         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9226         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9227       // Combine:
9228       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9229       // Into:
9230       //    indices are equal or bit offsets are equal => V1
9231       //    otherwise => (extract_subvec V1, ExtIdx)
9232       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9233           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9234         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9235       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9236                          DAG.getNode(ISD::BITCAST, dl,
9237                                      N->getOperand(0).getValueType(),
9238                                      V->getOperand(0)), N->getOperand(1));
9239     }
9240   }
9241
9242   return SDValue();
9243 }
9244
9245 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9246 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9247   EVT VT = N->getValueType(0);
9248   unsigned NumElts = VT.getVectorNumElements();
9249
9250   SDValue N0 = N->getOperand(0);
9251   SDValue N1 = N->getOperand(1);
9252   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9253
9254   SmallVector<SDValue, 4> Ops;
9255   EVT ConcatVT = N0.getOperand(0).getValueType();
9256   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9257   unsigned NumConcats = NumElts / NumElemsPerConcat;
9258
9259   // Look at every vector that's inserted. We're looking for exact
9260   // subvector-sized copies from a concatenated vector
9261   for (unsigned I = 0; I != NumConcats; ++I) {
9262     // Make sure we're dealing with a copy.
9263     unsigned Begin = I * NumElemsPerConcat;
9264     bool AllUndef = true, NoUndef = true;
9265     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9266       if (SVN->getMaskElt(J) >= 0)
9267         AllUndef = false;
9268       else
9269         NoUndef = false;
9270     }
9271
9272     if (NoUndef) {
9273       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9274         return SDValue();
9275
9276       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9277         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9278           return SDValue();
9279
9280       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9281       if (FirstElt < N0.getNumOperands())
9282         Ops.push_back(N0.getOperand(FirstElt));
9283       else
9284         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9285
9286     } else if (AllUndef) {
9287       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9288     } else { // Mixed with general masks and undefs, can't do optimization.
9289       return SDValue();
9290     }
9291   }
9292
9293   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9294                      Ops.size());
9295 }
9296
9297 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9298   EVT VT = N->getValueType(0);
9299   unsigned NumElts = VT.getVectorNumElements();
9300
9301   SDValue N0 = N->getOperand(0);
9302   SDValue N1 = N->getOperand(1);
9303
9304   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9305
9306   // Canonicalize shuffle undef, undef -> undef
9307   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9308     return DAG.getUNDEF(VT);
9309
9310   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9311
9312   // Canonicalize shuffle v, v -> v, undef
9313   if (N0 == N1) {
9314     SmallVector<int, 8> NewMask;
9315     for (unsigned i = 0; i != NumElts; ++i) {
9316       int Idx = SVN->getMaskElt(i);
9317       if (Idx >= (int)NumElts) Idx -= NumElts;
9318       NewMask.push_back(Idx);
9319     }
9320     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9321                                 &NewMask[0]);
9322   }
9323
9324   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9325   if (N0.getOpcode() == ISD::UNDEF) {
9326     SmallVector<int, 8> NewMask;
9327     for (unsigned i = 0; i != NumElts; ++i) {
9328       int Idx = SVN->getMaskElt(i);
9329       if (Idx >= 0) {
9330         if (Idx < (int)NumElts)
9331           Idx += NumElts;
9332         else
9333           Idx -= NumElts;
9334       }
9335       NewMask.push_back(Idx);
9336     }
9337     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9338                                 &NewMask[0]);
9339   }
9340
9341   // Remove references to rhs if it is undef
9342   if (N1.getOpcode() == ISD::UNDEF) {
9343     bool Changed = false;
9344     SmallVector<int, 8> NewMask;
9345     for (unsigned i = 0; i != NumElts; ++i) {
9346       int Idx = SVN->getMaskElt(i);
9347       if (Idx >= (int)NumElts) {
9348         Idx = -1;
9349         Changed = true;
9350       }
9351       NewMask.push_back(Idx);
9352     }
9353     if (Changed)
9354       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9355   }
9356
9357   // If it is a splat, check if the argument vector is another splat or a
9358   // build_vector with all scalar elements the same.
9359   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9360     SDNode *V = N0.getNode();
9361
9362     // If this is a bit convert that changes the element type of the vector but
9363     // not the number of vector elements, look through it.  Be careful not to
9364     // look though conversions that change things like v4f32 to v2f64.
9365     if (V->getOpcode() == ISD::BITCAST) {
9366       SDValue ConvInput = V->getOperand(0);
9367       if (ConvInput.getValueType().isVector() &&
9368           ConvInput.getValueType().getVectorNumElements() == NumElts)
9369         V = ConvInput.getNode();
9370     }
9371
9372     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9373       assert(V->getNumOperands() == NumElts &&
9374              "BUILD_VECTOR has wrong number of operands");
9375       SDValue Base;
9376       bool AllSame = true;
9377       for (unsigned i = 0; i != NumElts; ++i) {
9378         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9379           Base = V->getOperand(i);
9380           break;
9381         }
9382       }
9383       // Splat of <u, u, u, u>, return <u, u, u, u>
9384       if (!Base.getNode())
9385         return N0;
9386       for (unsigned i = 0; i != NumElts; ++i) {
9387         if (V->getOperand(i) != Base) {
9388           AllSame = false;
9389           break;
9390         }
9391       }
9392       // Splat of <x, x, x, x>, return <x, x, x, x>
9393       if (AllSame)
9394         return N0;
9395     }
9396   }
9397
9398   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9399       Level < AfterLegalizeVectorOps &&
9400       (N1.getOpcode() == ISD::UNDEF ||
9401       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9402        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9403     SDValue V = partitionShuffleOfConcats(N, DAG);
9404
9405     if (V.getNode())
9406       return V;
9407   }
9408
9409   // If this shuffle node is simply a swizzle of another shuffle node,
9410   // and it reverses the swizzle of the previous shuffle then we can
9411   // optimize shuffle(shuffle(x, undef), undef) -> x.
9412   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9413       N1.getOpcode() == ISD::UNDEF) {
9414
9415     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9416
9417     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9418     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9419       return SDValue();
9420
9421     // The incoming shuffle must be of the same type as the result of the
9422     // current shuffle.
9423     assert(OtherSV->getOperand(0).getValueType() == VT &&
9424            "Shuffle types don't match");
9425
9426     for (unsigned i = 0; i != NumElts; ++i) {
9427       int Idx = SVN->getMaskElt(i);
9428       assert(Idx < (int)NumElts && "Index references undef operand");
9429       // Next, this index comes from the first value, which is the incoming
9430       // shuffle. Adopt the incoming index.
9431       if (Idx >= 0)
9432         Idx = OtherSV->getMaskElt(Idx);
9433
9434       // The combined shuffle must map each index to itself.
9435       if (Idx >= 0 && (unsigned)Idx != i)
9436         return SDValue();
9437     }
9438
9439     return OtherSV->getOperand(0);
9440   }
9441
9442   return SDValue();
9443 }
9444
9445 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9446 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9447 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9448 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9449 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9450   EVT VT = N->getValueType(0);
9451   SDLoc dl(N);
9452   SDValue LHS = N->getOperand(0);
9453   SDValue RHS = N->getOperand(1);
9454   if (N->getOpcode() == ISD::AND) {
9455     if (RHS.getOpcode() == ISD::BITCAST)
9456       RHS = RHS.getOperand(0);
9457     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9458       SmallVector<int, 8> Indices;
9459       unsigned NumElts = RHS.getNumOperands();
9460       for (unsigned i = 0; i != NumElts; ++i) {
9461         SDValue Elt = RHS.getOperand(i);
9462         if (!isa<ConstantSDNode>(Elt))
9463           return SDValue();
9464
9465         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9466           Indices.push_back(i);
9467         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9468           Indices.push_back(NumElts);
9469         else
9470           return SDValue();
9471       }
9472
9473       // Let's see if the target supports this vector_shuffle.
9474       EVT RVT = RHS.getValueType();
9475       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9476         return SDValue();
9477
9478       // Return the new VECTOR_SHUFFLE node.
9479       EVT EltVT = RVT.getVectorElementType();
9480       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9481                                      DAG.getConstant(0, EltVT));
9482       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9483                                  RVT, &ZeroOps[0], ZeroOps.size());
9484       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9485       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9486       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9487     }
9488   }
9489
9490   return SDValue();
9491 }
9492
9493 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9494 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9495   assert(N->getValueType(0).isVector() &&
9496          "SimplifyVBinOp only works on vectors!");
9497
9498   SDValue LHS = N->getOperand(0);
9499   SDValue RHS = N->getOperand(1);
9500   SDValue Shuffle = XformToShuffleWithZero(N);
9501   if (Shuffle.getNode()) return Shuffle;
9502
9503   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9504   // this operation.
9505   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9506       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9507     SmallVector<SDValue, 8> Ops;
9508     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9509       SDValue LHSOp = LHS.getOperand(i);
9510       SDValue RHSOp = RHS.getOperand(i);
9511       // If these two elements can't be folded, bail out.
9512       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9513            LHSOp.getOpcode() != ISD::Constant &&
9514            LHSOp.getOpcode() != ISD::ConstantFP) ||
9515           (RHSOp.getOpcode() != ISD::UNDEF &&
9516            RHSOp.getOpcode() != ISD::Constant &&
9517            RHSOp.getOpcode() != ISD::ConstantFP))
9518         break;
9519
9520       // Can't fold divide by zero.
9521       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9522           N->getOpcode() == ISD::FDIV) {
9523         if ((RHSOp.getOpcode() == ISD::Constant &&
9524              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9525             (RHSOp.getOpcode() == ISD::ConstantFP &&
9526              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9527           break;
9528       }
9529
9530       EVT VT = LHSOp.getValueType();
9531       EVT RVT = RHSOp.getValueType();
9532       if (RVT != VT) {
9533         // Integer BUILD_VECTOR operands may have types larger than the element
9534         // size (e.g., when the element type is not legal).  Prior to type
9535         // legalization, the types may not match between the two BUILD_VECTORS.
9536         // Truncate one of the operands to make them match.
9537         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9538           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9539         } else {
9540           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9541           VT = RVT;
9542         }
9543       }
9544       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9545                                    LHSOp, RHSOp);
9546       if (FoldOp.getOpcode() != ISD::UNDEF &&
9547           FoldOp.getOpcode() != ISD::Constant &&
9548           FoldOp.getOpcode() != ISD::ConstantFP)
9549         break;
9550       Ops.push_back(FoldOp);
9551       AddToWorkList(FoldOp.getNode());
9552     }
9553
9554     if (Ops.size() == LHS.getNumOperands())
9555       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9556                          LHS.getValueType(), &Ops[0], Ops.size());
9557   }
9558
9559   return SDValue();
9560 }
9561
9562 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9563 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9564   assert(N->getValueType(0).isVector() &&
9565          "SimplifyVUnaryOp only works on vectors!");
9566
9567   SDValue N0 = N->getOperand(0);
9568
9569   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9570     return SDValue();
9571
9572   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9573   SmallVector<SDValue, 8> Ops;
9574   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9575     SDValue Op = N0.getOperand(i);
9576     if (Op.getOpcode() != ISD::UNDEF &&
9577         Op.getOpcode() != ISD::ConstantFP)
9578       break;
9579     EVT EltVT = Op.getValueType();
9580     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9581     if (FoldOp.getOpcode() != ISD::UNDEF &&
9582         FoldOp.getOpcode() != ISD::ConstantFP)
9583       break;
9584     Ops.push_back(FoldOp);
9585     AddToWorkList(FoldOp.getNode());
9586   }
9587
9588   if (Ops.size() != N0.getNumOperands())
9589     return SDValue();
9590
9591   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9592                      N0.getValueType(), &Ops[0], Ops.size());
9593 }
9594
9595 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9596                                     SDValue N1, SDValue N2){
9597   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9598
9599   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9600                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9601
9602   // If we got a simplified select_cc node back from SimplifySelectCC, then
9603   // break it down into a new SETCC node, and a new SELECT node, and then return
9604   // the SELECT node, since we were called with a SELECT node.
9605   if (SCC.getNode()) {
9606     // Check to see if we got a select_cc back (to turn into setcc/select).
9607     // Otherwise, just return whatever node we got back, like fabs.
9608     if (SCC.getOpcode() == ISD::SELECT_CC) {
9609       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9610                                   N0.getValueType(),
9611                                   SCC.getOperand(0), SCC.getOperand(1),
9612                                   SCC.getOperand(4));
9613       AddToWorkList(SETCC.getNode());
9614       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9615                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
9616     }
9617
9618     return SCC;
9619   }
9620   return SDValue();
9621 }
9622
9623 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9624 /// are the two values being selected between, see if we can simplify the
9625 /// select.  Callers of this should assume that TheSelect is deleted if this
9626 /// returns true.  As such, they should return the appropriate thing (e.g. the
9627 /// node) back to the top-level of the DAG combiner loop to avoid it being
9628 /// looked at.
9629 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9630                                     SDValue RHS) {
9631
9632   // Cannot simplify select with vector condition
9633   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9634
9635   // If this is a select from two identical things, try to pull the operation
9636   // through the select.
9637   if (LHS.getOpcode() != RHS.getOpcode() ||
9638       !LHS.hasOneUse() || !RHS.hasOneUse())
9639     return false;
9640
9641   // If this is a load and the token chain is identical, replace the select
9642   // of two loads with a load through a select of the address to load from.
9643   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9644   // constants have been dropped into the constant pool.
9645   if (LHS.getOpcode() == ISD::LOAD) {
9646     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9647     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9648
9649     // Token chains must be identical.
9650     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9651         // Do not let this transformation reduce the number of volatile loads.
9652         LLD->isVolatile() || RLD->isVolatile() ||
9653         // If this is an EXTLOAD, the VT's must match.
9654         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9655         // If this is an EXTLOAD, the kind of extension must match.
9656         (LLD->getExtensionType() != RLD->getExtensionType() &&
9657          // The only exception is if one of the extensions is anyext.
9658          LLD->getExtensionType() != ISD::EXTLOAD &&
9659          RLD->getExtensionType() != ISD::EXTLOAD) ||
9660         // FIXME: this discards src value information.  This is
9661         // over-conservative. It would be beneficial to be able to remember
9662         // both potential memory locations.  Since we are discarding
9663         // src value info, don't do the transformation if the memory
9664         // locations are not in the default address space.
9665         LLD->getPointerInfo().getAddrSpace() != 0 ||
9666         RLD->getPointerInfo().getAddrSpace() != 0 ||
9667         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9668                                       LLD->getBasePtr().getValueType()))
9669       return false;
9670
9671     // Check that the select condition doesn't reach either load.  If so,
9672     // folding this will induce a cycle into the DAG.  If not, this is safe to
9673     // xform, so create a select of the addresses.
9674     SDValue Addr;
9675     if (TheSelect->getOpcode() == ISD::SELECT) {
9676       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9677       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9678           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9679         return false;
9680       // The loads must not depend on one another.
9681       if (LLD->isPredecessorOf(RLD) ||
9682           RLD->isPredecessorOf(LLD))
9683         return false;
9684       Addr = DAG.getSelect(SDLoc(TheSelect),
9685                            LLD->getBasePtr().getValueType(),
9686                            TheSelect->getOperand(0), LLD->getBasePtr(),
9687                            RLD->getBasePtr());
9688     } else {  // Otherwise SELECT_CC
9689       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9690       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9691
9692       if ((LLD->hasAnyUseOfValue(1) &&
9693            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9694           (RLD->hasAnyUseOfValue(1) &&
9695            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9696         return false;
9697
9698       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9699                          LLD->getBasePtr().getValueType(),
9700                          TheSelect->getOperand(0),
9701                          TheSelect->getOperand(1),
9702                          LLD->getBasePtr(), RLD->getBasePtr(),
9703                          TheSelect->getOperand(4));
9704     }
9705
9706     SDValue Load;
9707     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9708       Load = DAG.getLoad(TheSelect->getValueType(0),
9709                          SDLoc(TheSelect),
9710                          // FIXME: Discards pointer info.
9711                          LLD->getChain(), Addr, MachinePointerInfo(),
9712                          LLD->isVolatile(), LLD->isNonTemporal(),
9713                          LLD->isInvariant(), LLD->getAlignment());
9714     } else {
9715       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9716                             RLD->getExtensionType() : LLD->getExtensionType(),
9717                             SDLoc(TheSelect),
9718                             TheSelect->getValueType(0),
9719                             // FIXME: Discards pointer info.
9720                             LLD->getChain(), Addr, MachinePointerInfo(),
9721                             LLD->getMemoryVT(), LLD->isVolatile(),
9722                             LLD->isNonTemporal(), LLD->getAlignment());
9723     }
9724
9725     // Users of the select now use the result of the load.
9726     CombineTo(TheSelect, Load);
9727
9728     // Users of the old loads now use the new load's chain.  We know the
9729     // old-load value is dead now.
9730     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9731     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9732     return true;
9733   }
9734
9735   return false;
9736 }
9737
9738 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9739 /// where 'cond' is the comparison specified by CC.
9740 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9741                                       SDValue N2, SDValue N3,
9742                                       ISD::CondCode CC, bool NotExtCompare) {
9743   // (x ? y : y) -> y.
9744   if (N2 == N3) return N2;
9745
9746   EVT VT = N2.getValueType();
9747   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9748   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9749   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9750
9751   // Determine if the condition we're dealing with is constant
9752   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9753                               N0, N1, CC, DL, false);
9754   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9755   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9756
9757   // fold select_cc true, x, y -> x
9758   if (SCCC && !SCCC->isNullValue())
9759     return N2;
9760   // fold select_cc false, x, y -> y
9761   if (SCCC && SCCC->isNullValue())
9762     return N3;
9763
9764   // Check to see if we can simplify the select into an fabs node
9765   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9766     // Allow either -0.0 or 0.0
9767     if (CFP->getValueAPF().isZero()) {
9768       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9769       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9770           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9771           N2 == N3.getOperand(0))
9772         return DAG.getNode(ISD::FABS, DL, VT, N0);
9773
9774       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9775       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9776           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9777           N2.getOperand(0) == N3)
9778         return DAG.getNode(ISD::FABS, DL, VT, N3);
9779     }
9780   }
9781
9782   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9783   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9784   // in it.  This is a win when the constant is not otherwise available because
9785   // it replaces two constant pool loads with one.  We only do this if the FP
9786   // type is known to be legal, because if it isn't, then we are before legalize
9787   // types an we want the other legalization to happen first (e.g. to avoid
9788   // messing with soft float) and if the ConstantFP is not legal, because if
9789   // it is legal, we may not need to store the FP constant in a constant pool.
9790   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9791     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9792       if (TLI.isTypeLegal(N2.getValueType()) &&
9793           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9794            TargetLowering::Legal) &&
9795           // If both constants have multiple uses, then we won't need to do an
9796           // extra load, they are likely around in registers for other users.
9797           (TV->hasOneUse() || FV->hasOneUse())) {
9798         Constant *Elts[] = {
9799           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9800           const_cast<ConstantFP*>(TV->getConstantFPValue())
9801         };
9802         Type *FPTy = Elts[0]->getType();
9803         const DataLayout &TD = *TLI.getDataLayout();
9804
9805         // Create a ConstantArray of the two constants.
9806         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9807         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9808                                             TD.getPrefTypeAlignment(FPTy));
9809         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9810
9811         // Get the offsets to the 0 and 1 element of the array so that we can
9812         // select between them.
9813         SDValue Zero = DAG.getIntPtrConstant(0);
9814         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9815         SDValue One = DAG.getIntPtrConstant(EltSize);
9816
9817         SDValue Cond = DAG.getSetCC(DL,
9818                                     getSetCCResultType(N0.getValueType()),
9819                                     N0, N1, CC);
9820         AddToWorkList(Cond.getNode());
9821         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9822                                           Cond, One, Zero);
9823         AddToWorkList(CstOffset.getNode());
9824         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9825                             CstOffset);
9826         AddToWorkList(CPIdx.getNode());
9827         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9828                            MachinePointerInfo::getConstantPool(), false,
9829                            false, false, Alignment);
9830
9831       }
9832     }
9833
9834   // Check to see if we can perform the "gzip trick", transforming
9835   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9836   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9837       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9838        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9839     EVT XType = N0.getValueType();
9840     EVT AType = N2.getValueType();
9841     if (XType.bitsGE(AType)) {
9842       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9843       // single-bit constant.
9844       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9845         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9846         ShCtV = XType.getSizeInBits()-ShCtV-1;
9847         SDValue ShCt = DAG.getConstant(ShCtV,
9848                                        getShiftAmountTy(N0.getValueType()));
9849         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9850                                     XType, N0, ShCt);
9851         AddToWorkList(Shift.getNode());
9852
9853         if (XType.bitsGT(AType)) {
9854           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9855           AddToWorkList(Shift.getNode());
9856         }
9857
9858         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9859       }
9860
9861       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9862                                   XType, N0,
9863                                   DAG.getConstant(XType.getSizeInBits()-1,
9864                                          getShiftAmountTy(N0.getValueType())));
9865       AddToWorkList(Shift.getNode());
9866
9867       if (XType.bitsGT(AType)) {
9868         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9869         AddToWorkList(Shift.getNode());
9870       }
9871
9872       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9873     }
9874   }
9875
9876   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9877   // where y is has a single bit set.
9878   // A plaintext description would be, we can turn the SELECT_CC into an AND
9879   // when the condition can be materialized as an all-ones register.  Any
9880   // single bit-test can be materialized as an all-ones register with
9881   // shift-left and shift-right-arith.
9882   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9883       N0->getValueType(0) == VT &&
9884       N1C && N1C->isNullValue() &&
9885       N2C && N2C->isNullValue()) {
9886     SDValue AndLHS = N0->getOperand(0);
9887     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9888     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9889       // Shift the tested bit over the sign bit.
9890       APInt AndMask = ConstAndRHS->getAPIntValue();
9891       SDValue ShlAmt =
9892         DAG.getConstant(AndMask.countLeadingZeros(),
9893                         getShiftAmountTy(AndLHS.getValueType()));
9894       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
9895
9896       // Now arithmetic right shift it all the way over, so the result is either
9897       // all-ones, or zero.
9898       SDValue ShrAmt =
9899         DAG.getConstant(AndMask.getBitWidth()-1,
9900                         getShiftAmountTy(Shl.getValueType()));
9901       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
9902
9903       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9904     }
9905   }
9906
9907   // fold select C, 16, 0 -> shl C, 4
9908   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9909     TLI.getBooleanContents(N0.getValueType().isVector()) ==
9910       TargetLowering::ZeroOrOneBooleanContent) {
9911
9912     // If the caller doesn't want us to simplify this into a zext of a compare,
9913     // don't do it.
9914     if (NotExtCompare && N2C->getAPIntValue() == 1)
9915       return SDValue();
9916
9917     // Get a SetCC of the condition
9918     // NOTE: Don't create a SETCC if it's not legal on this target.
9919     if (!LegalOperations ||
9920         TLI.isOperationLegal(ISD::SETCC,
9921           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9922       SDValue Temp, SCC;
9923       // cast from setcc result type to select result type
9924       if (LegalTypes) {
9925         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
9926                             N0, N1, CC);
9927         if (N2.getValueType().bitsLT(SCC.getValueType()))
9928           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
9929                                         N2.getValueType());
9930         else
9931           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
9932                              N2.getValueType(), SCC);
9933       } else {
9934         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
9935         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
9936                            N2.getValueType(), SCC);
9937       }
9938
9939       AddToWorkList(SCC.getNode());
9940       AddToWorkList(Temp.getNode());
9941
9942       if (N2C->getAPIntValue() == 1)
9943         return Temp;
9944
9945       // shl setcc result by log2 n2c
9946       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9947                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
9948                                          getShiftAmountTy(Temp.getValueType())));
9949     }
9950   }
9951
9952   // Check to see if this is the equivalent of setcc
9953   // FIXME: Turn all of these into setcc if setcc if setcc is legal
9954   // otherwise, go ahead with the folds.
9955   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9956     EVT XType = N0.getValueType();
9957     if (!LegalOperations ||
9958         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
9959       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
9960       if (Res.getValueType() != VT)
9961         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9962       return Res;
9963     }
9964
9965     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9966     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9967         (!LegalOperations ||
9968          TLI.isOperationLegal(ISD::CTLZ, XType))) {
9969       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
9970       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9971                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
9972                                        getShiftAmountTy(Ctlz.getValueType())));
9973     }
9974     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9975     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9976       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
9977                                   XType, DAG.getConstant(0, XType), N0);
9978       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
9979       return DAG.getNode(ISD::SRL, DL, XType,
9980                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
9981                          DAG.getConstant(XType.getSizeInBits()-1,
9982                                          getShiftAmountTy(XType)));
9983     }
9984     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
9985     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
9986       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
9987                                  DAG.getConstant(XType.getSizeInBits()-1,
9988                                          getShiftAmountTy(N0.getValueType())));
9989       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
9990     }
9991   }
9992
9993   // Check to see if this is an integer abs.
9994   // select_cc setg[te] X,  0,  X, -X ->
9995   // select_cc setgt    X, -1,  X, -X ->
9996   // select_cc setl[te] X,  0, -X,  X ->
9997   // select_cc setlt    X,  1, -X,  X ->
9998   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9999   if (N1C) {
10000     ConstantSDNode *SubC = NULL;
10001     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10002          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10003         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10004       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10005     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10006               (N1C->isOne() && CC == ISD::SETLT)) &&
10007              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10008       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10009
10010     EVT XType = N0.getValueType();
10011     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10012       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10013                                   N0,
10014                                   DAG.getConstant(XType.getSizeInBits()-1,
10015                                          getShiftAmountTy(N0.getValueType())));
10016       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10017                                 XType, N0, Shift);
10018       AddToWorkList(Shift.getNode());
10019       AddToWorkList(Add.getNode());
10020       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10021     }
10022   }
10023
10024   return SDValue();
10025 }
10026
10027 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10028 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10029                                    SDValue N1, ISD::CondCode Cond,
10030                                    SDLoc DL, bool foldBooleans) {
10031   TargetLowering::DAGCombinerInfo
10032     DagCombineInfo(DAG, Level, false, this);
10033   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10034 }
10035
10036 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10037 /// return a DAG expression to select that will generate the same value by
10038 /// multiplying by a magic number.  See:
10039 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10040 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10041   std::vector<SDNode*> Built;
10042   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10043
10044   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10045        ii != ee; ++ii)
10046     AddToWorkList(*ii);
10047   return S;
10048 }
10049
10050 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10051 /// return a DAG expression to select that will generate the same value by
10052 /// multiplying by a magic number.  See:
10053 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10054 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10055   std::vector<SDNode*> Built;
10056   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10057
10058   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10059        ii != ee; ++ii)
10060     AddToWorkList(*ii);
10061   return S;
10062 }
10063
10064 /// FindBaseOffset - Return true if base is a frame index, which is known not
10065 // to alias with anything but itself.  Provides base object and offset as
10066 // results.
10067 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10068                            const GlobalValue *&GV, const void *&CV) {
10069   // Assume it is a primitive operation.
10070   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10071
10072   // If it's an adding a simple constant then integrate the offset.
10073   if (Base.getOpcode() == ISD::ADD) {
10074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10075       Base = Base.getOperand(0);
10076       Offset += C->getZExtValue();
10077     }
10078   }
10079
10080   // Return the underlying GlobalValue, and update the Offset.  Return false
10081   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10082   // by multiple nodes with different offsets.
10083   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10084     GV = G->getGlobal();
10085     Offset += G->getOffset();
10086     return false;
10087   }
10088
10089   // Return the underlying Constant value, and update the Offset.  Return false
10090   // for ConstantSDNodes since the same constant pool entry may be represented
10091   // by multiple nodes with different offsets.
10092   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10093     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10094                                          : (const void *)C->getConstVal();
10095     Offset += C->getOffset();
10096     return false;
10097   }
10098   // If it's any of the following then it can't alias with anything but itself.
10099   return isa<FrameIndexSDNode>(Base);
10100 }
10101
10102 /// isAlias - Return true if there is any possibility that the two addresses
10103 /// overlap.
10104 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10105                           const Value *SrcValue1, int SrcValueOffset1,
10106                           unsigned SrcValueAlign1,
10107                           const MDNode *TBAAInfo1,
10108                           SDValue Ptr2, int64_t Size2,
10109                           const Value *SrcValue2, int SrcValueOffset2,
10110                           unsigned SrcValueAlign2,
10111                           const MDNode *TBAAInfo2) const {
10112   // If they are the same then they must be aliases.
10113   if (Ptr1 == Ptr2) return true;
10114
10115   // Gather base node and offset information.
10116   SDValue Base1, Base2;
10117   int64_t Offset1, Offset2;
10118   const GlobalValue *GV1, *GV2;
10119   const void *CV1, *CV2;
10120   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10121   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10122
10123   // If they have a same base address then check to see if they overlap.
10124   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10125     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10126
10127   // It is possible for different frame indices to alias each other, mostly
10128   // when tail call optimization reuses return address slots for arguments.
10129   // To catch this case, look up the actual index of frame indices to compute
10130   // the real alias relationship.
10131   if (isFrameIndex1 && isFrameIndex2) {
10132     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10133     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10134     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10135     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10136   }
10137
10138   // Otherwise, if we know what the bases are, and they aren't identical, then
10139   // we know they cannot alias.
10140   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10141     return false;
10142
10143   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10144   // compared to the size and offset of the access, we may be able to prove they
10145   // do not alias.  This check is conservative for now to catch cases created by
10146   // splitting vector types.
10147   if ((SrcValueAlign1 == SrcValueAlign2) &&
10148       (SrcValueOffset1 != SrcValueOffset2) &&
10149       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10150     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10151     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10152
10153     // There is no overlap between these relatively aligned accesses of similar
10154     // size, return no alias.
10155     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10156       return false;
10157   }
10158
10159   if (CombinerGlobalAA) {
10160     // Use alias analysis information.
10161     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10162     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10163     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10164     AliasAnalysis::AliasResult AAResult =
10165       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10166                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10167     if (AAResult == AliasAnalysis::NoAlias)
10168       return false;
10169   }
10170
10171   // Otherwise we have to assume they alias.
10172   return true;
10173 }
10174
10175 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10176   SDValue Ptr0, Ptr1;
10177   int64_t Size0, Size1;
10178   const Value *SrcValue0, *SrcValue1;
10179   int SrcValueOffset0, SrcValueOffset1;
10180   unsigned SrcValueAlign0, SrcValueAlign1;
10181   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10182   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10183                 SrcValueAlign0, SrcTBAAInfo0);
10184   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10185                 SrcValueAlign1, SrcTBAAInfo1);
10186   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10187                  SrcValueAlign0, SrcTBAAInfo0,
10188                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10189                  SrcValueAlign1, SrcTBAAInfo1);
10190 }
10191
10192 /// FindAliasInfo - Extracts the relevant alias information from the memory
10193 /// node.  Returns true if the operand was a load.
10194 bool DAGCombiner::FindAliasInfo(SDNode *N,
10195                                 SDValue &Ptr, int64_t &Size,
10196                                 const Value *&SrcValue,
10197                                 int &SrcValueOffset,
10198                                 unsigned &SrcValueAlign,
10199                                 const MDNode *&TBAAInfo) const {
10200   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10201
10202   Ptr = LS->getBasePtr();
10203   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10204   SrcValue = LS->getSrcValue();
10205   SrcValueOffset = LS->getSrcValueOffset();
10206   SrcValueAlign = LS->getOriginalAlignment();
10207   TBAAInfo = LS->getTBAAInfo();
10208   return isa<LoadSDNode>(LS);
10209 }
10210
10211 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10212 /// looking for aliasing nodes and adding them to the Aliases vector.
10213 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10214                                    SmallVector<SDValue, 8> &Aliases) {
10215   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10216   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10217
10218   // Get alias information for node.
10219   SDValue Ptr;
10220   int64_t Size;
10221   const Value *SrcValue;
10222   int SrcValueOffset;
10223   unsigned SrcValueAlign;
10224   const MDNode *SrcTBAAInfo;
10225   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10226                               SrcValueAlign, SrcTBAAInfo);
10227
10228   // Starting off.
10229   Chains.push_back(OriginalChain);
10230   unsigned Depth = 0;
10231
10232   // Look at each chain and determine if it is an alias.  If so, add it to the
10233   // aliases list.  If not, then continue up the chain looking for the next
10234   // candidate.
10235   while (!Chains.empty()) {
10236     SDValue Chain = Chains.back();
10237     Chains.pop_back();
10238
10239     // For TokenFactor nodes, look at each operand and only continue up the
10240     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10241     // find more and revert to original chain since the xform is unlikely to be
10242     // profitable.
10243     //
10244     // FIXME: The depth check could be made to return the last non-aliasing
10245     // chain we found before we hit a tokenfactor rather than the original
10246     // chain.
10247     if (Depth > 6 || Aliases.size() == 2) {
10248       Aliases.clear();
10249       Aliases.push_back(OriginalChain);
10250       break;
10251     }
10252
10253     // Don't bother if we've been before.
10254     if (!Visited.insert(Chain.getNode()))
10255       continue;
10256
10257     switch (Chain.getOpcode()) {
10258     case ISD::EntryToken:
10259       // Entry token is ideal chain operand, but handled in FindBetterChain.
10260       break;
10261
10262     case ISD::LOAD:
10263     case ISD::STORE: {
10264       // Get alias information for Chain.
10265       SDValue OpPtr;
10266       int64_t OpSize;
10267       const Value *OpSrcValue;
10268       int OpSrcValueOffset;
10269       unsigned OpSrcValueAlign;
10270       const MDNode *OpSrcTBAAInfo;
10271       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10272                                     OpSrcValue, OpSrcValueOffset,
10273                                     OpSrcValueAlign,
10274                                     OpSrcTBAAInfo);
10275
10276       // If chain is alias then stop here.
10277       if (!(IsLoad && IsOpLoad) &&
10278           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10279                   SrcTBAAInfo,
10280                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10281                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10282         Aliases.push_back(Chain);
10283       } else {
10284         // Look further up the chain.
10285         Chains.push_back(Chain.getOperand(0));
10286         ++Depth;
10287       }
10288       break;
10289     }
10290
10291     case ISD::TokenFactor:
10292       // We have to check each of the operands of the token factor for "small"
10293       // token factors, so we queue them up.  Adding the operands to the queue
10294       // (stack) in reverse order maintains the original order and increases the
10295       // likelihood that getNode will find a matching token factor (CSE.)
10296       if (Chain.getNumOperands() > 16) {
10297         Aliases.push_back(Chain);
10298         break;
10299       }
10300       for (unsigned n = Chain.getNumOperands(); n;)
10301         Chains.push_back(Chain.getOperand(--n));
10302       ++Depth;
10303       break;
10304
10305     default:
10306       // For all other instructions we will just have to take what we can get.
10307       Aliases.push_back(Chain);
10308       break;
10309     }
10310   }
10311 }
10312
10313 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10314 /// for a better chain (aliasing node.)
10315 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10316   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10317
10318   // Accumulate all the aliases to this node.
10319   GatherAllAliases(N, OldChain, Aliases);
10320
10321   // If no operands then chain to entry token.
10322   if (Aliases.size() == 0)
10323     return DAG.getEntryNode();
10324
10325   // If a single operand then chain to it.  We don't need to revisit it.
10326   if (Aliases.size() == 1)
10327     return Aliases[0];
10328
10329   // Construct a custom tailored token factor.
10330   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10331                      &Aliases[0], Aliases.size());
10332 }
10333
10334 // SelectionDAG::Combine - This is the entry point for the file.
10335 //
10336 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10337                            CodeGenOpt::Level OptLevel) {
10338   /// run - This is the main entry point to this class.
10339   ///
10340   DAGCombiner(*this, AA, OptLevel).Run(Level);
10341 }