Handle masked rotate amounts
[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 "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 STATISTIC(NodesCombined   , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
49
50 namespace {
51   static cl::opt<bool>
52     CombinerAA("combiner-alias-analysis", cl::Hidden,
53                cl::desc("Turn on alias analysis during testing"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Include global information in alias analysis"));
58
59   /// Hidden option to stress test load slicing, i.e., when this option
60   /// is enabled, load slicing bypasses most of its profitability guards.
61   static cl::opt<bool>
62   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63                     cl::desc("Bypass the profitability model of load "
64                              "slicing"),
65                     cl::init(false));
66
67 //------------------------------ DAGCombiner ---------------------------------//
68
69   class DAGCombiner {
70     SelectionDAG &DAG;
71     const TargetLowering &TLI;
72     CombineLevel Level;
73     CodeGenOpt::Level OptLevel;
74     bool LegalOperations;
75     bool LegalTypes;
76     bool ForCodeSize;
77
78     // Worklist of all of the nodes that need to be simplified.
79     //
80     // This has the semantics that when adding to the worklist,
81     // the item added must be next to be processed. It should
82     // also only appear once. The naive approach to this takes
83     // linear time.
84     //
85     // To reduce the insert/remove time to logarithmic, we use
86     // a set and a vector to maintain our worklist.
87     //
88     // The set contains the items on the worklist, but does not
89     // maintain the order they should be visited.
90     //
91     // The vector maintains the order nodes should be visited, but may
92     // contain duplicate or removed nodes. When choosing a node to
93     // visit, we pop off the order stack until we find an item that is
94     // also in the contents set. All operations are O(log N).
95     SmallPtrSet<SDNode*, 64> WorkListContents;
96     SmallVector<SDNode*, 64> WorkListOrder;
97
98     // AA - Used for DAG load/store alias analysis.
99     AliasAnalysis &AA;
100
101     /// AddUsersToWorkList - When an instruction is simplified, add all users of
102     /// the instruction to the work lists because they might get more simplified
103     /// now.
104     ///
105     void AddUsersToWorkList(SDNode *N) {
106       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
107            UI != UE; ++UI)
108         AddToWorkList(*UI);
109     }
110
111     /// visit - call the node-specific routine that knows how to fold each
112     /// particular type of node.
113     SDValue visit(SDNode *N);
114
115   public:
116     /// AddToWorkList - Add to the work list making sure its instance is at the
117     /// back (next to be processed.)
118     void AddToWorkList(SDNode *N) {
119       WorkListContents.insert(N);
120       WorkListOrder.push_back(N);
121     }
122
123     /// removeFromWorkList - remove all instances of N from the worklist.
124     ///
125     void removeFromWorkList(SDNode *N) {
126       WorkListContents.erase(N);
127     }
128
129     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
130                       bool AddTo = true);
131
132     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133       return CombineTo(N, &Res, 1, AddTo);
134     }
135
136     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
137                       bool AddTo = true) {
138       SDValue To[] = { Res0, Res1 };
139       return CombineTo(N, To, 2, AddTo);
140     }
141
142     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
143
144   private:
145
146     /// SimplifyDemandedBits - Check the specified integer node value to see if
147     /// it can be simplified or if things it uses can be simplified by bit
148     /// propagation.  If so, return true.
149     bool SimplifyDemandedBits(SDValue Op) {
150       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151       APInt Demanded = APInt::getAllOnesValue(BitWidth);
152       return SimplifyDemandedBits(Op, Demanded);
153     }
154
155     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
156
157     bool CombineToPreIndexedLoadStore(SDNode *N);
158     bool CombineToPostIndexedLoadStore(SDNode *N);
159     bool SliceUpLoad(SDNode *N);
160
161     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165     SDValue PromoteIntBinOp(SDValue Op);
166     SDValue PromoteIntShiftOp(SDValue Op);
167     SDValue PromoteExtend(SDValue Op);
168     bool PromoteLoad(SDValue Op);
169
170     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172                          ISD::NodeType ExtType);
173
174     /// combine - call the node-specific routine that knows how to fold each
175     /// particular type of node. If that doesn't do anything, try the
176     /// target-specific DAG combines.
177     SDValue combine(SDNode *N);
178
179     // Visitation implementation - Implement dag node combining for different
180     // node types.  The semantics are as follows:
181     // Return Value:
182     //   SDValue.getNode() == 0 - No change was made
183     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
184     //   otherwise              - N should be replaced by the returned Operand.
185     //
186     SDValue visitTokenFactor(SDNode *N);
187     SDValue visitMERGE_VALUES(SDNode *N);
188     SDValue visitADD(SDNode *N);
189     SDValue visitSUB(SDNode *N);
190     SDValue visitADDC(SDNode *N);
191     SDValue visitSUBC(SDNode *N);
192     SDValue visitADDE(SDNode *N);
193     SDValue visitSUBE(SDNode *N);
194     SDValue visitMUL(SDNode *N);
195     SDValue visitSDIV(SDNode *N);
196     SDValue visitUDIV(SDNode *N);
197     SDValue visitSREM(SDNode *N);
198     SDValue visitUREM(SDNode *N);
199     SDValue visitMULHU(SDNode *N);
200     SDValue visitMULHS(SDNode *N);
201     SDValue visitSMUL_LOHI(SDNode *N);
202     SDValue visitUMUL_LOHI(SDNode *N);
203     SDValue visitSMULO(SDNode *N);
204     SDValue visitUMULO(SDNode *N);
205     SDValue visitSDIVREM(SDNode *N);
206     SDValue visitUDIVREM(SDNode *N);
207     SDValue visitAND(SDNode *N);
208     SDValue visitOR(SDNode *N);
209     SDValue visitXOR(SDNode *N);
210     SDValue SimplifyVBinOp(SDNode *N);
211     SDValue SimplifyVUnaryOp(SDNode *N);
212     SDValue visitSHL(SDNode *N);
213     SDValue visitSRA(SDNode *N);
214     SDValue visitSRL(SDNode *N);
215     SDValue visitCTLZ(SDNode *N);
216     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217     SDValue visitCTTZ(SDNode *N);
218     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219     SDValue visitCTPOP(SDNode *N);
220     SDValue visitSELECT(SDNode *N);
221     SDValue visitVSELECT(SDNode *N);
222     SDValue visitSELECT_CC(SDNode *N);
223     SDValue visitSETCC(SDNode *N);
224     SDValue visitSIGN_EXTEND(SDNode *N);
225     SDValue visitZERO_EXTEND(SDNode *N);
226     SDValue visitANY_EXTEND(SDNode *N);
227     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228     SDValue visitTRUNCATE(SDNode *N);
229     SDValue visitBITCAST(SDNode *N);
230     SDValue visitBUILD_PAIR(SDNode *N);
231     SDValue visitFADD(SDNode *N);
232     SDValue visitFSUB(SDNode *N);
233     SDValue visitFMUL(SDNode *N);
234     SDValue visitFMA(SDNode *N);
235     SDValue visitFDIV(SDNode *N);
236     SDValue visitFREM(SDNode *N);
237     SDValue visitFCOPYSIGN(SDNode *N);
238     SDValue visitSINT_TO_FP(SDNode *N);
239     SDValue visitUINT_TO_FP(SDNode *N);
240     SDValue visitFP_TO_SINT(SDNode *N);
241     SDValue visitFP_TO_UINT(SDNode *N);
242     SDValue visitFP_ROUND(SDNode *N);
243     SDValue visitFP_ROUND_INREG(SDNode *N);
244     SDValue visitFP_EXTEND(SDNode *N);
245     SDValue visitFNEG(SDNode *N);
246     SDValue visitFABS(SDNode *N);
247     SDValue visitFCEIL(SDNode *N);
248     SDValue visitFTRUNC(SDNode *N);
249     SDValue visitFFLOOR(SDNode *N);
250     SDValue visitBRCOND(SDNode *N);
251     SDValue visitBR_CC(SDNode *N);
252     SDValue visitLOAD(SDNode *N);
253     SDValue visitSTORE(SDNode *N);
254     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256     SDValue visitBUILD_VECTOR(SDNode *N);
257     SDValue visitCONCAT_VECTORS(SDNode *N);
258     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259     SDValue visitVECTOR_SHUFFLE(SDNode *N);
260
261     SDValue XformToShuffleWithZero(SDNode *N);
262     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
263
264     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
265
266     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270                              SDValue N3, ISD::CondCode CC,
271                              bool NotExtCompare = false);
272     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273                           SDLoc DL, bool foldBooleans = true);
274     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
275                                          unsigned HiOp);
276     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278     SDValue BuildSDIV(SDNode *N);
279     SDValue BuildUDIV(SDNode *N);
280     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281                                bool DemandHighBits = true);
282     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
284                               SDValue InnerPos, SDValue InnerNeg,
285                               unsigned PosOpcode, unsigned NegOpcode,
286                               SDLoc DL);
287     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
288     SDValue ReduceLoadWidth(SDNode *N);
289     SDValue ReduceLoadOpStoreWidth(SDNode *N);
290     SDValue TransformFPLoadStorePair(SDNode *N);
291     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
292     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
293
294     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
295
296     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
297     /// looking for aliasing nodes and adding them to the Aliases vector.
298     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
299                           SmallVectorImpl<SDValue> &Aliases);
300
301     /// isAlias - Return true if there is any possibility that the two addresses
302     /// overlap.
303     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
304                  const Value *SrcValue1, int SrcValueOffset1,
305                  unsigned SrcValueAlign1,
306                  const MDNode *TBAAInfo1,
307                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
308                  const Value *SrcValue2, int SrcValueOffset2,
309                  unsigned SrcValueAlign2,
310                  const MDNode *TBAAInfo2) const;
311
312     /// isAlias - Return true if there is any possibility that the two addresses
313     /// overlap.
314     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
315
316     /// FindAliasInfo - Extracts the relevant alias information from the memory
317     /// node.  Returns true if the operand was a load.
318     bool FindAliasInfo(SDNode *N,
319                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
320                        const Value *&SrcValue, int &SrcValueOffset,
321                        unsigned &SrcValueAlignment,
322                        const MDNode *&TBAAInfo) const;
323
324     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
325     /// looking for a better chain (aliasing node.)
326     SDValue FindBetterChain(SDNode *N, SDValue Chain);
327
328     /// Merge consecutive store operations into a wide store.
329     /// This optimization uses wide integers or vectors when possible.
330     /// \return True if some memory operations were changed.
331     bool MergeConsecutiveStores(StoreSDNode *N);
332
333   public:
334     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
335         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
336           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
337       AttributeSet FnAttrs =
338           DAG.getMachineFunction().getFunction()->getAttributes();
339       ForCodeSize =
340           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
341                                Attribute::OptimizeForSize) ||
342           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
343     }
344
345     /// Run - runs the dag combiner on all nodes in the work list
346     void Run(CombineLevel AtLevel);
347
348     SelectionDAG &getDAG() const { return DAG; }
349
350     /// getShiftAmountTy - Returns a type large enough to hold any valid
351     /// shift amount - before type legalization these can be huge.
352     EVT getShiftAmountTy(EVT LHSTy) {
353       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
354       if (LHSTy.isVector())
355         return LHSTy;
356       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
357                         : TLI.getPointerTy();
358     }
359
360     /// isTypeLegal - This method returns true if we are running before type
361     /// legalization or if the specified VT is legal.
362     bool isTypeLegal(const EVT &VT) {
363       if (!LegalTypes) return true;
364       return TLI.isTypeLegal(VT);
365     }
366
367     /// getSetCCResultType - Convenience wrapper around
368     /// TargetLowering::getSetCCResultType
369     EVT getSetCCResultType(EVT VT) const {
370       return TLI.getSetCCResultType(*DAG.getContext(), VT);
371     }
372   };
373 }
374
375
376 namespace {
377 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
378 /// nodes from the worklist.
379 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
380   DAGCombiner &DC;
381 public:
382   explicit WorkListRemover(DAGCombiner &dc)
383     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
384
385   virtual void NodeDeleted(SDNode *N, SDNode *E) {
386     DC.removeFromWorkList(N);
387   }
388 };
389 }
390
391 //===----------------------------------------------------------------------===//
392 //  TargetLowering::DAGCombinerInfo implementation
393 //===----------------------------------------------------------------------===//
394
395 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
396   ((DAGCombiner*)DC)->AddToWorkList(N);
397 }
398
399 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
400   ((DAGCombiner*)DC)->removeFromWorkList(N);
401 }
402
403 SDValue TargetLowering::DAGCombinerInfo::
404 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
405   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
406 }
407
408 SDValue TargetLowering::DAGCombinerInfo::
409 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
410   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
411 }
412
413
414 SDValue TargetLowering::DAGCombinerInfo::
415 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
416   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
417 }
418
419 void TargetLowering::DAGCombinerInfo::
420 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
421   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
422 }
423
424 //===----------------------------------------------------------------------===//
425 // Helper Functions
426 //===----------------------------------------------------------------------===//
427
428 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
429 /// specified expression for the same cost as the expression itself, or 2 if we
430 /// can compute the negated form more cheaply than the expression itself.
431 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
432                                const TargetLowering &TLI,
433                                const TargetOptions *Options,
434                                unsigned Depth = 0) {
435   // fneg is removable even if it has multiple uses.
436   if (Op.getOpcode() == ISD::FNEG) return 2;
437
438   // Don't allow anything with multiple uses.
439   if (!Op.hasOneUse()) return 0;
440
441   // Don't recurse exponentially.
442   if (Depth > 6) return 0;
443
444   switch (Op.getOpcode()) {
445   default: return false;
446   case ISD::ConstantFP:
447     // Don't invert constant FP values after legalize.  The negated constant
448     // isn't necessarily legal.
449     return LegalOperations ? 0 : 1;
450   case ISD::FADD:
451     // FIXME: determine better conditions for this xform.
452     if (!Options->UnsafeFPMath) return 0;
453
454     // After operation legalization, it might not be legal to create new FSUBs.
455     if (LegalOperations &&
456         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
457       return 0;
458
459     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
460     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
461                                     Options, Depth + 1))
462       return V;
463     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
464     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
465                               Depth + 1);
466   case ISD::FSUB:
467     // We can't turn -(A-B) into B-A when we honor signed zeros.
468     if (!Options->UnsafeFPMath) return 0;
469
470     // fold (fneg (fsub A, B)) -> (fsub B, A)
471     return 1;
472
473   case ISD::FMUL:
474   case ISD::FDIV:
475     if (Options->HonorSignDependentRoundingFPMath()) return 0;
476
477     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
478     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
479                                     Options, Depth + 1))
480       return V;
481
482     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
483                               Depth + 1);
484
485   case ISD::FP_EXTEND:
486   case ISD::FP_ROUND:
487   case ISD::FSIN:
488     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
489                               Depth + 1);
490   }
491 }
492
493 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
494 /// returns the newly negated expression.
495 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
496                                     bool LegalOperations, unsigned Depth = 0) {
497   // fneg is removable even if it has multiple uses.
498   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
499
500   // Don't allow anything with multiple uses.
501   assert(Op.hasOneUse() && "Unknown reuse!");
502
503   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
504   switch (Op.getOpcode()) {
505   default: llvm_unreachable("Unknown code");
506   case ISD::ConstantFP: {
507     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
508     V.changeSign();
509     return DAG.getConstantFP(V, Op.getValueType());
510   }
511   case ISD::FADD:
512     // FIXME: determine better conditions for this xform.
513     assert(DAG.getTarget().Options.UnsafeFPMath);
514
515     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
516     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
517                            DAG.getTargetLoweringInfo(),
518                            &DAG.getTarget().Options, Depth+1))
519       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
520                          GetNegatedExpression(Op.getOperand(0), DAG,
521                                               LegalOperations, Depth+1),
522                          Op.getOperand(1));
523     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
525                        GetNegatedExpression(Op.getOperand(1), DAG,
526                                             LegalOperations, Depth+1),
527                        Op.getOperand(0));
528   case ISD::FSUB:
529     // We can't turn -(A-B) into B-A when we honor signed zeros.
530     assert(DAG.getTarget().Options.UnsafeFPMath);
531
532     // fold (fneg (fsub 0, B)) -> B
533     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
534       if (N0CFP->getValueAPF().isZero())
535         return Op.getOperand(1);
536
537     // fold (fneg (fsub A, B)) -> (fsub B, A)
538     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
539                        Op.getOperand(1), Op.getOperand(0));
540
541   case ISD::FMUL:
542   case ISD::FDIV:
543     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
544
545     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
546     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
547                            DAG.getTargetLoweringInfo(),
548                            &DAG.getTarget().Options, Depth+1))
549       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
550                          GetNegatedExpression(Op.getOperand(0), DAG,
551                                               LegalOperations, Depth+1),
552                          Op.getOperand(1));
553
554     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
555     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
556                        Op.getOperand(0),
557                        GetNegatedExpression(Op.getOperand(1), DAG,
558                                             LegalOperations, Depth+1));
559
560   case ISD::FP_EXTEND:
561   case ISD::FSIN:
562     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563                        GetNegatedExpression(Op.getOperand(0), DAG,
564                                             LegalOperations, Depth+1));
565   case ISD::FP_ROUND:
566       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
567                          GetNegatedExpression(Op.getOperand(0), DAG,
568                                               LegalOperations, Depth+1),
569                          Op.getOperand(1));
570   }
571 }
572
573
574 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
575 // that selects between the values 1 and 0, making it equivalent to a setcc.
576 // Also, set the incoming LHS, RHS, and CC references to the appropriate
577 // nodes based on the type of node we are checking.  This simplifies life a
578 // bit for the callers.
579 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
580                               SDValue &CC) {
581   if (N.getOpcode() == ISD::SETCC) {
582     LHS = N.getOperand(0);
583     RHS = N.getOperand(1);
584     CC  = N.getOperand(2);
585     return true;
586   }
587   if (N.getOpcode() == ISD::SELECT_CC &&
588       N.getOperand(2).getOpcode() == ISD::Constant &&
589       N.getOperand(3).getOpcode() == ISD::Constant &&
590       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
591       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
592     LHS = N.getOperand(0);
593     RHS = N.getOperand(1);
594     CC  = N.getOperand(4);
595     return true;
596   }
597   return false;
598 }
599
600 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
601 // one use.  If this is true, it allows the users to invert the operation for
602 // free when it is profitable to do so.
603 static bool isOneUseSetCC(SDValue N) {
604   SDValue N0, N1, N2;
605   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
606     return true;
607   return false;
608 }
609
610 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
611                                     SDValue N0, SDValue N1) {
612   EVT VT = N0.getValueType();
613   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
614     if (isa<ConstantSDNode>(N1)) {
615       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
616       SDValue OpNode =
617         DAG.FoldConstantArithmetic(Opc, VT,
618                                    cast<ConstantSDNode>(N0.getOperand(1)),
619                                    cast<ConstantSDNode>(N1));
620       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
621     }
622     if (N0.hasOneUse()) {
623       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
624       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
625                                    N0.getOperand(0), N1);
626       AddToWorkList(OpNode.getNode());
627       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
628     }
629   }
630
631   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
632     if (isa<ConstantSDNode>(N0)) {
633       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
634       SDValue OpNode =
635         DAG.FoldConstantArithmetic(Opc, VT,
636                                    cast<ConstantSDNode>(N1.getOperand(1)),
637                                    cast<ConstantSDNode>(N0));
638       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
639     }
640     if (N1.hasOneUse()) {
641       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
642       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
643                                    N1.getOperand(0), N0);
644       AddToWorkList(OpNode.getNode());
645       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
646     }
647   }
648
649   return SDValue();
650 }
651
652 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
653                                bool AddTo) {
654   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
655   ++NodesCombined;
656   DEBUG(dbgs() << "\nReplacing.1 ";
657         N->dump(&DAG);
658         dbgs() << "\nWith: ";
659         To[0].getNode()->dump(&DAG);
660         dbgs() << " and " << NumTo-1 << " other values\n";
661         for (unsigned i = 0, e = NumTo; i != e; ++i)
662           assert((!To[i].getNode() ||
663                   N->getValueType(i) == To[i].getValueType()) &&
664                  "Cannot combine value to value of different type!"));
665   WorkListRemover DeadNodes(*this);
666   DAG.ReplaceAllUsesWith(N, To);
667   if (AddTo) {
668     // Push the new nodes and any users onto the worklist
669     for (unsigned i = 0, e = NumTo; i != e; ++i) {
670       if (To[i].getNode()) {
671         AddToWorkList(To[i].getNode());
672         AddUsersToWorkList(To[i].getNode());
673       }
674     }
675   }
676
677   // Finally, if the node is now dead, remove it from the graph.  The node
678   // may not be dead if the replacement process recursively simplified to
679   // something else needing this node.
680   if (N->use_empty()) {
681     // Nodes can be reintroduced into the worklist.  Make sure we do not
682     // process a node that has been replaced.
683     removeFromWorkList(N);
684
685     // Finally, since the node is now dead, remove it from the graph.
686     DAG.DeleteNode(N);
687   }
688   return SDValue(N, 0);
689 }
690
691 void DAGCombiner::
692 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
693   // Replace all uses.  If any nodes become isomorphic to other nodes and
694   // are deleted, make sure to remove them from our worklist.
695   WorkListRemover DeadNodes(*this);
696   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
697
698   // Push the new node and any (possibly new) users onto the worklist.
699   AddToWorkList(TLO.New.getNode());
700   AddUsersToWorkList(TLO.New.getNode());
701
702   // Finally, if the node is now dead, remove it from the graph.  The node
703   // may not be dead if the replacement process recursively simplified to
704   // something else needing this node.
705   if (TLO.Old.getNode()->use_empty()) {
706     removeFromWorkList(TLO.Old.getNode());
707
708     // If the operands of this node are only used by the node, they will now
709     // be dead.  Make sure to visit them first to delete dead nodes early.
710     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
711       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
712         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
713
714     DAG.DeleteNode(TLO.Old.getNode());
715   }
716 }
717
718 /// SimplifyDemandedBits - Check the specified integer node value to see if
719 /// it can be simplified or if things it uses can be simplified by bit
720 /// propagation.  If so, return true.
721 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
722   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
723   APInt KnownZero, KnownOne;
724   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
725     return false;
726
727   // Revisit the node.
728   AddToWorkList(Op.getNode());
729
730   // Replace the old value with the new one.
731   ++NodesCombined;
732   DEBUG(dbgs() << "\nReplacing.2 ";
733         TLO.Old.getNode()->dump(&DAG);
734         dbgs() << "\nWith: ";
735         TLO.New.getNode()->dump(&DAG);
736         dbgs() << '\n');
737
738   CommitTargetLoweringOpt(TLO);
739   return true;
740 }
741
742 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
743   SDLoc dl(Load);
744   EVT VT = Load->getValueType(0);
745   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
746
747   DEBUG(dbgs() << "\nReplacing.9 ";
748         Load->dump(&DAG);
749         dbgs() << "\nWith: ";
750         Trunc.getNode()->dump(&DAG);
751         dbgs() << '\n');
752   WorkListRemover DeadNodes(*this);
753   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
754   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
755   removeFromWorkList(Load);
756   DAG.DeleteNode(Load);
757   AddToWorkList(Trunc.getNode());
758 }
759
760 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
761   Replace = false;
762   SDLoc dl(Op);
763   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
764     EVT MemVT = LD->getMemoryVT();
765     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
766       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
767                                                   : ISD::EXTLOAD)
768       : LD->getExtensionType();
769     Replace = true;
770     return DAG.getExtLoad(ExtType, dl, PVT,
771                           LD->getChain(), LD->getBasePtr(),
772                           MemVT, LD->getMemOperand());
773   }
774
775   unsigned Opc = Op.getOpcode();
776   switch (Opc) {
777   default: break;
778   case ISD::AssertSext:
779     return DAG.getNode(ISD::AssertSext, dl, PVT,
780                        SExtPromoteOperand(Op.getOperand(0), PVT),
781                        Op.getOperand(1));
782   case ISD::AssertZext:
783     return DAG.getNode(ISD::AssertZext, dl, PVT,
784                        ZExtPromoteOperand(Op.getOperand(0), PVT),
785                        Op.getOperand(1));
786   case ISD::Constant: {
787     unsigned ExtOpc =
788       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
789     return DAG.getNode(ExtOpc, dl, PVT, Op);
790   }
791   }
792
793   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
794     return SDValue();
795   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
796 }
797
798 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
799   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
800     return SDValue();
801   EVT OldVT = Op.getValueType();
802   SDLoc dl(Op);
803   bool Replace = false;
804   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
805   if (NewOp.getNode() == 0)
806     return SDValue();
807   AddToWorkList(NewOp.getNode());
808
809   if (Replace)
810     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
811   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
812                      DAG.getValueType(OldVT));
813 }
814
815 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
816   EVT OldVT = Op.getValueType();
817   SDLoc dl(Op);
818   bool Replace = false;
819   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
820   if (NewOp.getNode() == 0)
821     return SDValue();
822   AddToWorkList(NewOp.getNode());
823
824   if (Replace)
825     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
826   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
827 }
828
829 /// PromoteIntBinOp - Promote the specified integer binary operation if the
830 /// target indicates it is beneficial. e.g. On x86, it's usually better to
831 /// promote i16 operations to i32 since i16 instructions are longer.
832 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
833   if (!LegalOperations)
834     return SDValue();
835
836   EVT VT = Op.getValueType();
837   if (VT.isVector() || !VT.isInteger())
838     return SDValue();
839
840   // If operation type is 'undesirable', e.g. i16 on x86, consider
841   // promoting it.
842   unsigned Opc = Op.getOpcode();
843   if (TLI.isTypeDesirableForOp(Opc, VT))
844     return SDValue();
845
846   EVT PVT = VT;
847   // Consult target whether it is a good idea to promote this operation and
848   // what's the right type to promote it to.
849   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
850     assert(PVT != VT && "Don't know what type to promote to!");
851
852     bool Replace0 = false;
853     SDValue N0 = Op.getOperand(0);
854     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
855     if (NN0.getNode() == 0)
856       return SDValue();
857
858     bool Replace1 = false;
859     SDValue N1 = Op.getOperand(1);
860     SDValue NN1;
861     if (N0 == N1)
862       NN1 = NN0;
863     else {
864       NN1 = PromoteOperand(N1, PVT, Replace1);
865       if (NN1.getNode() == 0)
866         return SDValue();
867     }
868
869     AddToWorkList(NN0.getNode());
870     if (NN1.getNode())
871       AddToWorkList(NN1.getNode());
872
873     if (Replace0)
874       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
875     if (Replace1)
876       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
877
878     DEBUG(dbgs() << "\nPromoting ";
879           Op.getNode()->dump(&DAG));
880     SDLoc dl(Op);
881     return DAG.getNode(ISD::TRUNCATE, dl, VT,
882                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
883   }
884   return SDValue();
885 }
886
887 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
888 /// target indicates it is beneficial. e.g. On x86, it's usually better to
889 /// promote i16 operations to i32 since i16 instructions are longer.
890 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
891   if (!LegalOperations)
892     return SDValue();
893
894   EVT VT = Op.getValueType();
895   if (VT.isVector() || !VT.isInteger())
896     return SDValue();
897
898   // If operation type is 'undesirable', e.g. i16 on x86, consider
899   // promoting it.
900   unsigned Opc = Op.getOpcode();
901   if (TLI.isTypeDesirableForOp(Opc, VT))
902     return SDValue();
903
904   EVT PVT = VT;
905   // Consult target whether it is a good idea to promote this operation and
906   // what's the right type to promote it to.
907   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908     assert(PVT != VT && "Don't know what type to promote to!");
909
910     bool Replace = false;
911     SDValue N0 = Op.getOperand(0);
912     if (Opc == ISD::SRA)
913       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
914     else if (Opc == ISD::SRL)
915       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
916     else
917       N0 = PromoteOperand(N0, PVT, Replace);
918     if (N0.getNode() == 0)
919       return SDValue();
920
921     AddToWorkList(N0.getNode());
922     if (Replace)
923       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
924
925     DEBUG(dbgs() << "\nPromoting ";
926           Op.getNode()->dump(&DAG));
927     SDLoc dl(Op);
928     return DAG.getNode(ISD::TRUNCATE, dl, VT,
929                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
930   }
931   return SDValue();
932 }
933
934 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
935   if (!LegalOperations)
936     return SDValue();
937
938   EVT VT = Op.getValueType();
939   if (VT.isVector() || !VT.isInteger())
940     return SDValue();
941
942   // If operation type is 'undesirable', e.g. i16 on x86, consider
943   // promoting it.
944   unsigned Opc = Op.getOpcode();
945   if (TLI.isTypeDesirableForOp(Opc, VT))
946     return SDValue();
947
948   EVT PVT = VT;
949   // Consult target whether it is a good idea to promote this operation and
950   // what's the right type to promote it to.
951   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
952     assert(PVT != VT && "Don't know what type to promote to!");
953     // fold (aext (aext x)) -> (aext x)
954     // fold (aext (zext x)) -> (zext x)
955     // fold (aext (sext x)) -> (sext x)
956     DEBUG(dbgs() << "\nPromoting ";
957           Op.getNode()->dump(&DAG));
958     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
959   }
960   return SDValue();
961 }
962
963 bool DAGCombiner::PromoteLoad(SDValue Op) {
964   if (!LegalOperations)
965     return false;
966
967   EVT VT = Op.getValueType();
968   if (VT.isVector() || !VT.isInteger())
969     return false;
970
971   // If operation type is 'undesirable', e.g. i16 on x86, consider
972   // promoting it.
973   unsigned Opc = Op.getOpcode();
974   if (TLI.isTypeDesirableForOp(Opc, VT))
975     return false;
976
977   EVT PVT = VT;
978   // Consult target whether it is a good idea to promote this operation and
979   // what's the right type to promote it to.
980   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
981     assert(PVT != VT && "Don't know what type to promote to!");
982
983     SDLoc dl(Op);
984     SDNode *N = Op.getNode();
985     LoadSDNode *LD = cast<LoadSDNode>(N);
986     EVT MemVT = LD->getMemoryVT();
987     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
988       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
989                                                   : ISD::EXTLOAD)
990       : LD->getExtensionType();
991     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
992                                    LD->getChain(), LD->getBasePtr(),
993                                    MemVT, LD->getMemOperand());
994     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
995
996     DEBUG(dbgs() << "\nPromoting ";
997           N->dump(&DAG);
998           dbgs() << "\nTo: ";
999           Result.getNode()->dump(&DAG);
1000           dbgs() << '\n');
1001     WorkListRemover DeadNodes(*this);
1002     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1003     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1004     removeFromWorkList(N);
1005     DAG.DeleteNode(N);
1006     AddToWorkList(Result.getNode());
1007     return true;
1008   }
1009   return false;
1010 }
1011
1012
1013 //===----------------------------------------------------------------------===//
1014 //  Main DAG Combiner implementation
1015 //===----------------------------------------------------------------------===//
1016
1017 void DAGCombiner::Run(CombineLevel AtLevel) {
1018   // set the instance variables, so that the various visit routines may use it.
1019   Level = AtLevel;
1020   LegalOperations = Level >= AfterLegalizeVectorOps;
1021   LegalTypes = Level >= AfterLegalizeTypes;
1022
1023   // Add all the dag nodes to the worklist.
1024   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1025        E = DAG.allnodes_end(); I != E; ++I)
1026     AddToWorkList(I);
1027
1028   // Create a dummy node (which is not added to allnodes), that adds a reference
1029   // to the root node, preventing it from being deleted, and tracking any
1030   // changes of the root.
1031   HandleSDNode Dummy(DAG.getRoot());
1032
1033   // The root of the dag may dangle to deleted nodes until the dag combiner is
1034   // done.  Set it to null to avoid confusion.
1035   DAG.setRoot(SDValue());
1036
1037   // while the worklist isn't empty, find a node and
1038   // try and combine it.
1039   while (!WorkListContents.empty()) {
1040     SDNode *N;
1041     // The WorkListOrder holds the SDNodes in order, but it may contain
1042     // duplicates.
1043     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1044     // worklist *should* contain, and check the node we want to visit is should
1045     // actually be visited.
1046     do {
1047       N = WorkListOrder.pop_back_val();
1048     } while (!WorkListContents.erase(N));
1049
1050     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1051     // N is deleted from the DAG, since they too may now be dead or may have a
1052     // reduced number of uses, allowing other xforms.
1053     if (N->use_empty() && N != &Dummy) {
1054       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1055         AddToWorkList(N->getOperand(i).getNode());
1056
1057       DAG.DeleteNode(N);
1058       continue;
1059     }
1060
1061     SDValue RV = combine(N);
1062
1063     if (RV.getNode() == 0)
1064       continue;
1065
1066     ++NodesCombined;
1067
1068     // If we get back the same node we passed in, rather than a new node or
1069     // zero, we know that the node must have defined multiple values and
1070     // CombineTo was used.  Since CombineTo takes care of the worklist
1071     // mechanics for us, we have no work to do in this case.
1072     if (RV.getNode() == N)
1073       continue;
1074
1075     assert(N->getOpcode() != ISD::DELETED_NODE &&
1076            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1077            "Node was deleted but visit returned new node!");
1078
1079     DEBUG(dbgs() << "\nReplacing.3 ";
1080           N->dump(&DAG);
1081           dbgs() << "\nWith: ";
1082           RV.getNode()->dump(&DAG);
1083           dbgs() << '\n');
1084
1085     // Transfer debug value.
1086     DAG.TransferDbgValues(SDValue(N, 0), RV);
1087     WorkListRemover DeadNodes(*this);
1088     if (N->getNumValues() == RV.getNode()->getNumValues())
1089       DAG.ReplaceAllUsesWith(N, RV.getNode());
1090     else {
1091       assert(N->getValueType(0) == RV.getValueType() &&
1092              N->getNumValues() == 1 && "Type mismatch");
1093       SDValue OpV = RV;
1094       DAG.ReplaceAllUsesWith(N, &OpV);
1095     }
1096
1097     // Push the new node and any users onto the worklist
1098     AddToWorkList(RV.getNode());
1099     AddUsersToWorkList(RV.getNode());
1100
1101     // Add any uses of the old node to the worklist in case this node is the
1102     // last one that uses them.  They may become dead after this node is
1103     // deleted.
1104     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1105       AddToWorkList(N->getOperand(i).getNode());
1106
1107     // Finally, if the node is now dead, remove it from the graph.  The node
1108     // may not be dead if the replacement process recursively simplified to
1109     // something else needing this node.
1110     if (N->use_empty()) {
1111       // Nodes can be reintroduced into the worklist.  Make sure we do not
1112       // process a node that has been replaced.
1113       removeFromWorkList(N);
1114
1115       // Finally, since the node is now dead, remove it from the graph.
1116       DAG.DeleteNode(N);
1117     }
1118   }
1119
1120   // If the root changed (e.g. it was a dead load, update the root).
1121   DAG.setRoot(Dummy.getValue());
1122   DAG.RemoveDeadNodes();
1123 }
1124
1125 SDValue DAGCombiner::visit(SDNode *N) {
1126   switch (N->getOpcode()) {
1127   default: break;
1128   case ISD::TokenFactor:        return visitTokenFactor(N);
1129   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1130   case ISD::ADD:                return visitADD(N);
1131   case ISD::SUB:                return visitSUB(N);
1132   case ISD::ADDC:               return visitADDC(N);
1133   case ISD::SUBC:               return visitSUBC(N);
1134   case ISD::ADDE:               return visitADDE(N);
1135   case ISD::SUBE:               return visitSUBE(N);
1136   case ISD::MUL:                return visitMUL(N);
1137   case ISD::SDIV:               return visitSDIV(N);
1138   case ISD::UDIV:               return visitUDIV(N);
1139   case ISD::SREM:               return visitSREM(N);
1140   case ISD::UREM:               return visitUREM(N);
1141   case ISD::MULHU:              return visitMULHU(N);
1142   case ISD::MULHS:              return visitMULHS(N);
1143   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1144   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1145   case ISD::SMULO:              return visitSMULO(N);
1146   case ISD::UMULO:              return visitUMULO(N);
1147   case ISD::SDIVREM:            return visitSDIVREM(N);
1148   case ISD::UDIVREM:            return visitUDIVREM(N);
1149   case ISD::AND:                return visitAND(N);
1150   case ISD::OR:                 return visitOR(N);
1151   case ISD::XOR:                return visitXOR(N);
1152   case ISD::SHL:                return visitSHL(N);
1153   case ISD::SRA:                return visitSRA(N);
1154   case ISD::SRL:                return visitSRL(N);
1155   case ISD::CTLZ:               return visitCTLZ(N);
1156   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1157   case ISD::CTTZ:               return visitCTTZ(N);
1158   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1159   case ISD::CTPOP:              return visitCTPOP(N);
1160   case ISD::SELECT:             return visitSELECT(N);
1161   case ISD::VSELECT:            return visitVSELECT(N);
1162   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1163   case ISD::SETCC:              return visitSETCC(N);
1164   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1165   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1166   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1167   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1168   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1169   case ISD::BITCAST:            return visitBITCAST(N);
1170   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1171   case ISD::FADD:               return visitFADD(N);
1172   case ISD::FSUB:               return visitFSUB(N);
1173   case ISD::FMUL:               return visitFMUL(N);
1174   case ISD::FMA:                return visitFMA(N);
1175   case ISD::FDIV:               return visitFDIV(N);
1176   case ISD::FREM:               return visitFREM(N);
1177   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1178   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1179   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1180   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1181   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1182   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1183   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1184   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1185   case ISD::FNEG:               return visitFNEG(N);
1186   case ISD::FABS:               return visitFABS(N);
1187   case ISD::FFLOOR:             return visitFFLOOR(N);
1188   case ISD::FCEIL:              return visitFCEIL(N);
1189   case ISD::FTRUNC:             return visitFTRUNC(N);
1190   case ISD::BRCOND:             return visitBRCOND(N);
1191   case ISD::BR_CC:              return visitBR_CC(N);
1192   case ISD::LOAD:               return visitLOAD(N);
1193   case ISD::STORE:              return visitSTORE(N);
1194   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1195   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1196   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1197   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1198   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1199   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1200   }
1201   return SDValue();
1202 }
1203
1204 SDValue DAGCombiner::combine(SDNode *N) {
1205   SDValue RV = visit(N);
1206
1207   // If nothing happened, try a target-specific DAG combine.
1208   if (RV.getNode() == 0) {
1209     assert(N->getOpcode() != ISD::DELETED_NODE &&
1210            "Node was deleted but visit returned NULL!");
1211
1212     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1213         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1214
1215       // Expose the DAG combiner to the target combiner impls.
1216       TargetLowering::DAGCombinerInfo
1217         DagCombineInfo(DAG, Level, false, this);
1218
1219       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1220     }
1221   }
1222
1223   // If nothing happened still, try promoting the operation.
1224   if (RV.getNode() == 0) {
1225     switch (N->getOpcode()) {
1226     default: break;
1227     case ISD::ADD:
1228     case ISD::SUB:
1229     case ISD::MUL:
1230     case ISD::AND:
1231     case ISD::OR:
1232     case ISD::XOR:
1233       RV = PromoteIntBinOp(SDValue(N, 0));
1234       break;
1235     case ISD::SHL:
1236     case ISD::SRA:
1237     case ISD::SRL:
1238       RV = PromoteIntShiftOp(SDValue(N, 0));
1239       break;
1240     case ISD::SIGN_EXTEND:
1241     case ISD::ZERO_EXTEND:
1242     case ISD::ANY_EXTEND:
1243       RV = PromoteExtend(SDValue(N, 0));
1244       break;
1245     case ISD::LOAD:
1246       if (PromoteLoad(SDValue(N, 0)))
1247         RV = SDValue(N, 0);
1248       break;
1249     }
1250   }
1251
1252   // If N is a commutative binary node, try commuting it to enable more
1253   // sdisel CSE.
1254   if (RV.getNode() == 0 &&
1255       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1256       N->getNumValues() == 1) {
1257     SDValue N0 = N->getOperand(0);
1258     SDValue N1 = N->getOperand(1);
1259
1260     // Constant operands are canonicalized to RHS.
1261     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1262       SDValue Ops[] = { N1, N0 };
1263       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1264                                             Ops, 2);
1265       if (CSENode)
1266         return SDValue(CSENode, 0);
1267     }
1268   }
1269
1270   return RV;
1271 }
1272
1273 /// getInputChainForNode - Given a node, return its input chain if it has one,
1274 /// otherwise return a null sd operand.
1275 static SDValue getInputChainForNode(SDNode *N) {
1276   if (unsigned NumOps = N->getNumOperands()) {
1277     if (N->getOperand(0).getValueType() == MVT::Other)
1278       return N->getOperand(0);
1279     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1280       return N->getOperand(NumOps-1);
1281     for (unsigned i = 1; i < NumOps-1; ++i)
1282       if (N->getOperand(i).getValueType() == MVT::Other)
1283         return N->getOperand(i);
1284   }
1285   return SDValue();
1286 }
1287
1288 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1289   // If N has two operands, where one has an input chain equal to the other,
1290   // the 'other' chain is redundant.
1291   if (N->getNumOperands() == 2) {
1292     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1293       return N->getOperand(0);
1294     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1295       return N->getOperand(1);
1296   }
1297
1298   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1299   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1300   SmallPtrSet<SDNode*, 16> SeenOps;
1301   bool Changed = false;             // If we should replace this token factor.
1302
1303   // Start out with this token factor.
1304   TFs.push_back(N);
1305
1306   // Iterate through token factors.  The TFs grows when new token factors are
1307   // encountered.
1308   for (unsigned i = 0; i < TFs.size(); ++i) {
1309     SDNode *TF = TFs[i];
1310
1311     // Check each of the operands.
1312     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1313       SDValue Op = TF->getOperand(i);
1314
1315       switch (Op.getOpcode()) {
1316       case ISD::EntryToken:
1317         // Entry tokens don't need to be added to the list. They are
1318         // rededundant.
1319         Changed = true;
1320         break;
1321
1322       case ISD::TokenFactor:
1323         if (Op.hasOneUse() &&
1324             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1325           // Queue up for processing.
1326           TFs.push_back(Op.getNode());
1327           // Clean up in case the token factor is removed.
1328           AddToWorkList(Op.getNode());
1329           Changed = true;
1330           break;
1331         }
1332         // Fall thru
1333
1334       default:
1335         // Only add if it isn't already in the list.
1336         if (SeenOps.insert(Op.getNode()))
1337           Ops.push_back(Op);
1338         else
1339           Changed = true;
1340         break;
1341       }
1342     }
1343   }
1344
1345   SDValue Result;
1346
1347   // If we've change things around then replace token factor.
1348   if (Changed) {
1349     if (Ops.empty()) {
1350       // The entry token is the only possible outcome.
1351       Result = DAG.getEntryNode();
1352     } else {
1353       // New and improved token factor.
1354       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1355                            MVT::Other, &Ops[0], Ops.size());
1356     }
1357
1358     // Don't add users to work list.
1359     return CombineTo(N, Result, false);
1360   }
1361
1362   return Result;
1363 }
1364
1365 /// MERGE_VALUES can always be eliminated.
1366 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1367   WorkListRemover DeadNodes(*this);
1368   // Replacing results may cause a different MERGE_VALUES to suddenly
1369   // be CSE'd with N, and carry its uses with it. Iterate until no
1370   // uses remain, to ensure that the node can be safely deleted.
1371   // First add the users of this node to the work list so that they
1372   // can be tried again once they have new operands.
1373   AddUsersToWorkList(N);
1374   do {
1375     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1376       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1377   } while (!N->use_empty());
1378   removeFromWorkList(N);
1379   DAG.DeleteNode(N);
1380   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1381 }
1382
1383 static
1384 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1385                               SelectionDAG &DAG) {
1386   EVT VT = N0.getValueType();
1387   SDValue N00 = N0.getOperand(0);
1388   SDValue N01 = N0.getOperand(1);
1389   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1390
1391   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1392       isa<ConstantSDNode>(N00.getOperand(1))) {
1393     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1394     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1395                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1396                                  N00.getOperand(0), N01),
1397                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1398                                  N00.getOperand(1), N01));
1399     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1400   }
1401
1402   return SDValue();
1403 }
1404
1405 SDValue DAGCombiner::visitADD(SDNode *N) {
1406   SDValue N0 = N->getOperand(0);
1407   SDValue N1 = N->getOperand(1);
1408   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1409   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1410   EVT VT = N0.getValueType();
1411
1412   // fold vector ops
1413   if (VT.isVector()) {
1414     SDValue FoldedVOp = SimplifyVBinOp(N);
1415     if (FoldedVOp.getNode()) return FoldedVOp;
1416
1417     // fold (add x, 0) -> x, vector edition
1418     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1419       return N0;
1420     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1421       return N1;
1422   }
1423
1424   // fold (add x, undef) -> undef
1425   if (N0.getOpcode() == ISD::UNDEF)
1426     return N0;
1427   if (N1.getOpcode() == ISD::UNDEF)
1428     return N1;
1429   // fold (add c1, c2) -> c1+c2
1430   if (N0C && N1C)
1431     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1432   // canonicalize constant to RHS
1433   if (N0C && !N1C)
1434     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1435   // fold (add x, 0) -> x
1436   if (N1C && N1C->isNullValue())
1437     return N0;
1438   // fold (add Sym, c) -> Sym+c
1439   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1440     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1441         GA->getOpcode() == ISD::GlobalAddress)
1442       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1443                                   GA->getOffset() +
1444                                     (uint64_t)N1C->getSExtValue());
1445   // fold ((c1-A)+c2) -> (c1+c2)-A
1446   if (N1C && N0.getOpcode() == ISD::SUB)
1447     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1448       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1449                          DAG.getConstant(N1C->getAPIntValue()+
1450                                          N0C->getAPIntValue(), VT),
1451                          N0.getOperand(1));
1452   // reassociate add
1453   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1454   if (RADD.getNode() != 0)
1455     return RADD;
1456   // fold ((0-A) + B) -> B-A
1457   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1458       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1459     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1460   // fold (A + (0-B)) -> A-B
1461   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1462       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1463     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1464   // fold (A+(B-A)) -> B
1465   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1466     return N1.getOperand(0);
1467   // fold ((B-A)+A) -> B
1468   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1469     return N0.getOperand(0);
1470   // fold (A+(B-(A+C))) to (B-C)
1471   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1472       N0 == N1.getOperand(1).getOperand(0))
1473     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1474                        N1.getOperand(1).getOperand(1));
1475   // fold (A+(B-(C+A))) to (B-C)
1476   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1477       N0 == N1.getOperand(1).getOperand(1))
1478     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1479                        N1.getOperand(1).getOperand(0));
1480   // fold (A+((B-A)+or-C)) to (B+or-C)
1481   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1482       N1.getOperand(0).getOpcode() == ISD::SUB &&
1483       N0 == N1.getOperand(0).getOperand(1))
1484     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1485                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1486
1487   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1488   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1489     SDValue N00 = N0.getOperand(0);
1490     SDValue N01 = N0.getOperand(1);
1491     SDValue N10 = N1.getOperand(0);
1492     SDValue N11 = N1.getOperand(1);
1493
1494     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1495       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1496                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1497                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1498   }
1499
1500   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1501     return SDValue(N, 0);
1502
1503   // fold (a+b) -> (a|b) iff a and b share no bits.
1504   if (VT.isInteger() && !VT.isVector()) {
1505     APInt LHSZero, LHSOne;
1506     APInt RHSZero, RHSOne;
1507     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1508
1509     if (LHSZero.getBoolValue()) {
1510       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1511
1512       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1513       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1514       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1515         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1516     }
1517   }
1518
1519   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1520   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1521     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1522     if (Result.getNode()) return Result;
1523   }
1524   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1525     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1526     if (Result.getNode()) return Result;
1527   }
1528
1529   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1530   if (N1.getOpcode() == ISD::SHL &&
1531       N1.getOperand(0).getOpcode() == ISD::SUB)
1532     if (ConstantSDNode *C =
1533           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1534       if (C->getAPIntValue() == 0)
1535         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1536                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1537                                        N1.getOperand(0).getOperand(1),
1538                                        N1.getOperand(1)));
1539   if (N0.getOpcode() == ISD::SHL &&
1540       N0.getOperand(0).getOpcode() == ISD::SUB)
1541     if (ConstantSDNode *C =
1542           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1543       if (C->getAPIntValue() == 0)
1544         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1545                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1546                                        N0.getOperand(0).getOperand(1),
1547                                        N0.getOperand(1)));
1548
1549   if (N1.getOpcode() == ISD::AND) {
1550     SDValue AndOp0 = N1.getOperand(0);
1551     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1552     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1553     unsigned DestBits = VT.getScalarType().getSizeInBits();
1554
1555     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1556     // and similar xforms where the inner op is either ~0 or 0.
1557     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1558       SDLoc DL(N);
1559       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1560     }
1561   }
1562
1563   // add (sext i1), X -> sub X, (zext i1)
1564   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1565       N0.getOperand(0).getValueType() == MVT::i1 &&
1566       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1567     SDLoc DL(N);
1568     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1569     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1570   }
1571
1572   return SDValue();
1573 }
1574
1575 SDValue DAGCombiner::visitADDC(SDNode *N) {
1576   SDValue N0 = N->getOperand(0);
1577   SDValue N1 = N->getOperand(1);
1578   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1579   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1580   EVT VT = N0.getValueType();
1581
1582   // If the flag result is dead, turn this into an ADD.
1583   if (!N->hasAnyUseOfValue(1))
1584     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1585                      DAG.getNode(ISD::CARRY_FALSE,
1586                                  SDLoc(N), MVT::Glue));
1587
1588   // canonicalize constant to RHS.
1589   if (N0C && !N1C)
1590     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1591
1592   // fold (addc x, 0) -> x + no carry out
1593   if (N1C && N1C->isNullValue())
1594     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1595                                         SDLoc(N), MVT::Glue));
1596
1597   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1598   APInt LHSZero, LHSOne;
1599   APInt RHSZero, RHSOne;
1600   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1601
1602   if (LHSZero.getBoolValue()) {
1603     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1604
1605     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1606     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1607     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1608       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1609                        DAG.getNode(ISD::CARRY_FALSE,
1610                                    SDLoc(N), MVT::Glue));
1611   }
1612
1613   return SDValue();
1614 }
1615
1616 SDValue DAGCombiner::visitADDE(SDNode *N) {
1617   SDValue N0 = N->getOperand(0);
1618   SDValue N1 = N->getOperand(1);
1619   SDValue CarryIn = N->getOperand(2);
1620   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1621   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1622
1623   // canonicalize constant to RHS
1624   if (N0C && !N1C)
1625     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1626                        N1, N0, CarryIn);
1627
1628   // fold (adde x, y, false) -> (addc x, y)
1629   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1630     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1631
1632   return SDValue();
1633 }
1634
1635 // Since it may not be valid to emit a fold to zero for vector initializers
1636 // check if we can before folding.
1637 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1638                              SelectionDAG &DAG,
1639                              bool LegalOperations, bool LegalTypes) {
1640   if (!VT.isVector())
1641     return DAG.getConstant(0, VT);
1642   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1643     return DAG.getConstant(0, VT);
1644   return SDValue();
1645 }
1646
1647 SDValue DAGCombiner::visitSUB(SDNode *N) {
1648   SDValue N0 = N->getOperand(0);
1649   SDValue N1 = N->getOperand(1);
1650   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1651   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1652   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1653     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1654   EVT VT = N0.getValueType();
1655
1656   // fold vector ops
1657   if (VT.isVector()) {
1658     SDValue FoldedVOp = SimplifyVBinOp(N);
1659     if (FoldedVOp.getNode()) return FoldedVOp;
1660
1661     // fold (sub x, 0) -> x, vector edition
1662     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1663       return N0;
1664   }
1665
1666   // fold (sub x, x) -> 0
1667   // FIXME: Refactor this and xor and other similar operations together.
1668   if (N0 == N1)
1669     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1670   // fold (sub c1, c2) -> c1-c2
1671   if (N0C && N1C)
1672     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1673   // fold (sub x, c) -> (add x, -c)
1674   if (N1C)
1675     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1676                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1677   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1678   if (N0C && N0C->isAllOnesValue())
1679     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1680   // fold A-(A-B) -> B
1681   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1682     return N1.getOperand(1);
1683   // fold (A+B)-A -> B
1684   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1685     return N0.getOperand(1);
1686   // fold (A+B)-B -> A
1687   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1688     return N0.getOperand(0);
1689   // fold C2-(A+C1) -> (C2-C1)-A
1690   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1691     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1692                                    VT);
1693     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1694                        N1.getOperand(0));
1695   }
1696   // fold ((A+(B+or-C))-B) -> A+or-C
1697   if (N0.getOpcode() == ISD::ADD &&
1698       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1699        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1700       N0.getOperand(1).getOperand(0) == N1)
1701     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1702                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1703   // fold ((A+(C+B))-B) -> A+C
1704   if (N0.getOpcode() == ISD::ADD &&
1705       N0.getOperand(1).getOpcode() == ISD::ADD &&
1706       N0.getOperand(1).getOperand(1) == N1)
1707     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1708                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1709   // fold ((A-(B-C))-C) -> A-B
1710   if (N0.getOpcode() == ISD::SUB &&
1711       N0.getOperand(1).getOpcode() == ISD::SUB &&
1712       N0.getOperand(1).getOperand(1) == N1)
1713     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1714                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1715
1716   // If either operand of a sub is undef, the result is undef
1717   if (N0.getOpcode() == ISD::UNDEF)
1718     return N0;
1719   if (N1.getOpcode() == ISD::UNDEF)
1720     return N1;
1721
1722   // If the relocation model supports it, consider symbol offsets.
1723   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1724     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1725       // fold (sub Sym, c) -> Sym-c
1726       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1727         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1728                                     GA->getOffset() -
1729                                       (uint64_t)N1C->getSExtValue());
1730       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1731       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1732         if (GA->getGlobal() == GB->getGlobal())
1733           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1734                                  VT);
1735     }
1736
1737   return SDValue();
1738 }
1739
1740 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1741   SDValue N0 = N->getOperand(0);
1742   SDValue N1 = N->getOperand(1);
1743   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1745   EVT VT = N0.getValueType();
1746
1747   // If the flag result is dead, turn this into an SUB.
1748   if (!N->hasAnyUseOfValue(1))
1749     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1750                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1751                                  MVT::Glue));
1752
1753   // fold (subc x, x) -> 0 + no borrow
1754   if (N0 == N1)
1755     return CombineTo(N, DAG.getConstant(0, VT),
1756                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1757                                  MVT::Glue));
1758
1759   // fold (subc x, 0) -> x + no borrow
1760   if (N1C && N1C->isNullValue())
1761     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1762                                         MVT::Glue));
1763
1764   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1765   if (N0C && N0C->isAllOnesValue())
1766     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1767                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1768                                  MVT::Glue));
1769
1770   return SDValue();
1771 }
1772
1773 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1774   SDValue N0 = N->getOperand(0);
1775   SDValue N1 = N->getOperand(1);
1776   SDValue CarryIn = N->getOperand(2);
1777
1778   // fold (sube x, y, false) -> (subc x, y)
1779   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1780     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1781
1782   return SDValue();
1783 }
1784
1785 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1786 /// elements are all the same constant or undefined.
1787 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1788   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1789   if (!C)
1790     return false;
1791
1792   APInt SplatUndef;
1793   unsigned SplatBitSize;
1794   bool HasAnyUndefs;
1795   EVT EltVT = N->getValueType(0).getVectorElementType();
1796   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1797                              HasAnyUndefs) &&
1798           EltVT.getSizeInBits() >= SplatBitSize);
1799 }
1800
1801 SDValue DAGCombiner::visitMUL(SDNode *N) {
1802   SDValue N0 = N->getOperand(0);
1803   SDValue N1 = N->getOperand(1);
1804   EVT VT = N0.getValueType();
1805
1806   // fold (mul x, undef) -> 0
1807   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1808     return DAG.getConstant(0, VT);
1809
1810   bool N0IsConst = false;
1811   bool N1IsConst = false;
1812   APInt ConstValue0, ConstValue1;
1813   // fold vector ops
1814   if (VT.isVector()) {
1815     SDValue FoldedVOp = SimplifyVBinOp(N);
1816     if (FoldedVOp.getNode()) return FoldedVOp;
1817
1818     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1819     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1820   } else {
1821     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1822     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1823                             : APInt();
1824     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1825     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1826                             : APInt();
1827   }
1828
1829   // fold (mul c1, c2) -> c1*c2
1830   if (N0IsConst && N1IsConst)
1831     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1832
1833   // canonicalize constant to RHS
1834   if (N0IsConst && !N1IsConst)
1835     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1836   // fold (mul x, 0) -> 0
1837   if (N1IsConst && ConstValue1 == 0)
1838     return N1;
1839   // We require a splat of the entire scalar bit width for non-contiguous
1840   // bit patterns.
1841   bool IsFullSplat =
1842     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1843   // fold (mul x, 1) -> x
1844   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1845     return N0;
1846   // fold (mul x, -1) -> 0-x
1847   if (N1IsConst && ConstValue1.isAllOnesValue())
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        DAG.getConstant(0, VT), N0);
1850   // fold (mul x, (1 << c)) -> x << c
1851   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1852     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1853                        DAG.getConstant(ConstValue1.logBase2(),
1854                                        getShiftAmountTy(N0.getValueType())));
1855   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1856   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1857     unsigned Log2Val = (-ConstValue1).logBase2();
1858     // FIXME: If the input is something that is easily negated (e.g. a
1859     // single-use add), we should put the negate there.
1860     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1861                        DAG.getConstant(0, VT),
1862                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1863                             DAG.getConstant(Log2Val,
1864                                       getShiftAmountTy(N0.getValueType()))));
1865   }
1866
1867   APInt Val;
1868   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1869   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1870       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1871                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1872     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1873                              N1, N0.getOperand(1));
1874     AddToWorkList(C3.getNode());
1875     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1876                        N0.getOperand(0), C3);
1877   }
1878
1879   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1880   // use.
1881   {
1882     SDValue Sh(0,0), Y(0,0);
1883     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1884     if (N0.getOpcode() == ISD::SHL &&
1885         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1886                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1887         N0.getNode()->hasOneUse()) {
1888       Sh = N0; Y = N1;
1889     } else if (N1.getOpcode() == ISD::SHL &&
1890                isa<ConstantSDNode>(N1.getOperand(1)) &&
1891                N1.getNode()->hasOneUse()) {
1892       Sh = N1; Y = N0;
1893     }
1894
1895     if (Sh.getNode()) {
1896       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1897                                 Sh.getOperand(0), Y);
1898       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1899                          Mul, Sh.getOperand(1));
1900     }
1901   }
1902
1903   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1904   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1905       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1906                      isa<ConstantSDNode>(N0.getOperand(1))))
1907     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1908                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1909                                    N0.getOperand(0), N1),
1910                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1911                                    N0.getOperand(1), N1));
1912
1913   // reassociate mul
1914   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1915   if (RMUL.getNode() != 0)
1916     return RMUL;
1917
1918   return SDValue();
1919 }
1920
1921 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1922   SDValue N0 = N->getOperand(0);
1923   SDValue N1 = N->getOperand(1);
1924   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1925   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1926   EVT VT = N->getValueType(0);
1927
1928   // fold vector ops
1929   if (VT.isVector()) {
1930     SDValue FoldedVOp = SimplifyVBinOp(N);
1931     if (FoldedVOp.getNode()) return FoldedVOp;
1932   }
1933
1934   // fold (sdiv c1, c2) -> c1/c2
1935   if (N0C && N1C && !N1C->isNullValue())
1936     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1937   // fold (sdiv X, 1) -> X
1938   if (N1C && N1C->getAPIntValue() == 1LL)
1939     return N0;
1940   // fold (sdiv X, -1) -> 0-X
1941   if (N1C && N1C->isAllOnesValue())
1942     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1943                        DAG.getConstant(0, VT), N0);
1944   // If we know the sign bits of both operands are zero, strength reduce to a
1945   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1946   if (!VT.isVector()) {
1947     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1948       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1949                          N0, N1);
1950   }
1951   // fold (sdiv X, pow2) -> simple ops after legalize
1952   if (N1C && !N1C->isNullValue() &&
1953       (N1C->getAPIntValue().isPowerOf2() ||
1954        (-N1C->getAPIntValue()).isPowerOf2())) {
1955     // If dividing by powers of two is cheap, then don't perform the following
1956     // fold.
1957     if (TLI.isPow2DivCheap())
1958       return SDValue();
1959
1960     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1961
1962     // Splat the sign bit into the register
1963     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1964                               DAG.getConstant(VT.getSizeInBits()-1,
1965                                        getShiftAmountTy(N0.getValueType())));
1966     AddToWorkList(SGN.getNode());
1967
1968     // Add (N0 < 0) ? abs2 - 1 : 0;
1969     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1970                               DAG.getConstant(VT.getSizeInBits() - lg2,
1971                                        getShiftAmountTy(SGN.getValueType())));
1972     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1973     AddToWorkList(SRL.getNode());
1974     AddToWorkList(ADD.getNode());    // Divide by pow2
1975     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1976                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1977
1978     // If we're dividing by a positive value, we're done.  Otherwise, we must
1979     // negate the result.
1980     if (N1C->getAPIntValue().isNonNegative())
1981       return SRA;
1982
1983     AddToWorkList(SRA.getNode());
1984     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1985                        DAG.getConstant(0, VT), SRA);
1986   }
1987
1988   // if integer divide is expensive and we satisfy the requirements, emit an
1989   // alternate sequence.
1990   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1991     SDValue Op = BuildSDIV(N);
1992     if (Op.getNode()) return Op;
1993   }
1994
1995   // undef / X -> 0
1996   if (N0.getOpcode() == ISD::UNDEF)
1997     return DAG.getConstant(0, VT);
1998   // X / undef -> undef
1999   if (N1.getOpcode() == ISD::UNDEF)
2000     return N1;
2001
2002   return SDValue();
2003 }
2004
2005 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2006   SDValue N0 = N->getOperand(0);
2007   SDValue N1 = N->getOperand(1);
2008   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2009   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2010   EVT VT = N->getValueType(0);
2011
2012   // fold vector ops
2013   if (VT.isVector()) {
2014     SDValue FoldedVOp = SimplifyVBinOp(N);
2015     if (FoldedVOp.getNode()) return FoldedVOp;
2016   }
2017
2018   // fold (udiv c1, c2) -> c1/c2
2019   if (N0C && N1C && !N1C->isNullValue())
2020     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2021   // fold (udiv x, (1 << c)) -> x >>u c
2022   if (N1C && N1C->getAPIntValue().isPowerOf2())
2023     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2024                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2025                                        getShiftAmountTy(N0.getValueType())));
2026   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2027   if (N1.getOpcode() == ISD::SHL) {
2028     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2029       if (SHC->getAPIntValue().isPowerOf2()) {
2030         EVT ADDVT = N1.getOperand(1).getValueType();
2031         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2032                                   N1.getOperand(1),
2033                                   DAG.getConstant(SHC->getAPIntValue()
2034                                                                   .logBase2(),
2035                                                   ADDVT));
2036         AddToWorkList(Add.getNode());
2037         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2038       }
2039     }
2040   }
2041   // fold (udiv x, c) -> alternate
2042   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2043     SDValue Op = BuildUDIV(N);
2044     if (Op.getNode()) return Op;
2045   }
2046
2047   // undef / X -> 0
2048   if (N0.getOpcode() == ISD::UNDEF)
2049     return DAG.getConstant(0, VT);
2050   // X / undef -> undef
2051   if (N1.getOpcode() == ISD::UNDEF)
2052     return N1;
2053
2054   return SDValue();
2055 }
2056
2057 SDValue DAGCombiner::visitSREM(SDNode *N) {
2058   SDValue N0 = N->getOperand(0);
2059   SDValue N1 = N->getOperand(1);
2060   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2061   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2062   EVT VT = N->getValueType(0);
2063
2064   // fold (srem c1, c2) -> c1%c2
2065   if (N0C && N1C && !N1C->isNullValue())
2066     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2067   // If we know the sign bits of both operands are zero, strength reduce to a
2068   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2069   if (!VT.isVector()) {
2070     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2071       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2072   }
2073
2074   // If X/C can be simplified by the division-by-constant logic, lower
2075   // X%C to the equivalent of X-X/C*C.
2076   if (N1C && !N1C->isNullValue()) {
2077     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2078     AddToWorkList(Div.getNode());
2079     SDValue OptimizedDiv = combine(Div.getNode());
2080     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2081       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2082                                 OptimizedDiv, N1);
2083       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2084       AddToWorkList(Mul.getNode());
2085       return Sub;
2086     }
2087   }
2088
2089   // undef % X -> 0
2090   if (N0.getOpcode() == ISD::UNDEF)
2091     return DAG.getConstant(0, VT);
2092   // X % undef -> undef
2093   if (N1.getOpcode() == ISD::UNDEF)
2094     return N1;
2095
2096   return SDValue();
2097 }
2098
2099 SDValue DAGCombiner::visitUREM(SDNode *N) {
2100   SDValue N0 = N->getOperand(0);
2101   SDValue N1 = N->getOperand(1);
2102   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2103   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2104   EVT VT = N->getValueType(0);
2105
2106   // fold (urem c1, c2) -> c1%c2
2107   if (N0C && N1C && !N1C->isNullValue())
2108     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2109   // fold (urem x, pow2) -> (and x, pow2-1)
2110   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2111     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2112                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2113   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2114   if (N1.getOpcode() == ISD::SHL) {
2115     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2116       if (SHC->getAPIntValue().isPowerOf2()) {
2117         SDValue Add =
2118           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2119                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2120                                  VT));
2121         AddToWorkList(Add.getNode());
2122         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2123       }
2124     }
2125   }
2126
2127   // If X/C can be simplified by the division-by-constant logic, lower
2128   // X%C to the equivalent of X-X/C*C.
2129   if (N1C && !N1C->isNullValue()) {
2130     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2131     AddToWorkList(Div.getNode());
2132     SDValue OptimizedDiv = combine(Div.getNode());
2133     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2134       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2135                                 OptimizedDiv, N1);
2136       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2137       AddToWorkList(Mul.getNode());
2138       return Sub;
2139     }
2140   }
2141
2142   // undef % X -> 0
2143   if (N0.getOpcode() == ISD::UNDEF)
2144     return DAG.getConstant(0, VT);
2145   // X % undef -> undef
2146   if (N1.getOpcode() == ISD::UNDEF)
2147     return N1;
2148
2149   return SDValue();
2150 }
2151
2152 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2153   SDValue N0 = N->getOperand(0);
2154   SDValue N1 = N->getOperand(1);
2155   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2156   EVT VT = N->getValueType(0);
2157   SDLoc DL(N);
2158
2159   // fold (mulhs x, 0) -> 0
2160   if (N1C && N1C->isNullValue())
2161     return N1;
2162   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2163   if (N1C && N1C->getAPIntValue() == 1)
2164     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2165                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2166                                        getShiftAmountTy(N0.getValueType())));
2167   // fold (mulhs x, undef) -> 0
2168   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2169     return DAG.getConstant(0, VT);
2170
2171   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2172   // plus a shift.
2173   if (VT.isSimple() && !VT.isVector()) {
2174     MVT Simple = VT.getSimpleVT();
2175     unsigned SimpleSize = Simple.getSizeInBits();
2176     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2177     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2178       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2179       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2180       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2181       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2182             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2183       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2184     }
2185   }
2186
2187   return SDValue();
2188 }
2189
2190 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2191   SDValue N0 = N->getOperand(0);
2192   SDValue N1 = N->getOperand(1);
2193   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2194   EVT VT = N->getValueType(0);
2195   SDLoc DL(N);
2196
2197   // fold (mulhu x, 0) -> 0
2198   if (N1C && N1C->isNullValue())
2199     return N1;
2200   // fold (mulhu x, 1) -> 0
2201   if (N1C && N1C->getAPIntValue() == 1)
2202     return DAG.getConstant(0, N0.getValueType());
2203   // fold (mulhu x, undef) -> 0
2204   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2205     return DAG.getConstant(0, VT);
2206
2207   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2208   // plus a shift.
2209   if (VT.isSimple() && !VT.isVector()) {
2210     MVT Simple = VT.getSimpleVT();
2211     unsigned SimpleSize = Simple.getSizeInBits();
2212     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2213     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2214       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2215       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2216       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2217       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2218             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2219       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2220     }
2221   }
2222
2223   return SDValue();
2224 }
2225
2226 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2227 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2228 /// that are being performed. Return true if a simplification was made.
2229 ///
2230 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2231                                                 unsigned HiOp) {
2232   // If the high half is not needed, just compute the low half.
2233   bool HiExists = N->hasAnyUseOfValue(1);
2234   if (!HiExists &&
2235       (!LegalOperations ||
2236        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2237     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2238                               N->op_begin(), N->getNumOperands());
2239     return CombineTo(N, Res, Res);
2240   }
2241
2242   // If the low half is not needed, just compute the high half.
2243   bool LoExists = N->hasAnyUseOfValue(0);
2244   if (!LoExists &&
2245       (!LegalOperations ||
2246        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2247     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2248                               N->op_begin(), N->getNumOperands());
2249     return CombineTo(N, Res, Res);
2250   }
2251
2252   // If both halves are used, return as it is.
2253   if (LoExists && HiExists)
2254     return SDValue();
2255
2256   // If the two computed results can be simplified separately, separate them.
2257   if (LoExists) {
2258     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2259                              N->op_begin(), N->getNumOperands());
2260     AddToWorkList(Lo.getNode());
2261     SDValue LoOpt = combine(Lo.getNode());
2262     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2263         (!LegalOperations ||
2264          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2265       return CombineTo(N, LoOpt, LoOpt);
2266   }
2267
2268   if (HiExists) {
2269     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2270                              N->op_begin(), N->getNumOperands());
2271     AddToWorkList(Hi.getNode());
2272     SDValue HiOpt = combine(Hi.getNode());
2273     if (HiOpt.getNode() && HiOpt != Hi &&
2274         (!LegalOperations ||
2275          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2276       return CombineTo(N, HiOpt, HiOpt);
2277   }
2278
2279   return SDValue();
2280 }
2281
2282 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2283   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2284   if (Res.getNode()) return Res;
2285
2286   EVT VT = N->getValueType(0);
2287   SDLoc DL(N);
2288
2289   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2290   // plus a shift.
2291   if (VT.isSimple() && !VT.isVector()) {
2292     MVT Simple = VT.getSimpleVT();
2293     unsigned SimpleSize = Simple.getSizeInBits();
2294     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2295     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2296       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2297       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2298       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2299       // Compute the high part as N1.
2300       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2301             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2302       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2303       // Compute the low part as N0.
2304       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2305       return CombineTo(N, Lo, Hi);
2306     }
2307   }
2308
2309   return SDValue();
2310 }
2311
2312 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2313   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2314   if (Res.getNode()) return Res;
2315
2316   EVT VT = N->getValueType(0);
2317   SDLoc DL(N);
2318
2319   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2320   // plus a shift.
2321   if (VT.isSimple() && !VT.isVector()) {
2322     MVT Simple = VT.getSimpleVT();
2323     unsigned SimpleSize = Simple.getSizeInBits();
2324     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2325     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2326       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2327       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2328       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2329       // Compute the high part as N1.
2330       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2331             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2332       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2333       // Compute the low part as N0.
2334       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2335       return CombineTo(N, Lo, Hi);
2336     }
2337   }
2338
2339   return SDValue();
2340 }
2341
2342 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2343   // (smulo x, 2) -> (saddo x, x)
2344   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2345     if (C2->getAPIntValue() == 2)
2346       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2347                          N->getOperand(0), N->getOperand(0));
2348
2349   return SDValue();
2350 }
2351
2352 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2353   // (umulo x, 2) -> (uaddo x, x)
2354   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2355     if (C2->getAPIntValue() == 2)
2356       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2357                          N->getOperand(0), N->getOperand(0));
2358
2359   return SDValue();
2360 }
2361
2362 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2363   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2364   if (Res.getNode()) return Res;
2365
2366   return SDValue();
2367 }
2368
2369 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2370   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2371   if (Res.getNode()) return Res;
2372
2373   return SDValue();
2374 }
2375
2376 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2377 /// two operands of the same opcode, try to simplify it.
2378 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2379   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2380   EVT VT = N0.getValueType();
2381   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2382
2383   // Bail early if none of these transforms apply.
2384   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2385
2386   // For each of OP in AND/OR/XOR:
2387   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2388   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2389   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2390   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2391   //
2392   // do not sink logical op inside of a vector extend, since it may combine
2393   // into a vsetcc.
2394   EVT Op0VT = N0.getOperand(0).getValueType();
2395   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2396        N0.getOpcode() == ISD::SIGN_EXTEND ||
2397        // Avoid infinite looping with PromoteIntBinOp.
2398        (N0.getOpcode() == ISD::ANY_EXTEND &&
2399         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2400        (N0.getOpcode() == ISD::TRUNCATE &&
2401         (!TLI.isZExtFree(VT, Op0VT) ||
2402          !TLI.isTruncateFree(Op0VT, VT)) &&
2403         TLI.isTypeLegal(Op0VT))) &&
2404       !VT.isVector() &&
2405       Op0VT == N1.getOperand(0).getValueType() &&
2406       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2407     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2408                                  N0.getOperand(0).getValueType(),
2409                                  N0.getOperand(0), N1.getOperand(0));
2410     AddToWorkList(ORNode.getNode());
2411     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2412   }
2413
2414   // For each of OP in SHL/SRL/SRA/AND...
2415   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2416   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2417   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2418   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2419        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2420       N0.getOperand(1) == N1.getOperand(1)) {
2421     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2422                                  N0.getOperand(0).getValueType(),
2423                                  N0.getOperand(0), N1.getOperand(0));
2424     AddToWorkList(ORNode.getNode());
2425     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2426                        ORNode, N0.getOperand(1));
2427   }
2428
2429   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2430   // Only perform this optimization after type legalization and before
2431   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2432   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2433   // we don't want to undo this promotion.
2434   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2435   // on scalars.
2436   if ((N0.getOpcode() == ISD::BITCAST ||
2437        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2438       Level == AfterLegalizeTypes) {
2439     SDValue In0 = N0.getOperand(0);
2440     SDValue In1 = N1.getOperand(0);
2441     EVT In0Ty = In0.getValueType();
2442     EVT In1Ty = In1.getValueType();
2443     SDLoc DL(N);
2444     // If both incoming values are integers, and the original types are the
2445     // same.
2446     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2447       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2448       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2449       AddToWorkList(Op.getNode());
2450       return BC;
2451     }
2452   }
2453
2454   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2455   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2456   // If both shuffles use the same mask, and both shuffle within a single
2457   // vector, then it is worthwhile to move the swizzle after the operation.
2458   // The type-legalizer generates this pattern when loading illegal
2459   // vector types from memory. In many cases this allows additional shuffle
2460   // optimizations.
2461   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2462       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2463       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2464     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2465     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2466
2467     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2468            "Inputs to shuffles are not the same type");
2469
2470     unsigned NumElts = VT.getVectorNumElements();
2471
2472     // Check that both shuffles use the same mask. The masks are known to be of
2473     // the same length because the result vector type is the same.
2474     bool SameMask = true;
2475     for (unsigned i = 0; i != NumElts; ++i) {
2476       int Idx0 = SVN0->getMaskElt(i);
2477       int Idx1 = SVN1->getMaskElt(i);
2478       if (Idx0 != Idx1) {
2479         SameMask = false;
2480         break;
2481       }
2482     }
2483
2484     if (SameMask) {
2485       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2486                                N0.getOperand(0), N1.getOperand(0));
2487       AddToWorkList(Op.getNode());
2488       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2489                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2490     }
2491   }
2492
2493   return SDValue();
2494 }
2495
2496 SDValue DAGCombiner::visitAND(SDNode *N) {
2497   SDValue N0 = N->getOperand(0);
2498   SDValue N1 = N->getOperand(1);
2499   SDValue LL, LR, RL, RR, CC0, CC1;
2500   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2501   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2502   EVT VT = N1.getValueType();
2503   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2504
2505   // fold vector ops
2506   if (VT.isVector()) {
2507     SDValue FoldedVOp = SimplifyVBinOp(N);
2508     if (FoldedVOp.getNode()) return FoldedVOp;
2509
2510     // fold (and x, 0) -> 0, vector edition
2511     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2512       return N0;
2513     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2514       return N1;
2515
2516     // fold (and x, -1) -> x, vector edition
2517     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2518       return N1;
2519     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2520       return N0;
2521   }
2522
2523   // fold (and x, undef) -> 0
2524   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2525     return DAG.getConstant(0, VT);
2526   // fold (and c1, c2) -> c1&c2
2527   if (N0C && N1C)
2528     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2529   // canonicalize constant to RHS
2530   if (N0C && !N1C)
2531     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2532   // fold (and x, -1) -> x
2533   if (N1C && N1C->isAllOnesValue())
2534     return N0;
2535   // if (and x, c) is known to be zero, return 0
2536   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2537                                    APInt::getAllOnesValue(BitWidth)))
2538     return DAG.getConstant(0, VT);
2539   // reassociate and
2540   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2541   if (RAND.getNode() != 0)
2542     return RAND;
2543   // fold (and (or x, C), D) -> D if (C & D) == D
2544   if (N1C && N0.getOpcode() == ISD::OR)
2545     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2546       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2547         return N1;
2548   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2549   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2550     SDValue N0Op0 = N0.getOperand(0);
2551     APInt Mask = ~N1C->getAPIntValue();
2552     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2553     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2554       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2555                                  N0.getValueType(), N0Op0);
2556
2557       // Replace uses of the AND with uses of the Zero extend node.
2558       CombineTo(N, Zext);
2559
2560       // We actually want to replace all uses of the any_extend with the
2561       // zero_extend, to avoid duplicating things.  This will later cause this
2562       // AND to be folded.
2563       CombineTo(N0.getNode(), Zext);
2564       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2565     }
2566   }
2567   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2568   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2569   // already be zero by virtue of the width of the base type of the load.
2570   //
2571   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2572   // more cases.
2573   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2574        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2575       N0.getOpcode() == ISD::LOAD) {
2576     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2577                                          N0 : N0.getOperand(0) );
2578
2579     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2580     // This can be a pure constant or a vector splat, in which case we treat the
2581     // vector as a scalar and use the splat value.
2582     APInt Constant = APInt::getNullValue(1);
2583     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2584       Constant = C->getAPIntValue();
2585     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2586       APInt SplatValue, SplatUndef;
2587       unsigned SplatBitSize;
2588       bool HasAnyUndefs;
2589       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2590                                              SplatBitSize, HasAnyUndefs);
2591       if (IsSplat) {
2592         // Undef bits can contribute to a possible optimisation if set, so
2593         // set them.
2594         SplatValue |= SplatUndef;
2595
2596         // The splat value may be something like "0x00FFFFFF", which means 0 for
2597         // the first vector value and FF for the rest, repeating. We need a mask
2598         // that will apply equally to all members of the vector, so AND all the
2599         // lanes of the constant together.
2600         EVT VT = Vector->getValueType(0);
2601         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2602
2603         // If the splat value has been compressed to a bitlength lower
2604         // than the size of the vector lane, we need to re-expand it to
2605         // the lane size.
2606         if (BitWidth > SplatBitSize)
2607           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2608                SplatBitSize < BitWidth;
2609                SplatBitSize = SplatBitSize * 2)
2610             SplatValue |= SplatValue.shl(SplatBitSize);
2611
2612         Constant = APInt::getAllOnesValue(BitWidth);
2613         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2614           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2615       }
2616     }
2617
2618     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2619     // actually legal and isn't going to get expanded, else this is a false
2620     // optimisation.
2621     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2622                                                     Load->getMemoryVT());
2623
2624     // Resize the constant to the same size as the original memory access before
2625     // extension. If it is still the AllOnesValue then this AND is completely
2626     // unneeded.
2627     Constant =
2628       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2629
2630     bool B;
2631     switch (Load->getExtensionType()) {
2632     default: B = false; break;
2633     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2634     case ISD::ZEXTLOAD:
2635     case ISD::NON_EXTLOAD: B = true; break;
2636     }
2637
2638     if (B && Constant.isAllOnesValue()) {
2639       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2640       // preserve semantics once we get rid of the AND.
2641       SDValue NewLoad(Load, 0);
2642       if (Load->getExtensionType() == ISD::EXTLOAD) {
2643         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2644                               Load->getValueType(0), SDLoc(Load),
2645                               Load->getChain(), Load->getBasePtr(),
2646                               Load->getOffset(), Load->getMemoryVT(),
2647                               Load->getMemOperand());
2648         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2649         if (Load->getNumValues() == 3) {
2650           // PRE/POST_INC loads have 3 values.
2651           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2652                            NewLoad.getValue(2) };
2653           CombineTo(Load, To, 3, true);
2654         } else {
2655           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2656         }
2657       }
2658
2659       // Fold the AND away, taking care not to fold to the old load node if we
2660       // replaced it.
2661       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2662
2663       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2664     }
2665   }
2666   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2667   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2668     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2669     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2670
2671     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2672         LL.getValueType().isInteger()) {
2673       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2674       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2675         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2676                                      LR.getValueType(), LL, RL);
2677         AddToWorkList(ORNode.getNode());
2678         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2679       }
2680       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2681       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2682         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2683                                       LR.getValueType(), LL, RL);
2684         AddToWorkList(ANDNode.getNode());
2685         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2686       }
2687       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2688       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2689         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2690                                      LR.getValueType(), LL, RL);
2691         AddToWorkList(ORNode.getNode());
2692         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2693       }
2694     }
2695     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2696     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2697         Op0 == Op1 && LL.getValueType().isInteger() &&
2698       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2699                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2700                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2701                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2702       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2703                                     LL, DAG.getConstant(1, LL.getValueType()));
2704       AddToWorkList(ADDNode.getNode());
2705       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2706                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2707     }
2708     // canonicalize equivalent to ll == rl
2709     if (LL == RR && LR == RL) {
2710       Op1 = ISD::getSetCCSwappedOperands(Op1);
2711       std::swap(RL, RR);
2712     }
2713     if (LL == RL && LR == RR) {
2714       bool isInteger = LL.getValueType().isInteger();
2715       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2716       if (Result != ISD::SETCC_INVALID &&
2717           (!LegalOperations ||
2718            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2719             TLI.isOperationLegal(ISD::SETCC,
2720                             getSetCCResultType(N0.getSimpleValueType())))))
2721         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2722                             LL, LR, Result);
2723     }
2724   }
2725
2726   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2727   if (N0.getOpcode() == N1.getOpcode()) {
2728     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2729     if (Tmp.getNode()) return Tmp;
2730   }
2731
2732   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2733   // fold (and (sra)) -> (and (srl)) when possible.
2734   if (!VT.isVector() &&
2735       SimplifyDemandedBits(SDValue(N, 0)))
2736     return SDValue(N, 0);
2737
2738   // fold (zext_inreg (extload x)) -> (zextload x)
2739   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2740     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2741     EVT MemVT = LN0->getMemoryVT();
2742     // If we zero all the possible extended bits, then we can turn this into
2743     // a zextload if we are running before legalize or the operation is legal.
2744     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2745     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2746                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2747         ((!LegalOperations && !LN0->isVolatile()) ||
2748          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2749       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2750                                        LN0->getChain(), LN0->getBasePtr(),
2751                                        MemVT, LN0->getMemOperand());
2752       AddToWorkList(N);
2753       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2754       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2755     }
2756   }
2757   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2758   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2759       N0.hasOneUse()) {
2760     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2761     EVT MemVT = LN0->getMemoryVT();
2762     // If we zero all the possible extended bits, then we can turn this into
2763     // a zextload if we are running before legalize or the operation is legal.
2764     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2765     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2766                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2767         ((!LegalOperations && !LN0->isVolatile()) ||
2768          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2769       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2770                                        LN0->getChain(), LN0->getBasePtr(),
2771                                        MemVT, LN0->getMemOperand());
2772       AddToWorkList(N);
2773       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2774       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2775     }
2776   }
2777
2778   // fold (and (load x), 255) -> (zextload x, i8)
2779   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2780   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2781   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2782               (N0.getOpcode() == ISD::ANY_EXTEND &&
2783                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2784     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2785     LoadSDNode *LN0 = HasAnyExt
2786       ? cast<LoadSDNode>(N0.getOperand(0))
2787       : cast<LoadSDNode>(N0);
2788     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2789         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2790       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2791       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2792         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2793         EVT LoadedVT = LN0->getMemoryVT();
2794
2795         if (ExtVT == LoadedVT &&
2796             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2797           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2798
2799           SDValue NewLoad =
2800             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2801                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2802                            LN0->getMemOperand());
2803           AddToWorkList(N);
2804           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2805           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2806         }
2807
2808         // Do not change the width of a volatile load.
2809         // Do not generate loads of non-round integer types since these can
2810         // be expensive (and would be wrong if the type is not byte sized).
2811         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2812             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813           EVT PtrType = LN0->getOperand(1).getValueType();
2814
2815           unsigned Alignment = LN0->getAlignment();
2816           SDValue NewPtr = LN0->getBasePtr();
2817
2818           // For big endian targets, we need to add an offset to the pointer
2819           // to load the correct bytes.  For little endian systems, we merely
2820           // need to read fewer bytes from the same pointer.
2821           if (TLI.isBigEndian()) {
2822             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2823             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2824             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2825             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2826                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2827             Alignment = MinAlign(Alignment, PtrOff);
2828           }
2829
2830           AddToWorkList(NewPtr.getNode());
2831
2832           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2833           SDValue Load =
2834             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2835                            LN0->getChain(), NewPtr,
2836                            LN0->getPointerInfo(),
2837                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2838                            Alignment, LN0->getTBAAInfo());
2839           AddToWorkList(N);
2840           CombineTo(LN0, Load, Load.getValue(1));
2841           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2842         }
2843       }
2844     }
2845   }
2846
2847   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2848       VT.getSizeInBits() <= 64) {
2849     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2850       APInt ADDC = ADDI->getAPIntValue();
2851       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2852         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2853         // immediate for an add, but it is legal if its top c2 bits are set,
2854         // transform the ADD so the immediate doesn't need to be materialized
2855         // in a register.
2856         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2857           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2858                                              SRLI->getZExtValue());
2859           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2860             ADDC |= Mask;
2861             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2862               SDValue NewAdd =
2863                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2864                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2865               CombineTo(N0.getNode(), NewAdd);
2866               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2867             }
2868           }
2869         }
2870       }
2871     }
2872   }
2873
2874   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2875   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2876     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2877                                        N0.getOperand(1), false);
2878     if (BSwap.getNode())
2879       return BSwap;
2880   }
2881
2882   return SDValue();
2883 }
2884
2885 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2886 ///
2887 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2888                                         bool DemandHighBits) {
2889   if (!LegalOperations)
2890     return SDValue();
2891
2892   EVT VT = N->getValueType(0);
2893   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2894     return SDValue();
2895   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2896     return SDValue();
2897
2898   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2899   bool LookPassAnd0 = false;
2900   bool LookPassAnd1 = false;
2901   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2902       std::swap(N0, N1);
2903   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2904       std::swap(N0, N1);
2905   if (N0.getOpcode() == ISD::AND) {
2906     if (!N0.getNode()->hasOneUse())
2907       return SDValue();
2908     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2909     if (!N01C || N01C->getZExtValue() != 0xFF00)
2910       return SDValue();
2911     N0 = N0.getOperand(0);
2912     LookPassAnd0 = true;
2913   }
2914
2915   if (N1.getOpcode() == ISD::AND) {
2916     if (!N1.getNode()->hasOneUse())
2917       return SDValue();
2918     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2919     if (!N11C || N11C->getZExtValue() != 0xFF)
2920       return SDValue();
2921     N1 = N1.getOperand(0);
2922     LookPassAnd1 = true;
2923   }
2924
2925   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2926     std::swap(N0, N1);
2927   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2928     return SDValue();
2929   if (!N0.getNode()->hasOneUse() ||
2930       !N1.getNode()->hasOneUse())
2931     return SDValue();
2932
2933   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2934   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2935   if (!N01C || !N11C)
2936     return SDValue();
2937   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2938     return SDValue();
2939
2940   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2941   SDValue N00 = N0->getOperand(0);
2942   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2943     if (!N00.getNode()->hasOneUse())
2944       return SDValue();
2945     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2946     if (!N001C || N001C->getZExtValue() != 0xFF)
2947       return SDValue();
2948     N00 = N00.getOperand(0);
2949     LookPassAnd0 = true;
2950   }
2951
2952   SDValue N10 = N1->getOperand(0);
2953   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2954     if (!N10.getNode()->hasOneUse())
2955       return SDValue();
2956     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2957     if (!N101C || N101C->getZExtValue() != 0xFF00)
2958       return SDValue();
2959     N10 = N10.getOperand(0);
2960     LookPassAnd1 = true;
2961   }
2962
2963   if (N00 != N10)
2964     return SDValue();
2965
2966   // Make sure everything beyond the low halfword gets set to zero since the SRL
2967   // 16 will clear the top bits.
2968   unsigned OpSizeInBits = VT.getSizeInBits();
2969   if (DemandHighBits && OpSizeInBits > 16) {
2970     // If the left-shift isn't masked out then the only way this is a bswap is
2971     // if all bits beyond the low 8 are 0. In that case the entire pattern
2972     // reduces to a left shift anyway: leave it for other parts of the combiner.
2973     if (!LookPassAnd0)
2974       return SDValue();
2975
2976     // However, if the right shift isn't masked out then it might be because
2977     // it's not needed. See if we can spot that too.
2978     if (!LookPassAnd1 &&
2979         !DAG.MaskedValueIsZero(
2980             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2981       return SDValue();
2982   }
2983
2984   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2985   if (OpSizeInBits > 16)
2986     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2987                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2988   return Res;
2989 }
2990
2991 /// isBSwapHWordElement - Return true if the specified node is an element
2992 /// that makes up a 32-bit packed halfword byteswap. i.e.
2993 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2994 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2995   if (!N.getNode()->hasOneUse())
2996     return false;
2997
2998   unsigned Opc = N.getOpcode();
2999   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3000     return false;
3001
3002   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3003   if (!N1C)
3004     return false;
3005
3006   unsigned Num;
3007   switch (N1C->getZExtValue()) {
3008   default:
3009     return false;
3010   case 0xFF:       Num = 0; break;
3011   case 0xFF00:     Num = 1; break;
3012   case 0xFF0000:   Num = 2; break;
3013   case 0xFF000000: Num = 3; break;
3014   }
3015
3016   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3017   SDValue N0 = N.getOperand(0);
3018   if (Opc == ISD::AND) {
3019     if (Num == 0 || Num == 2) {
3020       // (x >> 8) & 0xff
3021       // (x >> 8) & 0xff0000
3022       if (N0.getOpcode() != ISD::SRL)
3023         return false;
3024       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3025       if (!C || C->getZExtValue() != 8)
3026         return false;
3027     } else {
3028       // (x << 8) & 0xff00
3029       // (x << 8) & 0xff000000
3030       if (N0.getOpcode() != ISD::SHL)
3031         return false;
3032       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3033       if (!C || C->getZExtValue() != 8)
3034         return false;
3035     }
3036   } else if (Opc == ISD::SHL) {
3037     // (x & 0xff) << 8
3038     // (x & 0xff0000) << 8
3039     if (Num != 0 && Num != 2)
3040       return false;
3041     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3042     if (!C || C->getZExtValue() != 8)
3043       return false;
3044   } else { // Opc == ISD::SRL
3045     // (x & 0xff00) >> 8
3046     // (x & 0xff000000) >> 8
3047     if (Num != 1 && Num != 3)
3048       return false;
3049     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3050     if (!C || C->getZExtValue() != 8)
3051       return false;
3052   }
3053
3054   if (Parts[Num])
3055     return false;
3056
3057   Parts[Num] = N0.getOperand(0).getNode();
3058   return true;
3059 }
3060
3061 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3062 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3063 /// => (rotl (bswap x), 16)
3064 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3065   if (!LegalOperations)
3066     return SDValue();
3067
3068   EVT VT = N->getValueType(0);
3069   if (VT != MVT::i32)
3070     return SDValue();
3071   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3072     return SDValue();
3073
3074   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3075   // Look for either
3076   // (or (or (and), (and)), (or (and), (and)))
3077   // (or (or (or (and), (and)), (and)), (and))
3078   if (N0.getOpcode() != ISD::OR)
3079     return SDValue();
3080   SDValue N00 = N0.getOperand(0);
3081   SDValue N01 = N0.getOperand(1);
3082
3083   if (N1.getOpcode() == ISD::OR &&
3084       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3085     // (or (or (and), (and)), (or (and), (and)))
3086     SDValue N000 = N00.getOperand(0);
3087     if (!isBSwapHWordElement(N000, Parts))
3088       return SDValue();
3089
3090     SDValue N001 = N00.getOperand(1);
3091     if (!isBSwapHWordElement(N001, Parts))
3092       return SDValue();
3093     SDValue N010 = N01.getOperand(0);
3094     if (!isBSwapHWordElement(N010, Parts))
3095       return SDValue();
3096     SDValue N011 = N01.getOperand(1);
3097     if (!isBSwapHWordElement(N011, Parts))
3098       return SDValue();
3099   } else {
3100     // (or (or (or (and), (and)), (and)), (and))
3101     if (!isBSwapHWordElement(N1, Parts))
3102       return SDValue();
3103     if (!isBSwapHWordElement(N01, Parts))
3104       return SDValue();
3105     if (N00.getOpcode() != ISD::OR)
3106       return SDValue();
3107     SDValue N000 = N00.getOperand(0);
3108     if (!isBSwapHWordElement(N000, Parts))
3109       return SDValue();
3110     SDValue N001 = N00.getOperand(1);
3111     if (!isBSwapHWordElement(N001, Parts))
3112       return SDValue();
3113   }
3114
3115   // Make sure the parts are all coming from the same node.
3116   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3117     return SDValue();
3118
3119   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3120                               SDValue(Parts[0],0));
3121
3122   // Result of the bswap should be rotated by 16. If it's not legal, then
3123   // do  (x << 16) | (x >> 16).
3124   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3125   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3126     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3127   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3128     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3129   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3130                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3131                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3132 }
3133
3134 SDValue DAGCombiner::visitOR(SDNode *N) {
3135   SDValue N0 = N->getOperand(0);
3136   SDValue N1 = N->getOperand(1);
3137   SDValue LL, LR, RL, RR, CC0, CC1;
3138   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3139   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3140   EVT VT = N1.getValueType();
3141
3142   // fold vector ops
3143   if (VT.isVector()) {
3144     SDValue FoldedVOp = SimplifyVBinOp(N);
3145     if (FoldedVOp.getNode()) return FoldedVOp;
3146
3147     // fold (or x, 0) -> x, vector edition
3148     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3149       return N1;
3150     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3151       return N0;
3152
3153     // fold (or x, -1) -> -1, vector edition
3154     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3155       return N0;
3156     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3157       return N1;
3158   }
3159
3160   // fold (or x, undef) -> -1
3161   if (!LegalOperations &&
3162       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3163     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3164     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3165   }
3166   // fold (or c1, c2) -> c1|c2
3167   if (N0C && N1C)
3168     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3169   // canonicalize constant to RHS
3170   if (N0C && !N1C)
3171     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3172   // fold (or x, 0) -> x
3173   if (N1C && N1C->isNullValue())
3174     return N0;
3175   // fold (or x, -1) -> -1
3176   if (N1C && N1C->isAllOnesValue())
3177     return N1;
3178   // fold (or x, c) -> c iff (x & ~c) == 0
3179   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3180     return N1;
3181
3182   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3183   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3184   if (BSwap.getNode() != 0)
3185     return BSwap;
3186   BSwap = MatchBSwapHWordLow(N, N0, N1);
3187   if (BSwap.getNode() != 0)
3188     return BSwap;
3189
3190   // reassociate or
3191   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3192   if (ROR.getNode() != 0)
3193     return ROR;
3194   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3195   // iff (c1 & c2) == 0.
3196   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3197              isa<ConstantSDNode>(N0.getOperand(1))) {
3198     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3199     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3200       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3201                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3202                                      N0.getOperand(0), N1),
3203                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3204   }
3205   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3206   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3207     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3208     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3209
3210     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3211         LL.getValueType().isInteger()) {
3212       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3213       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3214       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3215           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3216         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3217                                      LR.getValueType(), LL, RL);
3218         AddToWorkList(ORNode.getNode());
3219         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3220       }
3221       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3222       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3223       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3224           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3225         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3226                                       LR.getValueType(), LL, RL);
3227         AddToWorkList(ANDNode.getNode());
3228         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3229       }
3230     }
3231     // canonicalize equivalent to ll == rl
3232     if (LL == RR && LR == RL) {
3233       Op1 = ISD::getSetCCSwappedOperands(Op1);
3234       std::swap(RL, RR);
3235     }
3236     if (LL == RL && LR == RR) {
3237       bool isInteger = LL.getValueType().isInteger();
3238       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3239       if (Result != ISD::SETCC_INVALID &&
3240           (!LegalOperations ||
3241            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3242             TLI.isOperationLegal(ISD::SETCC,
3243               getSetCCResultType(N0.getValueType())))))
3244         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3245                             LL, LR, Result);
3246     }
3247   }
3248
3249   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3250   if (N0.getOpcode() == N1.getOpcode()) {
3251     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3252     if (Tmp.getNode()) return Tmp;
3253   }
3254
3255   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3256   if (N0.getOpcode() == ISD::AND &&
3257       N1.getOpcode() == ISD::AND &&
3258       N0.getOperand(1).getOpcode() == ISD::Constant &&
3259       N1.getOperand(1).getOpcode() == ISD::Constant &&
3260       // Don't increase # computations.
3261       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3262     // We can only do this xform if we know that bits from X that are set in C2
3263     // but not in C1 are already zero.  Likewise for Y.
3264     const APInt &LHSMask =
3265       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3266     const APInt &RHSMask =
3267       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3268
3269     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3270         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3271       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3272                               N0.getOperand(0), N1.getOperand(0));
3273       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3274                          DAG.getConstant(LHSMask | RHSMask, VT));
3275     }
3276   }
3277
3278   // See if this is some rotate idiom.
3279   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3280     return SDValue(Rot, 0);
3281
3282   // Simplify the operands using demanded-bits information.
3283   if (!VT.isVector() &&
3284       SimplifyDemandedBits(SDValue(N, 0)))
3285     return SDValue(N, 0);
3286
3287   return SDValue();
3288 }
3289
3290 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3291 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3292   if (Op.getOpcode() == ISD::AND) {
3293     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3294       Mask = Op.getOperand(1);
3295       Op = Op.getOperand(0);
3296     } else {
3297       return false;
3298     }
3299   }
3300
3301   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3302     Shift = Op;
3303     return true;
3304   }
3305
3306   return false;
3307 }
3308
3309 // Return true if we can prove that, whenever Neg and Pos are both in the
3310 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3311 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3312 //
3313 //     (or (shift1 X, Neg), (shift2 X, Pos))
3314 //
3315 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3316 // shift1 by Neg.  The range [0, OpSize) means that we only need to consider
3317 // shift amounts with defined behavior.
3318 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3319   // If OpSize is a power of 2 then:
3320   //
3321   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3322   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3323   //
3324   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3325   // for the stronger condition:
3326   //
3327   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3328   //
3329   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3330   // we can just replace Neg with Neg' for the rest of the function.
3331   //
3332   // In other cases we check for the even stronger condition:
3333   //
3334   //     Neg == OpSize - Pos                                    [B]
3335   //
3336   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3337   // behavior if Pos == 0 (and consequently Neg == OpSize).
3338   // 
3339   // We could actually use [A] whenever OpSize is a power of 2, but the
3340   // only extra cases that it would match are those uninteresting ones
3341   // where Neg and Pos are never in range at the same time.  E.g. for
3342   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3343   // as well as (sub 32, Pos), but:
3344   //
3345   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3346   //
3347   // always invokes undefined behavior for 32-bit X.
3348   //
3349   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3350   unsigned LoBits = 0;
3351   if (Neg.getOpcode() == ISD::AND &&
3352       isPowerOf2_64(OpSize) &&
3353       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3354       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3355     Neg = Neg.getOperand(0);
3356     LoBits = Log2_64(OpSize);
3357   }
3358
3359   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3360   if (Neg.getOpcode() != ISD::SUB)
3361     return 0;
3362   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3363   if (!NegC)
3364     return 0;
3365   SDValue NegOp1 = Neg.getOperand(1);
3366
3367   // The condition we need is now:
3368   //
3369   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3370   //
3371   // If NegOp1 == Pos then we need:
3372   //
3373   //              OpSize & Mask == NegC & Mask
3374   //
3375   // (because "x & Mask" is a truncation and distributes through subtraction).
3376   APInt Width;
3377   if (Pos == NegOp1)
3378     Width = NegC->getAPIntValue();
3379   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3380   // Then the condition we want to prove becomes:
3381   //
3382   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3383   //
3384   // which, again because "x & Mask" is a truncation, becomes:
3385   //
3386   //                NegC & Mask == (OpSize - PosC) & Mask
3387   //              OpSize & Mask == (NegC + PosC) & Mask
3388   else if (Pos.getOpcode() == ISD::ADD &&
3389            Pos.getOperand(0) == NegOp1 &&
3390            Pos.getOperand(1).getOpcode() == ISD::Constant)
3391     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3392              NegC->getAPIntValue());
3393   else
3394     return false;
3395
3396   // Now we just need to check that OpSize & Mask == Width & Mask.
3397   if (LoBits)
3398     return Width.getLoBits(LoBits) == 0;
3399   return Width == OpSize;
3400 }
3401
3402 // A subroutine of MatchRotate used once we have found an OR of two opposite
3403 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3404 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3405 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3406 // Neg with outer conversions stripped away.
3407 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3408                                        SDValue Neg, SDValue InnerPos,
3409                                        SDValue InnerNeg, unsigned PosOpcode,
3410                                        unsigned NegOpcode, SDLoc DL) {
3411   // fold (or (shl x, (*ext y)),
3412   //          (srl x, (*ext (sub 32, y)))) ->
3413   //   (rotl x, y) or (rotr x, (sub 32, y))
3414   //
3415   // fold (or (shl x, (*ext (sub 32, y))),
3416   //          (srl x, (*ext y))) ->
3417   //   (rotr x, y) or (rotl x, (sub 32, y))
3418   EVT VT = Shifted.getValueType();
3419   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3420     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3421     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3422                        HasPos ? Pos : Neg).getNode();
3423   }
3424
3425   // fold (or (shl (*ext x), (*ext y)),
3426   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3427   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3428   //
3429   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3430   //          (srl (*ext x), (*ext y))) ->
3431   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3432   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3433       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3434     SDValue InnerShifted = Shifted.getOperand(0);
3435     EVT InnerVT = InnerShifted.getValueType();
3436     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3437     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3438       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3439         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3440                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3441         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3442       }
3443     }
3444   }
3445
3446   return 0;
3447 }
3448
3449 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3450 // idioms for rotate, and if the target supports rotation instructions, generate
3451 // a rot[lr].
3452 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3453   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3454   EVT VT = LHS.getValueType();
3455   if (!TLI.isTypeLegal(VT)) return 0;
3456
3457   // The target must have at least one rotate flavor.
3458   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3459   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3460   if (!HasROTL && !HasROTR) return 0;
3461
3462   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3463   SDValue LHSShift;   // The shift.
3464   SDValue LHSMask;    // AND value if any.
3465   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3466     return 0; // Not part of a rotate.
3467
3468   SDValue RHSShift;   // The shift.
3469   SDValue RHSMask;    // AND value if any.
3470   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3471     return 0; // Not part of a rotate.
3472
3473   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3474     return 0;   // Not shifting the same value.
3475
3476   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3477     return 0;   // Shifts must disagree.
3478
3479   // Canonicalize shl to left side in a shl/srl pair.
3480   if (RHSShift.getOpcode() == ISD::SHL) {
3481     std::swap(LHS, RHS);
3482     std::swap(LHSShift, RHSShift);
3483     std::swap(LHSMask , RHSMask );
3484   }
3485
3486   unsigned OpSizeInBits = VT.getSizeInBits();
3487   SDValue LHSShiftArg = LHSShift.getOperand(0);
3488   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3489   SDValue RHSShiftArg = RHSShift.getOperand(0);
3490   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3491
3492   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3493   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3494   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3495       RHSShiftAmt.getOpcode() == ISD::Constant) {
3496     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3497     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3498     if ((LShVal + RShVal) != OpSizeInBits)
3499       return 0;
3500
3501     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3502                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3503
3504     // If there is an AND of either shifted operand, apply it to the result.
3505     if (LHSMask.getNode() || RHSMask.getNode()) {
3506       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3507
3508       if (LHSMask.getNode()) {
3509         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3510         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3511       }
3512       if (RHSMask.getNode()) {
3513         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3514         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3515       }
3516
3517       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3518     }
3519
3520     return Rot.getNode();
3521   }
3522
3523   // If there is a mask here, and we have a variable shift, we can't be sure
3524   // that we're masking out the right stuff.
3525   if (LHSMask.getNode() || RHSMask.getNode())
3526     return 0;
3527
3528   // If the shift amount is sign/zext/any-extended just peel it off.
3529   SDValue LExtOp0 = LHSShiftAmt;
3530   SDValue RExtOp0 = RHSShiftAmt;
3531   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3532        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3533        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3534        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3535       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3536        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3537        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3538        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3539     LExtOp0 = LHSShiftAmt.getOperand(0);
3540     RExtOp0 = RHSShiftAmt.getOperand(0);
3541   }
3542
3543   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3544                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3545   if (TryL)
3546     return TryL;
3547
3548   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3549                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3550   if (TryR)
3551     return TryR;
3552
3553   return 0;
3554 }
3555
3556 SDValue DAGCombiner::visitXOR(SDNode *N) {
3557   SDValue N0 = N->getOperand(0);
3558   SDValue N1 = N->getOperand(1);
3559   SDValue LHS, RHS, CC;
3560   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3561   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3562   EVT VT = N0.getValueType();
3563
3564   // fold vector ops
3565   if (VT.isVector()) {
3566     SDValue FoldedVOp = SimplifyVBinOp(N);
3567     if (FoldedVOp.getNode()) return FoldedVOp;
3568
3569     // fold (xor x, 0) -> x, vector edition
3570     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3571       return N1;
3572     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3573       return N0;
3574   }
3575
3576   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3577   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3578     return DAG.getConstant(0, VT);
3579   // fold (xor x, undef) -> undef
3580   if (N0.getOpcode() == ISD::UNDEF)
3581     return N0;
3582   if (N1.getOpcode() == ISD::UNDEF)
3583     return N1;
3584   // fold (xor c1, c2) -> c1^c2
3585   if (N0C && N1C)
3586     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3587   // canonicalize constant to RHS
3588   if (N0C && !N1C)
3589     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3590   // fold (xor x, 0) -> x
3591   if (N1C && N1C->isNullValue())
3592     return N0;
3593   // reassociate xor
3594   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3595   if (RXOR.getNode() != 0)
3596     return RXOR;
3597
3598   // fold !(x cc y) -> (x !cc y)
3599   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3600     bool isInt = LHS.getValueType().isInteger();
3601     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3602                                                isInt);
3603
3604     if (!LegalOperations ||
3605         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3606       switch (N0.getOpcode()) {
3607       default:
3608         llvm_unreachable("Unhandled SetCC Equivalent!");
3609       case ISD::SETCC:
3610         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3611       case ISD::SELECT_CC:
3612         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3613                                N0.getOperand(3), NotCC);
3614       }
3615     }
3616   }
3617
3618   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3619   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3620       N0.getNode()->hasOneUse() &&
3621       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3622     SDValue V = N0.getOperand(0);
3623     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3624                     DAG.getConstant(1, V.getValueType()));
3625     AddToWorkList(V.getNode());
3626     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3627   }
3628
3629   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3630   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3631       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3632     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3633     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3634       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3635       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3636       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3637       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3638       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3639     }
3640   }
3641   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3642   if (N1C && N1C->isAllOnesValue() &&
3643       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3644     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3645     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3646       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3647       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3648       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3649       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3650       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3651     }
3652   }
3653   // fold (xor (and x, y), y) -> (and (not x), y)
3654   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3655       N0->getOperand(1) == N1) {
3656     SDValue X = N0->getOperand(0);
3657     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3658     AddToWorkList(NotX.getNode());
3659     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3660   }
3661   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3662   if (N1C && N0.getOpcode() == ISD::XOR) {
3663     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3664     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3665     if (N00C)
3666       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3667                          DAG.getConstant(N1C->getAPIntValue() ^
3668                                          N00C->getAPIntValue(), VT));
3669     if (N01C)
3670       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3671                          DAG.getConstant(N1C->getAPIntValue() ^
3672                                          N01C->getAPIntValue(), VT));
3673   }
3674   // fold (xor x, x) -> 0
3675   if (N0 == N1)
3676     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3677
3678   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3679   if (N0.getOpcode() == N1.getOpcode()) {
3680     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3681     if (Tmp.getNode()) return Tmp;
3682   }
3683
3684   // Simplify the expression using non-local knowledge.
3685   if (!VT.isVector() &&
3686       SimplifyDemandedBits(SDValue(N, 0)))
3687     return SDValue(N, 0);
3688
3689   return SDValue();
3690 }
3691
3692 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3693 /// the shift amount is a constant.
3694 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3695   SDNode *LHS = N->getOperand(0).getNode();
3696   if (!LHS->hasOneUse()) return SDValue();
3697
3698   // We want to pull some binops through shifts, so that we have (and (shift))
3699   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3700   // thing happens with address calculations, so it's important to canonicalize
3701   // it.
3702   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3703
3704   switch (LHS->getOpcode()) {
3705   default: return SDValue();
3706   case ISD::OR:
3707   case ISD::XOR:
3708     HighBitSet = false; // We can only transform sra if the high bit is clear.
3709     break;
3710   case ISD::AND:
3711     HighBitSet = true;  // We can only transform sra if the high bit is set.
3712     break;
3713   case ISD::ADD:
3714     if (N->getOpcode() != ISD::SHL)
3715       return SDValue(); // only shl(add) not sr[al](add).
3716     HighBitSet = false; // We can only transform sra if the high bit is clear.
3717     break;
3718   }
3719
3720   // We require the RHS of the binop to be a constant as well.
3721   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3722   if (!BinOpCst) return SDValue();
3723
3724   // FIXME: disable this unless the input to the binop is a shift by a constant.
3725   // If it is not a shift, it pessimizes some common cases like:
3726   //
3727   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3728   //    int bar(int *X, int i) { return X[i & 255]; }
3729   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3730   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3731        BinOpLHSVal->getOpcode() != ISD::SRA &&
3732        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3733       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3734     return SDValue();
3735
3736   EVT VT = N->getValueType(0);
3737
3738   // If this is a signed shift right, and the high bit is modified by the
3739   // logical operation, do not perform the transformation. The highBitSet
3740   // boolean indicates the value of the high bit of the constant which would
3741   // cause it to be modified for this operation.
3742   if (N->getOpcode() == ISD::SRA) {
3743     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3744     if (BinOpRHSSignSet != HighBitSet)
3745       return SDValue();
3746   }
3747
3748   // Fold the constants, shifting the binop RHS by the shift amount.
3749   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3750                                N->getValueType(0),
3751                                LHS->getOperand(1), N->getOperand(1));
3752
3753   // Create the new shift.
3754   SDValue NewShift = DAG.getNode(N->getOpcode(),
3755                                  SDLoc(LHS->getOperand(0)),
3756                                  VT, LHS->getOperand(0), N->getOperand(1));
3757
3758   // Create the new binop.
3759   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3760 }
3761
3762 SDValue DAGCombiner::visitSHL(SDNode *N) {
3763   SDValue N0 = N->getOperand(0);
3764   SDValue N1 = N->getOperand(1);
3765   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3766   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3767   EVT VT = N0.getValueType();
3768   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3769
3770   // fold vector ops
3771   if (VT.isVector()) {
3772     SDValue FoldedVOp = SimplifyVBinOp(N);
3773     if (FoldedVOp.getNode()) return FoldedVOp;
3774   }
3775
3776   // fold (shl c1, c2) -> c1<<c2
3777   if (N0C && N1C)
3778     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3779   // fold (shl 0, x) -> 0
3780   if (N0C && N0C->isNullValue())
3781     return N0;
3782   // fold (shl x, c >= size(x)) -> undef
3783   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3784     return DAG.getUNDEF(VT);
3785   // fold (shl x, 0) -> x
3786   if (N1C && N1C->isNullValue())
3787     return N0;
3788   // fold (shl undef, x) -> 0
3789   if (N0.getOpcode() == ISD::UNDEF)
3790     return DAG.getConstant(0, VT);
3791   // if (shl x, c) is known to be zero, return 0
3792   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3793                             APInt::getAllOnesValue(OpSizeInBits)))
3794     return DAG.getConstant(0, VT);
3795   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3796   if (N1.getOpcode() == ISD::TRUNCATE &&
3797       N1.getOperand(0).getOpcode() == ISD::AND &&
3798       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3799     SDValue N101 = N1.getOperand(0).getOperand(1);
3800     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3801       EVT TruncVT = N1.getValueType();
3802       SDValue N100 = N1.getOperand(0).getOperand(0);
3803       APInt TruncC = N101C->getAPIntValue();
3804       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3805       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3806                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3807                                      DAG.getNode(ISD::TRUNCATE,
3808                                                  SDLoc(N),
3809                                                  TruncVT, N100),
3810                                      DAG.getConstant(TruncC, TruncVT)));
3811     }
3812   }
3813
3814   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3815     return SDValue(N, 0);
3816
3817   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3818   if (N1C && N0.getOpcode() == ISD::SHL &&
3819       N0.getOperand(1).getOpcode() == ISD::Constant) {
3820     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3821     uint64_t c2 = N1C->getZExtValue();
3822     if (c1 + c2 >= OpSizeInBits)
3823       return DAG.getConstant(0, VT);
3824     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3825                        DAG.getConstant(c1 + c2, N1.getValueType()));
3826   }
3827
3828   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3829   // For this to be valid, the second form must not preserve any of the bits
3830   // that are shifted out by the inner shift in the first form.  This means
3831   // the outer shift size must be >= the number of bits added by the ext.
3832   // As a corollary, we don't care what kind of ext it is.
3833   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3834               N0.getOpcode() == ISD::ANY_EXTEND ||
3835               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3836       N0.getOperand(0).getOpcode() == ISD::SHL &&
3837       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3838     uint64_t c1 =
3839       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3840     uint64_t c2 = N1C->getZExtValue();
3841     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3842     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3843     if (c2 >= OpSizeInBits - InnerShiftSize) {
3844       if (c1 + c2 >= OpSizeInBits)
3845         return DAG.getConstant(0, VT);
3846       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3847                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3848                                      N0.getOperand(0)->getOperand(0)),
3849                          DAG.getConstant(c1 + c2, N1.getValueType()));
3850     }
3851   }
3852
3853   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3854   // Only fold this if the inner zext has no other uses to avoid increasing
3855   // the total number of instructions.
3856   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3857       N0.getOperand(0).getOpcode() == ISD::SRL &&
3858       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3859     uint64_t c1 =
3860       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3861     if (c1 < VT.getSizeInBits()) {
3862       uint64_t c2 = N1C->getZExtValue();
3863       if (c1 == c2) {
3864         SDValue NewOp0 = N0.getOperand(0);
3865         EVT CountVT = NewOp0.getOperand(1).getValueType();
3866         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3867                                      NewOp0, DAG.getConstant(c2, CountVT));
3868         AddToWorkList(NewSHL.getNode());
3869         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3870       }
3871     }
3872   }
3873
3874   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3875   //                               (and (srl x, (sub c1, c2), MASK)
3876   // Only fold this if the inner shift has no other uses -- if it does, folding
3877   // this will increase the total number of instructions.
3878   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3879       N0.getOperand(1).getOpcode() == ISD::Constant) {
3880     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3881     if (c1 < VT.getSizeInBits()) {
3882       uint64_t c2 = N1C->getZExtValue();
3883       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3884                                          VT.getSizeInBits() - c1);
3885       SDValue Shift;
3886       if (c2 > c1) {
3887         Mask = Mask.shl(c2-c1);
3888         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3889                             DAG.getConstant(c2-c1, N1.getValueType()));
3890       } else {
3891         Mask = Mask.lshr(c1-c2);
3892         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3893                             DAG.getConstant(c1-c2, N1.getValueType()));
3894       }
3895       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3896                          DAG.getConstant(Mask, VT));
3897     }
3898   }
3899   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3900   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3901     SDValue HiBitsMask =
3902       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3903                                             VT.getSizeInBits() -
3904                                               N1C->getZExtValue()),
3905                       VT);
3906     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3907                        HiBitsMask);
3908   }
3909
3910   if (N1C) {
3911     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3912     if (NewSHL.getNode())
3913       return NewSHL;
3914   }
3915
3916   return SDValue();
3917 }
3918
3919 SDValue DAGCombiner::visitSRA(SDNode *N) {
3920   SDValue N0 = N->getOperand(0);
3921   SDValue N1 = N->getOperand(1);
3922   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3923   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3924   EVT VT = N0.getValueType();
3925   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3926
3927   // fold vector ops
3928   if (VT.isVector()) {
3929     SDValue FoldedVOp = SimplifyVBinOp(N);
3930     if (FoldedVOp.getNode()) return FoldedVOp;
3931   }
3932
3933   // fold (sra c1, c2) -> (sra c1, c2)
3934   if (N0C && N1C)
3935     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3936   // fold (sra 0, x) -> 0
3937   if (N0C && N0C->isNullValue())
3938     return N0;
3939   // fold (sra -1, x) -> -1
3940   if (N0C && N0C->isAllOnesValue())
3941     return N0;
3942   // fold (sra x, (setge c, size(x))) -> undef
3943   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3944     return DAG.getUNDEF(VT);
3945   // fold (sra x, 0) -> x
3946   if (N1C && N1C->isNullValue())
3947     return N0;
3948   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3949   // sext_inreg.
3950   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3951     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3952     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3953     if (VT.isVector())
3954       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3955                                ExtVT, VT.getVectorNumElements());
3956     if ((!LegalOperations ||
3957          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3958       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3959                          N0.getOperand(0), DAG.getValueType(ExtVT));
3960   }
3961
3962   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3963   if (N1C && N0.getOpcode() == ISD::SRA) {
3964     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3965       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3966       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3967       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3968                          DAG.getConstant(Sum, N1C->getValueType(0)));
3969     }
3970   }
3971
3972   // fold (sra (shl X, m), (sub result_size, n))
3973   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3974   // result_size - n != m.
3975   // If truncate is free for the target sext(shl) is likely to result in better
3976   // code.
3977   if (N0.getOpcode() == ISD::SHL) {
3978     // Get the two constanst of the shifts, CN0 = m, CN = n.
3979     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3980     if (N01C && N1C) {
3981       // Determine what the truncate's result bitsize and type would be.
3982       EVT TruncVT =
3983         EVT::getIntegerVT(*DAG.getContext(),
3984                           OpSizeInBits - N1C->getZExtValue());
3985       // Determine the residual right-shift amount.
3986       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3987
3988       // If the shift is not a no-op (in which case this should be just a sign
3989       // extend already), the truncated to type is legal, sign_extend is legal
3990       // on that type, and the truncate to that type is both legal and free,
3991       // perform the transform.
3992       if ((ShiftAmt > 0) &&
3993           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3994           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3995           TLI.isTruncateFree(VT, TruncVT)) {
3996
3997           SDValue Amt = DAG.getConstant(ShiftAmt,
3998               getShiftAmountTy(N0.getOperand(0).getValueType()));
3999           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4000                                       N0.getOperand(0), Amt);
4001           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4002                                       Shift);
4003           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4004                              N->getValueType(0), Trunc);
4005       }
4006     }
4007   }
4008
4009   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4010   if (N1.getOpcode() == ISD::TRUNCATE &&
4011       N1.getOperand(0).getOpcode() == ISD::AND &&
4012       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4013     SDValue N101 = N1.getOperand(0).getOperand(1);
4014     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4015       EVT TruncVT = N1.getValueType();
4016       SDValue N100 = N1.getOperand(0).getOperand(0);
4017       APInt TruncC = N101C->getAPIntValue();
4018       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
4019       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4020                          DAG.getNode(ISD::AND, SDLoc(N),
4021                                      TruncVT,
4022                                      DAG.getNode(ISD::TRUNCATE,
4023                                                  SDLoc(N),
4024                                                  TruncVT, N100),
4025                                      DAG.getConstant(TruncC, TruncVT)));
4026     }
4027   }
4028
4029   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4030   //      if c1 is equal to the number of bits the trunc removes
4031   if (N0.getOpcode() == ISD::TRUNCATE &&
4032       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4033        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4034       N0.getOperand(0).hasOneUse() &&
4035       N0.getOperand(0).getOperand(1).hasOneUse() &&
4036       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4037     EVT LargeVT = N0.getOperand(0).getValueType();
4038     ConstantSDNode *LargeShiftAmt =
4039       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4040
4041     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4042         LargeShiftAmt->getZExtValue()) {
4043       SDValue Amt =
4044         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4045               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4046       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4047                                 N0.getOperand(0).getOperand(0), Amt);
4048       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4049     }
4050   }
4051
4052   // Simplify, based on bits shifted out of the LHS.
4053   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4054     return SDValue(N, 0);
4055
4056
4057   // If the sign bit is known to be zero, switch this to a SRL.
4058   if (DAG.SignBitIsZero(N0))
4059     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4060
4061   if (N1C) {
4062     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4063     if (NewSRA.getNode())
4064       return NewSRA;
4065   }
4066
4067   return SDValue();
4068 }
4069
4070 SDValue DAGCombiner::visitSRL(SDNode *N) {
4071   SDValue N0 = N->getOperand(0);
4072   SDValue N1 = N->getOperand(1);
4073   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4074   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4075   EVT VT = N0.getValueType();
4076   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4077
4078   // fold vector ops
4079   if (VT.isVector()) {
4080     SDValue FoldedVOp = SimplifyVBinOp(N);
4081     if (FoldedVOp.getNode()) return FoldedVOp;
4082   }
4083
4084   // fold (srl c1, c2) -> c1 >>u c2
4085   if (N0C && N1C)
4086     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4087   // fold (srl 0, x) -> 0
4088   if (N0C && N0C->isNullValue())
4089     return N0;
4090   // fold (srl x, c >= size(x)) -> undef
4091   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4092     return DAG.getUNDEF(VT);
4093   // fold (srl x, 0) -> x
4094   if (N1C && N1C->isNullValue())
4095     return N0;
4096   // if (srl x, c) is known to be zero, return 0
4097   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4098                                    APInt::getAllOnesValue(OpSizeInBits)))
4099     return DAG.getConstant(0, VT);
4100
4101   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4102   if (N1C && N0.getOpcode() == ISD::SRL &&
4103       N0.getOperand(1).getOpcode() == ISD::Constant) {
4104     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4105     uint64_t c2 = N1C->getZExtValue();
4106     if (c1 + c2 >= OpSizeInBits)
4107       return DAG.getConstant(0, VT);
4108     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4109                        DAG.getConstant(c1 + c2, N1.getValueType()));
4110   }
4111
4112   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4113   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4114       N0.getOperand(0).getOpcode() == ISD::SRL &&
4115       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4116     uint64_t c1 =
4117       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4118     uint64_t c2 = N1C->getZExtValue();
4119     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4120     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4121     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4122     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4123     if (c1 + OpSizeInBits == InnerShiftSize) {
4124       if (c1 + c2 >= InnerShiftSize)
4125         return DAG.getConstant(0, VT);
4126       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4127                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4128                                      N0.getOperand(0)->getOperand(0),
4129                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4130     }
4131   }
4132
4133   // fold (srl (shl x, c), c) -> (and x, cst2)
4134   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4135       N0.getValueSizeInBits() <= 64) {
4136     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4137     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4138                        DAG.getConstant(~0ULL >> ShAmt, VT));
4139   }
4140
4141   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4142   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4143     // Shifting in all undef bits?
4144     EVT SmallVT = N0.getOperand(0).getValueType();
4145     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4146       return DAG.getUNDEF(VT);
4147
4148     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4149       uint64_t ShiftAmt = N1C->getZExtValue();
4150       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4151                                        N0.getOperand(0),
4152                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4153       AddToWorkList(SmallShift.getNode());
4154       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4155       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4156                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4157                          DAG.getConstant(Mask, VT));
4158     }
4159   }
4160
4161   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4162   // bit, which is unmodified by sra.
4163   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4164     if (N0.getOpcode() == ISD::SRA)
4165       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4166   }
4167
4168   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4169   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4170       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4171     APInt KnownZero, KnownOne;
4172     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4173
4174     // If any of the input bits are KnownOne, then the input couldn't be all
4175     // zeros, thus the result of the srl will always be zero.
4176     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4177
4178     // If all of the bits input the to ctlz node are known to be zero, then
4179     // the result of the ctlz is "32" and the result of the shift is one.
4180     APInt UnknownBits = ~KnownZero;
4181     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4182
4183     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4184     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4185       // Okay, we know that only that the single bit specified by UnknownBits
4186       // could be set on input to the CTLZ node. If this bit is set, the SRL
4187       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4188       // to an SRL/XOR pair, which is likely to simplify more.
4189       unsigned ShAmt = UnknownBits.countTrailingZeros();
4190       SDValue Op = N0.getOperand(0);
4191
4192       if (ShAmt) {
4193         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4194                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4195         AddToWorkList(Op.getNode());
4196       }
4197
4198       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4199                          Op, DAG.getConstant(1, VT));
4200     }
4201   }
4202
4203   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4204   if (N1.getOpcode() == ISD::TRUNCATE &&
4205       N1.getOperand(0).getOpcode() == ISD::AND &&
4206       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4207     SDValue N101 = N1.getOperand(0).getOperand(1);
4208     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4209       EVT TruncVT = N1.getValueType();
4210       SDValue N100 = N1.getOperand(0).getOperand(0);
4211       APInt TruncC = N101C->getAPIntValue();
4212       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4213       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4214                          DAG.getNode(ISD::AND, SDLoc(N),
4215                                      TruncVT,
4216                                      DAG.getNode(ISD::TRUNCATE,
4217                                                  SDLoc(N),
4218                                                  TruncVT, N100),
4219                                      DAG.getConstant(TruncC, TruncVT)));
4220     }
4221   }
4222
4223   // fold operands of srl based on knowledge that the low bits are not
4224   // demanded.
4225   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4226     return SDValue(N, 0);
4227
4228   if (N1C) {
4229     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4230     if (NewSRL.getNode())
4231       return NewSRL;
4232   }
4233
4234   // Attempt to convert a srl of a load into a narrower zero-extending load.
4235   SDValue NarrowLoad = ReduceLoadWidth(N);
4236   if (NarrowLoad.getNode())
4237     return NarrowLoad;
4238
4239   // Here is a common situation. We want to optimize:
4240   //
4241   //   %a = ...
4242   //   %b = and i32 %a, 2
4243   //   %c = srl i32 %b, 1
4244   //   brcond i32 %c ...
4245   //
4246   // into
4247   //
4248   //   %a = ...
4249   //   %b = and %a, 2
4250   //   %c = setcc eq %b, 0
4251   //   brcond %c ...
4252   //
4253   // However when after the source operand of SRL is optimized into AND, the SRL
4254   // itself may not be optimized further. Look for it and add the BRCOND into
4255   // the worklist.
4256   if (N->hasOneUse()) {
4257     SDNode *Use = *N->use_begin();
4258     if (Use->getOpcode() == ISD::BRCOND)
4259       AddToWorkList(Use);
4260     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4261       // Also look pass the truncate.
4262       Use = *Use->use_begin();
4263       if (Use->getOpcode() == ISD::BRCOND)
4264         AddToWorkList(Use);
4265     }
4266   }
4267
4268   return SDValue();
4269 }
4270
4271 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4272   SDValue N0 = N->getOperand(0);
4273   EVT VT = N->getValueType(0);
4274
4275   // fold (ctlz c1) -> c2
4276   if (isa<ConstantSDNode>(N0))
4277     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4278   return SDValue();
4279 }
4280
4281 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4282   SDValue N0 = N->getOperand(0);
4283   EVT VT = N->getValueType(0);
4284
4285   // fold (ctlz_zero_undef c1) -> c2
4286   if (isa<ConstantSDNode>(N0))
4287     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4288   return SDValue();
4289 }
4290
4291 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4292   SDValue N0 = N->getOperand(0);
4293   EVT VT = N->getValueType(0);
4294
4295   // fold (cttz c1) -> c2
4296   if (isa<ConstantSDNode>(N0))
4297     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4298   return SDValue();
4299 }
4300
4301 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4302   SDValue N0 = N->getOperand(0);
4303   EVT VT = N->getValueType(0);
4304
4305   // fold (cttz_zero_undef c1) -> c2
4306   if (isa<ConstantSDNode>(N0))
4307     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4308   return SDValue();
4309 }
4310
4311 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4312   SDValue N0 = N->getOperand(0);
4313   EVT VT = N->getValueType(0);
4314
4315   // fold (ctpop c1) -> c2
4316   if (isa<ConstantSDNode>(N0))
4317     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4318   return SDValue();
4319 }
4320
4321 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4322   SDValue N0 = N->getOperand(0);
4323   SDValue N1 = N->getOperand(1);
4324   SDValue N2 = N->getOperand(2);
4325   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4326   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4327   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4328   EVT VT = N->getValueType(0);
4329   EVT VT0 = N0.getValueType();
4330
4331   // fold (select C, X, X) -> X
4332   if (N1 == N2)
4333     return N1;
4334   // fold (select true, X, Y) -> X
4335   if (N0C && !N0C->isNullValue())
4336     return N1;
4337   // fold (select false, X, Y) -> Y
4338   if (N0C && N0C->isNullValue())
4339     return N2;
4340   // fold (select C, 1, X) -> (or C, X)
4341   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4342     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4343   // fold (select C, 0, 1) -> (xor C, 1)
4344   if (VT.isInteger() &&
4345       (VT0 == MVT::i1 ||
4346        (VT0.isInteger() &&
4347         TLI.getBooleanContents(false) ==
4348         TargetLowering::ZeroOrOneBooleanContent)) &&
4349       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4350     SDValue XORNode;
4351     if (VT == VT0)
4352       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4353                          N0, DAG.getConstant(1, VT0));
4354     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4355                           N0, DAG.getConstant(1, VT0));
4356     AddToWorkList(XORNode.getNode());
4357     if (VT.bitsGT(VT0))
4358       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4359     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4360   }
4361   // fold (select C, 0, X) -> (and (not C), X)
4362   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4363     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4364     AddToWorkList(NOTNode.getNode());
4365     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4366   }
4367   // fold (select C, X, 1) -> (or (not C), X)
4368   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4369     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4370     AddToWorkList(NOTNode.getNode());
4371     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4372   }
4373   // fold (select C, X, 0) -> (and C, X)
4374   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4375     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4376   // fold (select X, X, Y) -> (or X, Y)
4377   // fold (select X, 1, Y) -> (or X, Y)
4378   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4379     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4380   // fold (select X, Y, X) -> (and X, Y)
4381   // fold (select X, Y, 0) -> (and X, Y)
4382   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4383     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4384
4385   // If we can fold this based on the true/false value, do so.
4386   if (SimplifySelectOps(N, N1, N2))
4387     return SDValue(N, 0);  // Don't revisit N.
4388
4389   // fold selects based on a setcc into other things, such as min/max/abs
4390   if (N0.getOpcode() == ISD::SETCC) {
4391     // FIXME:
4392     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4393     // having to say they don't support SELECT_CC on every type the DAG knows
4394     // about, since there is no way to mark an opcode illegal at all value types
4395     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4396         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4397       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4398                          N0.getOperand(0), N0.getOperand(1),
4399                          N1, N2, N0.getOperand(2));
4400     return SimplifySelect(SDLoc(N), N0, N1, N2);
4401   }
4402
4403   return SDValue();
4404 }
4405
4406 static
4407 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4408   SDLoc DL(N);
4409   EVT LoVT, HiVT;
4410   llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4411
4412   // Split the inputs.
4413   SDValue Lo, Hi, LL, LH, RL, RH;
4414   llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4415   llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4416
4417   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4418   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4419
4420   return std::make_pair(Lo, Hi);
4421 }
4422
4423 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4424   SDValue N0 = N->getOperand(0);
4425   SDValue N1 = N->getOperand(1);
4426   SDValue N2 = N->getOperand(2);
4427   SDLoc DL(N);
4428
4429   // Canonicalize integer abs.
4430   // vselect (setg[te] X,  0),  X, -X ->
4431   // vselect (setgt    X, -1),  X, -X ->
4432   // vselect (setl[te] X,  0), -X,  X ->
4433   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4434   if (N0.getOpcode() == ISD::SETCC) {
4435     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4436     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4437     bool isAbs = false;
4438     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4439
4440     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4441          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4442         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4443       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4444     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4445              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4446       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4447
4448     if (isAbs) {
4449       EVT VT = LHS.getValueType();
4450       SDValue Shift = DAG.getNode(
4451           ISD::SRA, DL, VT, LHS,
4452           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4453       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4454       AddToWorkList(Shift.getNode());
4455       AddToWorkList(Add.getNode());
4456       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4457     }
4458   }
4459
4460   // If the VSELECT result requires splitting and the mask is provided by a
4461   // SETCC, then split both nodes and its operands before legalization. This
4462   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4463   // and enables future optimizations (e.g. min/max pattern matching on X86).
4464   if (N0.getOpcode() == ISD::SETCC) {
4465     EVT VT = N->getValueType(0);
4466
4467     // Check if any splitting is required.
4468     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4469         TargetLowering::TypeSplitVector)
4470       return SDValue();
4471
4472     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4473     llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4474     llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4475     llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4476
4477     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4478     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4479
4480     // Add the new VSELECT nodes to the work list in case they need to be split
4481     // again.
4482     AddToWorkList(Lo.getNode());
4483     AddToWorkList(Hi.getNode());
4484
4485     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4486   }
4487
4488   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4489   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4490     return N1;
4491   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4492   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4493     return N2;
4494
4495   return SDValue();
4496 }
4497
4498 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4499   SDValue N0 = N->getOperand(0);
4500   SDValue N1 = N->getOperand(1);
4501   SDValue N2 = N->getOperand(2);
4502   SDValue N3 = N->getOperand(3);
4503   SDValue N4 = N->getOperand(4);
4504   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4505
4506   // fold select_cc lhs, rhs, x, x, cc -> x
4507   if (N2 == N3)
4508     return N2;
4509
4510   // Determine if the condition we're dealing with is constant
4511   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4512                               N0, N1, CC, SDLoc(N), false);
4513   if (SCC.getNode()) {
4514     AddToWorkList(SCC.getNode());
4515
4516     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4517       if (!SCCC->isNullValue())
4518         return N2;    // cond always true -> true val
4519       else
4520         return N3;    // cond always false -> false val
4521     }
4522
4523     // Fold to a simpler select_cc
4524     if (SCC.getOpcode() == ISD::SETCC)
4525       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4526                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4527                          SCC.getOperand(2));
4528   }
4529
4530   // If we can fold this based on the true/false value, do so.
4531   if (SimplifySelectOps(N, N2, N3))
4532     return SDValue(N, 0);  // Don't revisit N.
4533
4534   // fold select_cc into other things, such as min/max/abs
4535   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4536 }
4537
4538 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4539   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4540                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4541                        SDLoc(N));
4542 }
4543
4544 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4545 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4546 // transformation. Returns true if extension are possible and the above
4547 // mentioned transformation is profitable.
4548 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4549                                     unsigned ExtOpc,
4550                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4551                                     const TargetLowering &TLI) {
4552   bool HasCopyToRegUses = false;
4553   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4554   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4555                             UE = N0.getNode()->use_end();
4556        UI != UE; ++UI) {
4557     SDNode *User = *UI;
4558     if (User == N)
4559       continue;
4560     if (UI.getUse().getResNo() != N0.getResNo())
4561       continue;
4562     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4563     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4564       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4565       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4566         // Sign bits will be lost after a zext.
4567         return false;
4568       bool Add = false;
4569       for (unsigned i = 0; i != 2; ++i) {
4570         SDValue UseOp = User->getOperand(i);
4571         if (UseOp == N0)
4572           continue;
4573         if (!isa<ConstantSDNode>(UseOp))
4574           return false;
4575         Add = true;
4576       }
4577       if (Add)
4578         ExtendNodes.push_back(User);
4579       continue;
4580     }
4581     // If truncates aren't free and there are users we can't
4582     // extend, it isn't worthwhile.
4583     if (!isTruncFree)
4584       return false;
4585     // Remember if this value is live-out.
4586     if (User->getOpcode() == ISD::CopyToReg)
4587       HasCopyToRegUses = true;
4588   }
4589
4590   if (HasCopyToRegUses) {
4591     bool BothLiveOut = false;
4592     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4593          UI != UE; ++UI) {
4594       SDUse &Use = UI.getUse();
4595       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4596         BothLiveOut = true;
4597         break;
4598       }
4599     }
4600     if (BothLiveOut)
4601       // Both unextended and extended values are live out. There had better be
4602       // a good reason for the transformation.
4603       return ExtendNodes.size();
4604   }
4605   return true;
4606 }
4607
4608 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4609                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4610                                   ISD::NodeType ExtType) {
4611   // Extend SetCC uses if necessary.
4612   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4613     SDNode *SetCC = SetCCs[i];
4614     SmallVector<SDValue, 4> Ops;
4615
4616     for (unsigned j = 0; j != 2; ++j) {
4617       SDValue SOp = SetCC->getOperand(j);
4618       if (SOp == Trunc)
4619         Ops.push_back(ExtLoad);
4620       else
4621         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4622     }
4623
4624     Ops.push_back(SetCC->getOperand(2));
4625     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4626                                  &Ops[0], Ops.size()));
4627   }
4628 }
4629
4630 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4631   SDValue N0 = N->getOperand(0);
4632   EVT VT = N->getValueType(0);
4633
4634   // fold (sext c1) -> c1
4635   if (isa<ConstantSDNode>(N0))
4636     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4637
4638   // fold (sext (sext x)) -> (sext x)
4639   // fold (sext (aext x)) -> (sext x)
4640   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4641     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4642                        N0.getOperand(0));
4643
4644   if (N0.getOpcode() == ISD::TRUNCATE) {
4645     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4646     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4647     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4648     if (NarrowLoad.getNode()) {
4649       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4650       if (NarrowLoad.getNode() != N0.getNode()) {
4651         CombineTo(N0.getNode(), NarrowLoad);
4652         // CombineTo deleted the truncate, if needed, but not what's under it.
4653         AddToWorkList(oye);
4654       }
4655       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4656     }
4657
4658     // See if the value being truncated is already sign extended.  If so, just
4659     // eliminate the trunc/sext pair.
4660     SDValue Op = N0.getOperand(0);
4661     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4662     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4663     unsigned DestBits = VT.getScalarType().getSizeInBits();
4664     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4665
4666     if (OpBits == DestBits) {
4667       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4668       // bits, it is already ready.
4669       if (NumSignBits > DestBits-MidBits)
4670         return Op;
4671     } else if (OpBits < DestBits) {
4672       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4673       // bits, just sext from i32.
4674       if (NumSignBits > OpBits-MidBits)
4675         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4676     } else {
4677       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4678       // bits, just truncate to i32.
4679       if (NumSignBits > OpBits-MidBits)
4680         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4681     }
4682
4683     // fold (sext (truncate x)) -> (sextinreg x).
4684     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4685                                                  N0.getValueType())) {
4686       if (OpBits < DestBits)
4687         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4688       else if (OpBits > DestBits)
4689         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4690       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4691                          DAG.getValueType(N0.getValueType()));
4692     }
4693   }
4694
4695   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4696   // None of the supported targets knows how to perform load and sign extend
4697   // on vectors in one instruction.  We only perform this transformation on
4698   // scalars.
4699   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4700       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4701        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4702     bool DoXform = true;
4703     SmallVector<SDNode*, 4> SetCCs;
4704     if (!N0.hasOneUse())
4705       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4706     if (DoXform) {
4707       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4708       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4709                                        LN0->getChain(),
4710                                        LN0->getBasePtr(), N0.getValueType(),
4711                                        LN0->getMemOperand());
4712       CombineTo(N, ExtLoad);
4713       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4714                                   N0.getValueType(), ExtLoad);
4715       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4716       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4717                       ISD::SIGN_EXTEND);
4718       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4719     }
4720   }
4721
4722   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4723   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4724   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4725       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4726     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4727     EVT MemVT = LN0->getMemoryVT();
4728     if ((!LegalOperations && !LN0->isVolatile()) ||
4729         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4730       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4731                                        LN0->getChain(),
4732                                        LN0->getBasePtr(), MemVT,
4733                                        LN0->getMemOperand());
4734       CombineTo(N, ExtLoad);
4735       CombineTo(N0.getNode(),
4736                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4737                             N0.getValueType(), ExtLoad),
4738                 ExtLoad.getValue(1));
4739       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4740     }
4741   }
4742
4743   // fold (sext (and/or/xor (load x), cst)) ->
4744   //      (and/or/xor (sextload x), (sext 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::SEXTLOAD, N0.getValueType()) &&
4750       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4751     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4752     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4753       bool DoXform = true;
4754       SmallVector<SDNode*, 4> SetCCs;
4755       if (!N0.hasOneUse())
4756         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4757                                           SetCCs, TLI);
4758       if (DoXform) {
4759         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4760                                          LN0->getChain(), LN0->getBasePtr(),
4761                                          LN0->getMemoryVT(),
4762                                          LN0->getMemOperand());
4763         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4764         Mask = Mask.sext(VT.getSizeInBits());
4765         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4766                                   ExtLoad, DAG.getConstant(Mask, VT));
4767         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4768                                     SDLoc(N0.getOperand(0)),
4769                                     N0.getOperand(0).getValueType(), ExtLoad);
4770         CombineTo(N, And);
4771         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4772         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4773                         ISD::SIGN_EXTEND);
4774         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4775       }
4776     }
4777   }
4778
4779   if (N0.getOpcode() == ISD::SETCC) {
4780     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4781     // Only do this before legalize for now.
4782     if (VT.isVector() && !LegalOperations &&
4783         TLI.getBooleanContents(true) ==
4784           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4785       EVT N0VT = N0.getOperand(0).getValueType();
4786       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4787       // of the same size as the compared operands. Only optimize sext(setcc())
4788       // if this is the case.
4789       EVT SVT = getSetCCResultType(N0VT);
4790
4791       // We know that the # elements of the results is the same as the
4792       // # elements of the compare (and the # elements of the compare result
4793       // for that matter).  Check to see that they are the same size.  If so,
4794       // we know that the element size of the sext'd result matches the
4795       // element size of the compare operands.
4796       if (VT.getSizeInBits() == SVT.getSizeInBits())
4797         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4798                              N0.getOperand(1),
4799                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4800
4801       // If the desired elements are smaller or larger than the source
4802       // elements we can use a matching integer vector type and then
4803       // truncate/sign extend
4804       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4805       if (SVT == MatchingVectorType) {
4806         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4807                                N0.getOperand(0), N0.getOperand(1),
4808                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4809         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4810       }
4811     }
4812
4813     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4814     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4815     SDValue NegOne =
4816       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4817     SDValue SCC =
4818       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4819                        NegOne, DAG.getConstant(0, VT),
4820                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4821     if (SCC.getNode()) return SCC;
4822     if (!VT.isVector() &&
4823         (!LegalOperations ||
4824          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4825       return DAG.getSelect(SDLoc(N), VT,
4826                            DAG.getSetCC(SDLoc(N),
4827                            getSetCCResultType(VT),
4828                            N0.getOperand(0), N0.getOperand(1),
4829                            cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4830                            NegOne, DAG.getConstant(0, VT));
4831     }
4832   }
4833
4834   // fold (sext x) -> (zext x) if the sign bit is known zero.
4835   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4836       DAG.SignBitIsZero(N0))
4837     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4838
4839   return SDValue();
4840 }
4841
4842 // isTruncateOf - If N is a truncate of some other value, return true, record
4843 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4844 // This function computes KnownZero to avoid a duplicated call to
4845 // ComputeMaskedBits in the caller.
4846 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4847                          APInt &KnownZero) {
4848   APInt KnownOne;
4849   if (N->getOpcode() == ISD::TRUNCATE) {
4850     Op = N->getOperand(0);
4851     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4852     return true;
4853   }
4854
4855   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4856       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4857     return false;
4858
4859   SDValue Op0 = N->getOperand(0);
4860   SDValue Op1 = N->getOperand(1);
4861   assert(Op0.getValueType() == Op1.getValueType());
4862
4863   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4864   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4865   if (COp0 && COp0->isNullValue())
4866     Op = Op1;
4867   else if (COp1 && COp1->isNullValue())
4868     Op = Op0;
4869   else
4870     return false;
4871
4872   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4873
4874   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4875     return false;
4876
4877   return true;
4878 }
4879
4880 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4881   SDValue N0 = N->getOperand(0);
4882   EVT VT = N->getValueType(0);
4883
4884   // fold (zext c1) -> c1
4885   if (isa<ConstantSDNode>(N0))
4886     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4887   // fold (zext (zext x)) -> (zext x)
4888   // fold (zext (aext x)) -> (zext x)
4889   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4890     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4891                        N0.getOperand(0));
4892
4893   // fold (zext (truncate x)) -> (zext x) or
4894   //      (zext (truncate x)) -> (truncate x)
4895   // This is valid when the truncated bits of x are already zero.
4896   // FIXME: We should extend this to work for vectors too.
4897   SDValue Op;
4898   APInt KnownZero;
4899   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4900     APInt TruncatedBits =
4901       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4902       APInt(Op.getValueSizeInBits(), 0) :
4903       APInt::getBitsSet(Op.getValueSizeInBits(),
4904                         N0.getValueSizeInBits(),
4905                         std::min(Op.getValueSizeInBits(),
4906                                  VT.getSizeInBits()));
4907     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4908       if (VT.bitsGT(Op.getValueType()))
4909         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4910       if (VT.bitsLT(Op.getValueType()))
4911         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4912
4913       return Op;
4914     }
4915   }
4916
4917   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4918   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4919   if (N0.getOpcode() == ISD::TRUNCATE) {
4920     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4921     if (NarrowLoad.getNode()) {
4922       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4923       if (NarrowLoad.getNode() != N0.getNode()) {
4924         CombineTo(N0.getNode(), NarrowLoad);
4925         // CombineTo deleted the truncate, if needed, but not what's under it.
4926         AddToWorkList(oye);
4927       }
4928       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4929     }
4930   }
4931
4932   // fold (zext (truncate x)) -> (and x, mask)
4933   if (N0.getOpcode() == ISD::TRUNCATE &&
4934       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4935
4936     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4937     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4938     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4939     if (NarrowLoad.getNode()) {
4940       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4941       if (NarrowLoad.getNode() != N0.getNode()) {
4942         CombineTo(N0.getNode(), NarrowLoad);
4943         // CombineTo deleted the truncate, if needed, but not what's under it.
4944         AddToWorkList(oye);
4945       }
4946       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4947     }
4948
4949     SDValue Op = N0.getOperand(0);
4950     if (Op.getValueType().bitsLT(VT)) {
4951       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4952       AddToWorkList(Op.getNode());
4953     } else if (Op.getValueType().bitsGT(VT)) {
4954       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4955       AddToWorkList(Op.getNode());
4956     }
4957     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4958                                   N0.getValueType().getScalarType());
4959   }
4960
4961   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4962   // if either of the casts is not free.
4963   if (N0.getOpcode() == ISD::AND &&
4964       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4965       N0.getOperand(1).getOpcode() == ISD::Constant &&
4966       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4967                            N0.getValueType()) ||
4968        !TLI.isZExtFree(N0.getValueType(), VT))) {
4969     SDValue X = N0.getOperand(0).getOperand(0);
4970     if (X.getValueType().bitsLT(VT)) {
4971       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4972     } else if (X.getValueType().bitsGT(VT)) {
4973       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4974     }
4975     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4976     Mask = Mask.zext(VT.getSizeInBits());
4977     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4978                        X, DAG.getConstant(Mask, VT));
4979   }
4980
4981   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4982   // None of the supported targets knows how to perform load and vector_zext
4983   // on vectors in one instruction.  We only perform this transformation on
4984   // scalars.
4985   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4986       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4987        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4988     bool DoXform = true;
4989     SmallVector<SDNode*, 4> SetCCs;
4990     if (!N0.hasOneUse())
4991       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4992     if (DoXform) {
4993       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4994       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4995                                        LN0->getChain(),
4996                                        LN0->getBasePtr(), N0.getValueType(),
4997                                        LN0->getMemOperand());
4998       CombineTo(N, ExtLoad);
4999       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5000                                   N0.getValueType(), ExtLoad);
5001       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5002
5003       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5004                       ISD::ZERO_EXTEND);
5005       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5006     }
5007   }
5008
5009   // fold (zext (and/or/xor (load x), cst)) ->
5010   //      (and/or/xor (zextload x), (zext cst))
5011   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5012        N0.getOpcode() == ISD::XOR) &&
5013       isa<LoadSDNode>(N0.getOperand(0)) &&
5014       N0.getOperand(1).getOpcode() == ISD::Constant &&
5015       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5016       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5017     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5018     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5019       bool DoXform = true;
5020       SmallVector<SDNode*, 4> SetCCs;
5021       if (!N0.hasOneUse())
5022         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5023                                           SetCCs, TLI);
5024       if (DoXform) {
5025         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5026                                          LN0->getChain(), LN0->getBasePtr(),
5027                                          LN0->getMemoryVT(),
5028                                          LN0->getMemOperand());
5029         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5030         Mask = Mask.zext(VT.getSizeInBits());
5031         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5032                                   ExtLoad, DAG.getConstant(Mask, VT));
5033         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5034                                     SDLoc(N0.getOperand(0)),
5035                                     N0.getOperand(0).getValueType(), ExtLoad);
5036         CombineTo(N, And);
5037         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5038         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5039                         ISD::ZERO_EXTEND);
5040         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5041       }
5042     }
5043   }
5044
5045   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5046   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5047   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5048       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5049     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5050     EVT MemVT = LN0->getMemoryVT();
5051     if ((!LegalOperations && !LN0->isVolatile()) ||
5052         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5053       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5054                                        LN0->getChain(),
5055                                        LN0->getBasePtr(), MemVT,
5056                                        LN0->getMemOperand());
5057       CombineTo(N, ExtLoad);
5058       CombineTo(N0.getNode(),
5059                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5060                             ExtLoad),
5061                 ExtLoad.getValue(1));
5062       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5063     }
5064   }
5065
5066   if (N0.getOpcode() == ISD::SETCC) {
5067     if (!LegalOperations && VT.isVector() &&
5068         N0.getValueType().getVectorElementType() == MVT::i1) {
5069       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5070       // Only do this before legalize for now.
5071       EVT N0VT = N0.getOperand(0).getValueType();
5072       EVT EltVT = VT.getVectorElementType();
5073       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5074                                     DAG.getConstant(1, EltVT));
5075       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5076         // We know that the # elements of the results is the same as the
5077         // # elements of the compare (and the # elements of the compare result
5078         // for that matter).  Check to see that they are the same size.  If so,
5079         // we know that the element size of the sext'd result matches the
5080         // element size of the compare operands.
5081         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5082                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5083                                          N0.getOperand(1),
5084                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5085                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5086                                        &OneOps[0], OneOps.size()));
5087
5088       // If the desired elements are smaller or larger than the source
5089       // elements we can use a matching integer vector type and then
5090       // truncate/sign extend
5091       EVT MatchingElementType =
5092         EVT::getIntegerVT(*DAG.getContext(),
5093                           N0VT.getScalarType().getSizeInBits());
5094       EVT MatchingVectorType =
5095         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5096                          N0VT.getVectorNumElements());
5097       SDValue VsetCC =
5098         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5099                       N0.getOperand(1),
5100                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5101       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5102                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5103                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5104                                      &OneOps[0], OneOps.size()));
5105     }
5106
5107     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5108     SDValue SCC =
5109       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5110                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5111                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5112     if (SCC.getNode()) return SCC;
5113   }
5114
5115   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5116   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5117       isa<ConstantSDNode>(N0.getOperand(1)) &&
5118       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5119       N0.hasOneUse()) {
5120     SDValue ShAmt = N0.getOperand(1);
5121     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5122     if (N0.getOpcode() == ISD::SHL) {
5123       SDValue InnerZExt = N0.getOperand(0);
5124       // If the original shl may be shifting out bits, do not perform this
5125       // transformation.
5126       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5127         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5128       if (ShAmtVal > KnownZeroBits)
5129         return SDValue();
5130     }
5131
5132     SDLoc DL(N);
5133
5134     // Ensure that the shift amount is wide enough for the shifted value.
5135     if (VT.getSizeInBits() >= 256)
5136       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5137
5138     return DAG.getNode(N0.getOpcode(), DL, VT,
5139                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5140                        ShAmt);
5141   }
5142
5143   return SDValue();
5144 }
5145
5146 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5147   SDValue N0 = N->getOperand(0);
5148   EVT VT = N->getValueType(0);
5149
5150   // fold (aext c1) -> c1
5151   if (isa<ConstantSDNode>(N0))
5152     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5153   // fold (aext (aext x)) -> (aext x)
5154   // fold (aext (zext x)) -> (zext x)
5155   // fold (aext (sext x)) -> (sext x)
5156   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5157       N0.getOpcode() == ISD::ZERO_EXTEND ||
5158       N0.getOpcode() == ISD::SIGN_EXTEND)
5159     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5160
5161   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5162   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5163   if (N0.getOpcode() == ISD::TRUNCATE) {
5164     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5165     if (NarrowLoad.getNode()) {
5166       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5167       if (NarrowLoad.getNode() != N0.getNode()) {
5168         CombineTo(N0.getNode(), NarrowLoad);
5169         // CombineTo deleted the truncate, if needed, but not what's under it.
5170         AddToWorkList(oye);
5171       }
5172       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5173     }
5174   }
5175
5176   // fold (aext (truncate x))
5177   if (N0.getOpcode() == ISD::TRUNCATE) {
5178     SDValue TruncOp = N0.getOperand(0);
5179     if (TruncOp.getValueType() == VT)
5180       return TruncOp; // x iff x size == zext size.
5181     if (TruncOp.getValueType().bitsGT(VT))
5182       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5183     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5184   }
5185
5186   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5187   // if the trunc is not free.
5188   if (N0.getOpcode() == ISD::AND &&
5189       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5190       N0.getOperand(1).getOpcode() == ISD::Constant &&
5191       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5192                           N0.getValueType())) {
5193     SDValue X = N0.getOperand(0).getOperand(0);
5194     if (X.getValueType().bitsLT(VT)) {
5195       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5196     } else if (X.getValueType().bitsGT(VT)) {
5197       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5198     }
5199     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5200     Mask = Mask.zext(VT.getSizeInBits());
5201     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5202                        X, DAG.getConstant(Mask, VT));
5203   }
5204
5205   // fold (aext (load x)) -> (aext (truncate (extload x)))
5206   // None of the supported targets knows how to perform load and any_ext
5207   // on vectors in one instruction.  We only perform this transformation on
5208   // scalars.
5209   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5210       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5211        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5212     bool DoXform = true;
5213     SmallVector<SDNode*, 4> SetCCs;
5214     if (!N0.hasOneUse())
5215       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5216     if (DoXform) {
5217       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5218       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5219                                        LN0->getChain(),
5220                                        LN0->getBasePtr(), N0.getValueType(),
5221                                        LN0->getMemOperand());
5222       CombineTo(N, ExtLoad);
5223       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5224                                   N0.getValueType(), ExtLoad);
5225       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5226       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5227                       ISD::ANY_EXTEND);
5228       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5229     }
5230   }
5231
5232   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5233   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5234   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5235   if (N0.getOpcode() == ISD::LOAD &&
5236       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5237       N0.hasOneUse()) {
5238     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5239     EVT MemVT = LN0->getMemoryVT();
5240     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5241                                      VT, LN0->getChain(), LN0->getBasePtr(),
5242                                      MemVT, LN0->getMemOperand());
5243     CombineTo(N, ExtLoad);
5244     CombineTo(N0.getNode(),
5245               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5246                           N0.getValueType(), ExtLoad),
5247               ExtLoad.getValue(1));
5248     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5249   }
5250
5251   if (N0.getOpcode() == ISD::SETCC) {
5252     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5253     // Only do this before legalize for now.
5254     if (VT.isVector() && !LegalOperations) {
5255       EVT N0VT = N0.getOperand(0).getValueType();
5256         // We know that the # elements of the results is the same as the
5257         // # elements of the compare (and the # elements of the compare result
5258         // for that matter).  Check to see that they are the same size.  If so,
5259         // we know that the element size of the sext'd result matches the
5260         // element size of the compare operands.
5261       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5262         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5263                              N0.getOperand(1),
5264                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5265       // If the desired elements are smaller or larger than the source
5266       // elements we can use a matching integer vector type and then
5267       // truncate/sign extend
5268       else {
5269         EVT MatchingElementType =
5270           EVT::getIntegerVT(*DAG.getContext(),
5271                             N0VT.getScalarType().getSizeInBits());
5272         EVT MatchingVectorType =
5273           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5274                            N0VT.getVectorNumElements());
5275         SDValue VsetCC =
5276           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5277                         N0.getOperand(1),
5278                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5279         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5280       }
5281     }
5282
5283     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5284     SDValue SCC =
5285       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5286                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5287                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5288     if (SCC.getNode())
5289       return SCC;
5290   }
5291
5292   return SDValue();
5293 }
5294
5295 /// GetDemandedBits - See if the specified operand can be simplified with the
5296 /// knowledge that only the bits specified by Mask are used.  If so, return the
5297 /// simpler operand, otherwise return a null SDValue.
5298 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5299   switch (V.getOpcode()) {
5300   default: break;
5301   case ISD::Constant: {
5302     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5303     assert(CV != 0 && "Const value should be ConstSDNode.");
5304     const APInt &CVal = CV->getAPIntValue();
5305     APInt NewVal = CVal & Mask;
5306     if (NewVal != CVal)
5307       return DAG.getConstant(NewVal, V.getValueType());
5308     break;
5309   }
5310   case ISD::OR:
5311   case ISD::XOR:
5312     // If the LHS or RHS don't contribute bits to the or, drop them.
5313     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5314       return V.getOperand(1);
5315     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5316       return V.getOperand(0);
5317     break;
5318   case ISD::SRL:
5319     // Only look at single-use SRLs.
5320     if (!V.getNode()->hasOneUse())
5321       break;
5322     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5323       // See if we can recursively simplify the LHS.
5324       unsigned Amt = RHSC->getZExtValue();
5325
5326       // Watch out for shift count overflow though.
5327       if (Amt >= Mask.getBitWidth()) break;
5328       APInt NewMask = Mask << Amt;
5329       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5330       if (SimplifyLHS.getNode())
5331         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5332                            SimplifyLHS, V.getOperand(1));
5333     }
5334   }
5335   return SDValue();
5336 }
5337
5338 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5339 /// bits and then truncated to a narrower type and where N is a multiple
5340 /// of number of bits of the narrower type, transform it to a narrower load
5341 /// from address + N / num of bits of new type. If the result is to be
5342 /// extended, also fold the extension to form a extending load.
5343 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5344   unsigned Opc = N->getOpcode();
5345
5346   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5347   SDValue N0 = N->getOperand(0);
5348   EVT VT = N->getValueType(0);
5349   EVT ExtVT = VT;
5350
5351   // This transformation isn't valid for vector loads.
5352   if (VT.isVector())
5353     return SDValue();
5354
5355   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5356   // extended to VT.
5357   if (Opc == ISD::SIGN_EXTEND_INREG) {
5358     ExtType = ISD::SEXTLOAD;
5359     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5360   } else if (Opc == ISD::SRL) {
5361     // Another special-case: SRL is basically zero-extending a narrower value.
5362     ExtType = ISD::ZEXTLOAD;
5363     N0 = SDValue(N, 0);
5364     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5365     if (!N01) return SDValue();
5366     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5367                               VT.getSizeInBits() - N01->getZExtValue());
5368   }
5369   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5370     return SDValue();
5371
5372   unsigned EVTBits = ExtVT.getSizeInBits();
5373
5374   // Do not generate loads of non-round integer types since these can
5375   // be expensive (and would be wrong if the type is not byte sized).
5376   if (!ExtVT.isRound())
5377     return SDValue();
5378
5379   unsigned ShAmt = 0;
5380   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5381     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5382       ShAmt = N01->getZExtValue();
5383       // Is the shift amount a multiple of size of VT?
5384       if ((ShAmt & (EVTBits-1)) == 0) {
5385         N0 = N0.getOperand(0);
5386         // Is the load width a multiple of size of VT?
5387         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5388           return SDValue();
5389       }
5390
5391       // At this point, we must have a load or else we can't do the transform.
5392       if (!isa<LoadSDNode>(N0)) return SDValue();
5393
5394       // Because a SRL must be assumed to *need* to zero-extend the high bits
5395       // (as opposed to anyext the high bits), we can't combine the zextload
5396       // lowering of SRL and an sextload.
5397       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5398         return SDValue();
5399
5400       // If the shift amount is larger than the input type then we're not
5401       // accessing any of the loaded bytes.  If the load was a zextload/extload
5402       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5403       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5404         return SDValue();
5405     }
5406   }
5407
5408   // If the load is shifted left (and the result isn't shifted back right),
5409   // we can fold the truncate through the shift.
5410   unsigned ShLeftAmt = 0;
5411   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5412       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5413     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5414       ShLeftAmt = N01->getZExtValue();
5415       N0 = N0.getOperand(0);
5416     }
5417   }
5418
5419   // If we haven't found a load, we can't narrow it.  Don't transform one with
5420   // multiple uses, this would require adding a new load.
5421   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5422     return SDValue();
5423
5424   // Don't change the width of a volatile load.
5425   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5426   if (LN0->isVolatile())
5427     return SDValue();
5428
5429   // Verify that we are actually reducing a load width here.
5430   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5431     return SDValue();
5432
5433   // For the transform to be legal, the load must produce only two values
5434   // (the value loaded and the chain).  Don't transform a pre-increment
5435   // load, for example, which produces an extra value.  Otherwise the
5436   // transformation is not equivalent, and the downstream logic to replace
5437   // uses gets things wrong.
5438   if (LN0->getNumValues() > 2)
5439     return SDValue();
5440
5441   // If the load that we're shrinking is an extload and we're not just
5442   // discarding the extension we can't simply shrink the load. Bail.
5443   // TODO: It would be possible to merge the extensions in some cases.
5444   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5445       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5446     return SDValue();
5447
5448   EVT PtrType = N0.getOperand(1).getValueType();
5449
5450   if (PtrType == MVT::Untyped || PtrType.isExtended())
5451     // It's not possible to generate a constant of extended or untyped type.
5452     return SDValue();
5453
5454   // For big endian targets, we need to adjust the offset to the pointer to
5455   // load the correct bytes.
5456   if (TLI.isBigEndian()) {
5457     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5458     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5459     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5460   }
5461
5462   uint64_t PtrOff = ShAmt / 8;
5463   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5464   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5465                                PtrType, LN0->getBasePtr(),
5466                                DAG.getConstant(PtrOff, PtrType));
5467   AddToWorkList(NewPtr.getNode());
5468
5469   SDValue Load;
5470   if (ExtType == ISD::NON_EXTLOAD)
5471     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5472                         LN0->getPointerInfo().getWithOffset(PtrOff),
5473                         LN0->isVolatile(), LN0->isNonTemporal(),
5474                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5475   else
5476     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5477                           LN0->getPointerInfo().getWithOffset(PtrOff),
5478                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5479                           NewAlign, LN0->getTBAAInfo());
5480
5481   // Replace the old load's chain with the new load's chain.
5482   WorkListRemover DeadNodes(*this);
5483   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5484
5485   // Shift the result left, if we've swallowed a left shift.
5486   SDValue Result = Load;
5487   if (ShLeftAmt != 0) {
5488     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5489     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5490       ShImmTy = VT;
5491     // If the shift amount is as large as the result size (but, presumably,
5492     // no larger than the source) then the useful bits of the result are
5493     // zero; we can't simply return the shortened shift, because the result
5494     // of that operation is undefined.
5495     if (ShLeftAmt >= VT.getSizeInBits())
5496       Result = DAG.getConstant(0, VT);
5497     else
5498       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5499                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5500   }
5501
5502   // Return the new loaded value.
5503   return Result;
5504 }
5505
5506 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5507   SDValue N0 = N->getOperand(0);
5508   SDValue N1 = N->getOperand(1);
5509   EVT VT = N->getValueType(0);
5510   EVT EVT = cast<VTSDNode>(N1)->getVT();
5511   unsigned VTBits = VT.getScalarType().getSizeInBits();
5512   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5513
5514   // fold (sext_in_reg c1) -> c1
5515   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5516     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5517
5518   // If the input is already sign extended, just drop the extension.
5519   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5520     return N0;
5521
5522   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5523   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5524       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5525     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5526                        N0.getOperand(0), N1);
5527
5528   // fold (sext_in_reg (sext x)) -> (sext x)
5529   // fold (sext_in_reg (aext x)) -> (sext x)
5530   // if x is small enough.
5531   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5532     SDValue N00 = N0.getOperand(0);
5533     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5534         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5535       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5536   }
5537
5538   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5539   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5540     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5541
5542   // fold operands of sext_in_reg based on knowledge that the top bits are not
5543   // demanded.
5544   if (SimplifyDemandedBits(SDValue(N, 0)))
5545     return SDValue(N, 0);
5546
5547   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5548   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5549   SDValue NarrowLoad = ReduceLoadWidth(N);
5550   if (NarrowLoad.getNode())
5551     return NarrowLoad;
5552
5553   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5554   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5555   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5556   if (N0.getOpcode() == ISD::SRL) {
5557     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5558       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5559         // We can turn this into an SRA iff the input to the SRL is already sign
5560         // extended enough.
5561         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5562         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5563           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5564                              N0.getOperand(0), N0.getOperand(1));
5565       }
5566   }
5567
5568   // fold (sext_inreg (extload x)) -> (sextload x)
5569   if (ISD::isEXTLoad(N0.getNode()) &&
5570       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5571       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5572       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5573        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5574     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5575     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5576                                      LN0->getChain(),
5577                                      LN0->getBasePtr(), EVT,
5578                                      LN0->getMemOperand());
5579     CombineTo(N, ExtLoad);
5580     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5581     AddToWorkList(ExtLoad.getNode());
5582     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5583   }
5584   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5585   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5586       N0.hasOneUse() &&
5587       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5588       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5589        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5590     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5591     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5592                                      LN0->getChain(),
5593                                      LN0->getBasePtr(), EVT,
5594                                      LN0->getMemOperand());
5595     CombineTo(N, ExtLoad);
5596     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5597     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5598   }
5599
5600   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5601   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5602     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5603                                        N0.getOperand(1), false);
5604     if (BSwap.getNode() != 0)
5605       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5606                          BSwap, N1);
5607   }
5608
5609   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5610   // into a build_vector.
5611   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5612     SmallVector<SDValue, 8> Elts;
5613     unsigned NumElts = N0->getNumOperands();
5614     unsigned ShAmt = VTBits - EVTBits;
5615
5616     for (unsigned i = 0; i != NumElts; ++i) {
5617       SDValue Op = N0->getOperand(i);
5618       if (Op->getOpcode() == ISD::UNDEF) {
5619         Elts.push_back(Op);
5620         continue;
5621       }
5622
5623       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5624       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5625       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5626                                      Op.getValueType()));
5627     }
5628
5629     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5630   }
5631
5632   return SDValue();
5633 }
5634
5635 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5636   SDValue N0 = N->getOperand(0);
5637   EVT VT = N->getValueType(0);
5638   bool isLE = TLI.isLittleEndian();
5639
5640   // noop truncate
5641   if (N0.getValueType() == N->getValueType(0))
5642     return N0;
5643   // fold (truncate c1) -> c1
5644   if (isa<ConstantSDNode>(N0))
5645     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5646   // fold (truncate (truncate x)) -> (truncate x)
5647   if (N0.getOpcode() == ISD::TRUNCATE)
5648     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5649   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5650   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5651       N0.getOpcode() == ISD::SIGN_EXTEND ||
5652       N0.getOpcode() == ISD::ANY_EXTEND) {
5653     if (N0.getOperand(0).getValueType().bitsLT(VT))
5654       // if the source is smaller than the dest, we still need an extend
5655       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5656                          N0.getOperand(0));
5657     if (N0.getOperand(0).getValueType().bitsGT(VT))
5658       // if the source is larger than the dest, than we just need the truncate
5659       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5660     // if the source and dest are the same type, we can drop both the extend
5661     // and the truncate.
5662     return N0.getOperand(0);
5663   }
5664
5665   // Fold extract-and-trunc into a narrow extract. For example:
5666   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5667   //   i32 y = TRUNCATE(i64 x)
5668   //        -- becomes --
5669   //   v16i8 b = BITCAST (v2i64 val)
5670   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5671   //
5672   // Note: We only run this optimization after type legalization (which often
5673   // creates this pattern) and before operation legalization after which
5674   // we need to be more careful about the vector instructions that we generate.
5675   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5676       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5677
5678     EVT VecTy = N0.getOperand(0).getValueType();
5679     EVT ExTy = N0.getValueType();
5680     EVT TrTy = N->getValueType(0);
5681
5682     unsigned NumElem = VecTy.getVectorNumElements();
5683     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5684
5685     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5686     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5687
5688     SDValue EltNo = N0->getOperand(1);
5689     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5690       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5691       EVT IndexTy = TLI.getVectorIdxTy();
5692       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5693
5694       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5695                               NVT, N0.getOperand(0));
5696
5697       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5698                          SDLoc(N), TrTy, V,
5699                          DAG.getConstant(Index, IndexTy));
5700     }
5701   }
5702
5703   // Fold a series of buildvector, bitcast, and truncate if possible.
5704   // For example fold
5705   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5706   //   (2xi32 (buildvector x, y)).
5707   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5708       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5709       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5710       N0.getOperand(0).hasOneUse()) {
5711
5712     SDValue BuildVect = N0.getOperand(0);
5713     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5714     EVT TruncVecEltTy = VT.getVectorElementType();
5715
5716     // Check that the element types match.
5717     if (BuildVectEltTy == TruncVecEltTy) {
5718       // Now we only need to compute the offset of the truncated elements.
5719       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5720       unsigned TruncVecNumElts = VT.getVectorNumElements();
5721       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5722
5723       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5724              "Invalid number of elements");
5725
5726       SmallVector<SDValue, 8> Opnds;
5727       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5728         Opnds.push_back(BuildVect.getOperand(i));
5729
5730       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5731                          Opnds.size());
5732     }
5733   }
5734
5735   // See if we can simplify the input to this truncate through knowledge that
5736   // only the low bits are being used.
5737   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5738   // Currently we only perform this optimization on scalars because vectors
5739   // may have different active low bits.
5740   if (!VT.isVector()) {
5741     SDValue Shorter =
5742       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5743                                                VT.getSizeInBits()));
5744     if (Shorter.getNode())
5745       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5746   }
5747   // fold (truncate (load x)) -> (smaller load x)
5748   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5749   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5750     SDValue Reduced = ReduceLoadWidth(N);
5751     if (Reduced.getNode())
5752       return Reduced;
5753     // Handle the case where the load remains an extending load even
5754     // after truncation.
5755     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5756       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5757       if (!LN0->isVolatile() &&
5758           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5759         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5760                                          VT, LN0->getChain(), LN0->getBasePtr(),
5761                                          LN0->getMemoryVT(),
5762                                          LN0->getMemOperand());
5763         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5764         return NewLoad;
5765       }
5766     }
5767   }
5768   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5769   // where ... are all 'undef'.
5770   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5771     SmallVector<EVT, 8> VTs;
5772     SDValue V;
5773     unsigned Idx = 0;
5774     unsigned NumDefs = 0;
5775
5776     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5777       SDValue X = N0.getOperand(i);
5778       if (X.getOpcode() != ISD::UNDEF) {
5779         V = X;
5780         Idx = i;
5781         NumDefs++;
5782       }
5783       // Stop if more than one members are non-undef.
5784       if (NumDefs > 1)
5785         break;
5786       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5787                                      VT.getVectorElementType(),
5788                                      X.getValueType().getVectorNumElements()));
5789     }
5790
5791     if (NumDefs == 0)
5792       return DAG.getUNDEF(VT);
5793
5794     if (NumDefs == 1) {
5795       assert(V.getNode() && "The single defined operand is empty!");
5796       SmallVector<SDValue, 8> Opnds;
5797       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5798         if (i != Idx) {
5799           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5800           continue;
5801         }
5802         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5803         AddToWorkList(NV.getNode());
5804         Opnds.push_back(NV);
5805       }
5806       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5807                          &Opnds[0], Opnds.size());
5808     }
5809   }
5810
5811   // Simplify the operands using demanded-bits information.
5812   if (!VT.isVector() &&
5813       SimplifyDemandedBits(SDValue(N, 0)))
5814     return SDValue(N, 0);
5815
5816   return SDValue();
5817 }
5818
5819 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5820   SDValue Elt = N->getOperand(i);
5821   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5822     return Elt.getNode();
5823   return Elt.getOperand(Elt.getResNo()).getNode();
5824 }
5825
5826 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5827 /// if load locations are consecutive.
5828 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5829   assert(N->getOpcode() == ISD::BUILD_PAIR);
5830
5831   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5832   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5833   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5834       LD1->getPointerInfo().getAddrSpace() !=
5835          LD2->getPointerInfo().getAddrSpace())
5836     return SDValue();
5837   EVT LD1VT = LD1->getValueType(0);
5838
5839   if (ISD::isNON_EXTLoad(LD2) &&
5840       LD2->hasOneUse() &&
5841       // If both are volatile this would reduce the number of volatile loads.
5842       // If one is volatile it might be ok, but play conservative and bail out.
5843       !LD1->isVolatile() &&
5844       !LD2->isVolatile() &&
5845       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5846     unsigned Align = LD1->getAlignment();
5847     unsigned NewAlign = TLI.getDataLayout()->
5848       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5849
5850     if (NewAlign <= Align &&
5851         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5852       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5853                          LD1->getBasePtr(), LD1->getPointerInfo(),
5854                          false, false, false, Align);
5855   }
5856
5857   return SDValue();
5858 }
5859
5860 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5861   SDValue N0 = N->getOperand(0);
5862   EVT VT = N->getValueType(0);
5863
5864   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5865   // Only do this before legalize, since afterward the target may be depending
5866   // on the bitconvert.
5867   // First check to see if this is all constant.
5868   if (!LegalTypes &&
5869       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5870       VT.isVector()) {
5871     bool isSimple = true;
5872     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5873       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5874           N0.getOperand(i).getOpcode() != ISD::Constant &&
5875           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5876         isSimple = false;
5877         break;
5878       }
5879
5880     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5881     assert(!DestEltVT.isVector() &&
5882            "Element type of vector ValueType must not be vector!");
5883     if (isSimple)
5884       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5885   }
5886
5887   // If the input is a constant, let getNode fold it.
5888   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5889     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5890     if (Res.getNode() != N) {
5891       if (!LegalOperations ||
5892           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5893         return Res;
5894
5895       // Folding it resulted in an illegal node, and it's too late to
5896       // do that. Clean up the old node and forego the transformation.
5897       // Ideally this won't happen very often, because instcombine
5898       // and the earlier dagcombine runs (where illegal nodes are
5899       // permitted) should have folded most of them already.
5900       DAG.DeleteNode(Res.getNode());
5901     }
5902   }
5903
5904   // (conv (conv x, t1), t2) -> (conv x, t2)
5905   if (N0.getOpcode() == ISD::BITCAST)
5906     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5907                        N0.getOperand(0));
5908
5909   // fold (conv (load x)) -> (load (conv*)x)
5910   // If the resultant load doesn't need a higher alignment than the original!
5911   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5912       // Do not change the width of a volatile load.
5913       !cast<LoadSDNode>(N0)->isVolatile() &&
5914       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5915       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5916     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5917     unsigned Align = TLI.getDataLayout()->
5918       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5919     unsigned OrigAlign = LN0->getAlignment();
5920
5921     if (Align <= OrigAlign) {
5922       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5923                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5924                                  LN0->isVolatile(), LN0->isNonTemporal(),
5925                                  LN0->isInvariant(), OrigAlign,
5926                                  LN0->getTBAAInfo());
5927       AddToWorkList(N);
5928       CombineTo(N0.getNode(),
5929                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5930                             N0.getValueType(), Load),
5931                 Load.getValue(1));
5932       return Load;
5933     }
5934   }
5935
5936   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5937   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5938   // This often reduces constant pool loads.
5939   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5940        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5941       N0.getNode()->hasOneUse() && VT.isInteger() &&
5942       !VT.isVector() && !N0.getValueType().isVector()) {
5943     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5944                                   N0.getOperand(0));
5945     AddToWorkList(NewConv.getNode());
5946
5947     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5948     if (N0.getOpcode() == ISD::FNEG)
5949       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5950                          NewConv, DAG.getConstant(SignBit, VT));
5951     assert(N0.getOpcode() == ISD::FABS);
5952     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5953                        NewConv, DAG.getConstant(~SignBit, VT));
5954   }
5955
5956   // fold (bitconvert (fcopysign cst, x)) ->
5957   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5958   // Note that we don't handle (copysign x, cst) because this can always be
5959   // folded to an fneg or fabs.
5960   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5961       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5962       VT.isInteger() && !VT.isVector()) {
5963     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5964     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5965     if (isTypeLegal(IntXVT)) {
5966       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5967                               IntXVT, N0.getOperand(1));
5968       AddToWorkList(X.getNode());
5969
5970       // If X has a different width than the result/lhs, sext it or truncate it.
5971       unsigned VTWidth = VT.getSizeInBits();
5972       if (OrigXWidth < VTWidth) {
5973         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5974         AddToWorkList(X.getNode());
5975       } else if (OrigXWidth > VTWidth) {
5976         // To get the sign bit in the right place, we have to shift it right
5977         // before truncating.
5978         X = DAG.getNode(ISD::SRL, SDLoc(X),
5979                         X.getValueType(), X,
5980                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5981         AddToWorkList(X.getNode());
5982         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5983         AddToWorkList(X.getNode());
5984       }
5985
5986       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5987       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5988                       X, DAG.getConstant(SignBit, VT));
5989       AddToWorkList(X.getNode());
5990
5991       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5992                                 VT, N0.getOperand(0));
5993       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5994                         Cst, DAG.getConstant(~SignBit, VT));
5995       AddToWorkList(Cst.getNode());
5996
5997       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5998     }
5999   }
6000
6001   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6002   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6003     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6004     if (CombineLD.getNode())
6005       return CombineLD;
6006   }
6007
6008   return SDValue();
6009 }
6010
6011 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6012   EVT VT = N->getValueType(0);
6013   return CombineConsecutiveLoads(N, VT);
6014 }
6015
6016 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6017 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6018 /// destination element value type.
6019 SDValue DAGCombiner::
6020 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6021   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6022
6023   // If this is already the right type, we're done.
6024   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6025
6026   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6027   unsigned DstBitSize = DstEltVT.getSizeInBits();
6028
6029   // If this is a conversion of N elements of one type to N elements of another
6030   // type, convert each element.  This handles FP<->INT cases.
6031   if (SrcBitSize == DstBitSize) {
6032     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6033                               BV->getValueType(0).getVectorNumElements());
6034
6035     // Due to the FP element handling below calling this routine recursively,
6036     // we can end up with a scalar-to-vector node here.
6037     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6038       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6039                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6040                                      DstEltVT, BV->getOperand(0)));
6041
6042     SmallVector<SDValue, 8> Ops;
6043     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6044       SDValue Op = BV->getOperand(i);
6045       // If the vector element type is not legal, the BUILD_VECTOR operands
6046       // are promoted and implicitly truncated.  Make that explicit here.
6047       if (Op.getValueType() != SrcEltVT)
6048         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6049       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6050                                 DstEltVT, Op));
6051       AddToWorkList(Ops.back().getNode());
6052     }
6053     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6054                        &Ops[0], Ops.size());
6055   }
6056
6057   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6058   // handle annoying details of growing/shrinking FP values, we convert them to
6059   // int first.
6060   if (SrcEltVT.isFloatingPoint()) {
6061     // Convert the input float vector to a int vector where the elements are the
6062     // same sizes.
6063     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6064     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6065     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6066     SrcEltVT = IntVT;
6067   }
6068
6069   // Now we know the input is an integer vector.  If the output is a FP type,
6070   // convert to integer first, then to FP of the right size.
6071   if (DstEltVT.isFloatingPoint()) {
6072     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6073     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6074     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6075
6076     // Next, convert to FP elements of the same size.
6077     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6078   }
6079
6080   // Okay, we know the src/dst types are both integers of differing types.
6081   // Handling growing first.
6082   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6083   if (SrcBitSize < DstBitSize) {
6084     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6085
6086     SmallVector<SDValue, 8> Ops;
6087     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6088          i += NumInputsPerOutput) {
6089       bool isLE = TLI.isLittleEndian();
6090       APInt NewBits = APInt(DstBitSize, 0);
6091       bool EltIsUndef = true;
6092       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6093         // Shift the previously computed bits over.
6094         NewBits <<= SrcBitSize;
6095         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6096         if (Op.getOpcode() == ISD::UNDEF) continue;
6097         EltIsUndef = false;
6098
6099         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6100                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6101       }
6102
6103       if (EltIsUndef)
6104         Ops.push_back(DAG.getUNDEF(DstEltVT));
6105       else
6106         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6107     }
6108
6109     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6110     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6111                        &Ops[0], Ops.size());
6112   }
6113
6114   // Finally, this must be the case where we are shrinking elements: each input
6115   // turns into multiple outputs.
6116   bool isS2V = ISD::isScalarToVector(BV);
6117   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6118   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6119                             NumOutputsPerInput*BV->getNumOperands());
6120   SmallVector<SDValue, 8> Ops;
6121
6122   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6123     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6124       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6125         Ops.push_back(DAG.getUNDEF(DstEltVT));
6126       continue;
6127     }
6128
6129     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6130                   getAPIntValue().zextOrTrunc(SrcBitSize);
6131
6132     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6133       APInt ThisVal = OpVal.trunc(DstBitSize);
6134       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6135       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6136         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6137         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6138                            Ops[0]);
6139       OpVal = OpVal.lshr(DstBitSize);
6140     }
6141
6142     // For big endian targets, swap the order of the pieces of each element.
6143     if (TLI.isBigEndian())
6144       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6145   }
6146
6147   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6148                      &Ops[0], Ops.size());
6149 }
6150
6151 SDValue DAGCombiner::visitFADD(SDNode *N) {
6152   SDValue N0 = N->getOperand(0);
6153   SDValue N1 = N->getOperand(1);
6154   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6155   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6156   EVT VT = N->getValueType(0);
6157
6158   // fold vector ops
6159   if (VT.isVector()) {
6160     SDValue FoldedVOp = SimplifyVBinOp(N);
6161     if (FoldedVOp.getNode()) return FoldedVOp;
6162   }
6163
6164   // fold (fadd c1, c2) -> c1 + c2
6165   if (N0CFP && N1CFP)
6166     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6167   // canonicalize constant to RHS
6168   if (N0CFP && !N1CFP)
6169     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6170   // fold (fadd A, 0) -> A
6171   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6172       N1CFP->getValueAPF().isZero())
6173     return N0;
6174   // fold (fadd A, (fneg B)) -> (fsub A, B)
6175   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6176     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6177     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6178                        GetNegatedExpression(N1, DAG, LegalOperations));
6179   // fold (fadd (fneg A), B) -> (fsub B, A)
6180   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6181     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6182     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6183                        GetNegatedExpression(N0, DAG, LegalOperations));
6184
6185   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6186   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6187       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6188       isa<ConstantFPSDNode>(N0.getOperand(1)))
6189     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6190                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6191                                    N0.getOperand(1), N1));
6192
6193   // No FP constant should be created after legalization as Instruction
6194   // Selection pass has hard time in dealing with FP constant.
6195   //
6196   // We don't need test this condition for transformation like following, as
6197   // the DAG being transformed implies it is legal to take FP constant as
6198   // operand.
6199   //
6200   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6201   //
6202   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6203
6204   // If allow, fold (fadd (fneg x), x) -> 0.0
6205   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6206       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6207     return DAG.getConstantFP(0.0, VT);
6208
6209     // If allow, fold (fadd x, (fneg x)) -> 0.0
6210   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6211       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6212     return DAG.getConstantFP(0.0, VT);
6213
6214   // In unsafe math mode, we can fold chains of FADD's of the same value
6215   // into multiplications.  This transform is not safe in general because
6216   // we are reducing the number of rounding steps.
6217   if (DAG.getTarget().Options.UnsafeFPMath &&
6218       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6219       !N0CFP && !N1CFP) {
6220     if (N0.getOpcode() == ISD::FMUL) {
6221       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6222       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6223
6224       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6225       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6226         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6227                                      SDValue(CFP00, 0),
6228                                      DAG.getConstantFP(1.0, VT));
6229         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6230                            N1, NewCFP);
6231       }
6232
6233       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6234       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6235         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6236                                      SDValue(CFP01, 0),
6237                                      DAG.getConstantFP(1.0, VT));
6238         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6239                            N1, NewCFP);
6240       }
6241
6242       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6243       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6244           N1.getOperand(0) == N1.getOperand(1) &&
6245           N0.getOperand(1) == N1.getOperand(0)) {
6246         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6247                                      SDValue(CFP00, 0),
6248                                      DAG.getConstantFP(2.0, VT));
6249         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6250                            N0.getOperand(1), NewCFP);
6251       }
6252
6253       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6254       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6255           N1.getOperand(0) == N1.getOperand(1) &&
6256           N0.getOperand(0) == N1.getOperand(0)) {
6257         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6258                                      SDValue(CFP01, 0),
6259                                      DAG.getConstantFP(2.0, VT));
6260         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6261                            N0.getOperand(0), NewCFP);
6262       }
6263     }
6264
6265     if (N1.getOpcode() == ISD::FMUL) {
6266       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6267       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6268
6269       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6270       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6271         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6272                                      SDValue(CFP10, 0),
6273                                      DAG.getConstantFP(1.0, VT));
6274         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6275                            N0, NewCFP);
6276       }
6277
6278       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6279       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6280         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6281                                      SDValue(CFP11, 0),
6282                                      DAG.getConstantFP(1.0, VT));
6283         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6284                            N0, NewCFP);
6285       }
6286
6287
6288       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6289       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6290           N0.getOperand(0) == N0.getOperand(1) &&
6291           N1.getOperand(1) == N0.getOperand(0)) {
6292         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6293                                      SDValue(CFP10, 0),
6294                                      DAG.getConstantFP(2.0, VT));
6295         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6296                            N1.getOperand(1), NewCFP);
6297       }
6298
6299       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6300       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6301           N0.getOperand(0) == N0.getOperand(1) &&
6302           N1.getOperand(0) == N0.getOperand(0)) {
6303         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6304                                      SDValue(CFP11, 0),
6305                                      DAG.getConstantFP(2.0, VT));
6306         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6307                            N1.getOperand(0), NewCFP);
6308       }
6309     }
6310
6311     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6312       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6313       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6314       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6315           (N0.getOperand(0) == N1))
6316         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6317                            N1, DAG.getConstantFP(3.0, VT));
6318     }
6319
6320     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6321       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6322       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6323       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6324           N1.getOperand(0) == N0)
6325         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6326                            N0, DAG.getConstantFP(3.0, VT));
6327     }
6328
6329     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6330     if (AllowNewFpConst &&
6331         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6332         N0.getOperand(0) == N0.getOperand(1) &&
6333         N1.getOperand(0) == N1.getOperand(1) &&
6334         N0.getOperand(0) == N1.getOperand(0))
6335       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6336                          N0.getOperand(0),
6337                          DAG.getConstantFP(4.0, VT));
6338   }
6339
6340   // FADD -> FMA combines:
6341   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6342        DAG.getTarget().Options.UnsafeFPMath) &&
6343       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6344       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6345
6346     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6347     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6348       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6349                          N0.getOperand(0), N0.getOperand(1), N1);
6350
6351     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6352     // Note: Commutes FADD operands.
6353     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6354       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6355                          N1.getOperand(0), N1.getOperand(1), N0);
6356   }
6357
6358   return SDValue();
6359 }
6360
6361 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6362   SDValue N0 = N->getOperand(0);
6363   SDValue N1 = N->getOperand(1);
6364   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6365   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6366   EVT VT = N->getValueType(0);
6367   SDLoc dl(N);
6368
6369   // fold vector ops
6370   if (VT.isVector()) {
6371     SDValue FoldedVOp = SimplifyVBinOp(N);
6372     if (FoldedVOp.getNode()) return FoldedVOp;
6373   }
6374
6375   // fold (fsub c1, c2) -> c1-c2
6376   if (N0CFP && N1CFP)
6377     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6378   // fold (fsub A, 0) -> A
6379   if (DAG.getTarget().Options.UnsafeFPMath &&
6380       N1CFP && N1CFP->getValueAPF().isZero())
6381     return N0;
6382   // fold (fsub 0, B) -> -B
6383   if (DAG.getTarget().Options.UnsafeFPMath &&
6384       N0CFP && N0CFP->getValueAPF().isZero()) {
6385     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6386       return GetNegatedExpression(N1, DAG, LegalOperations);
6387     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6388       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6389   }
6390   // fold (fsub A, (fneg B)) -> (fadd A, B)
6391   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6392     return DAG.getNode(ISD::FADD, dl, VT, N0,
6393                        GetNegatedExpression(N1, DAG, LegalOperations));
6394
6395   // If 'unsafe math' is enabled, fold
6396   //    (fsub x, x) -> 0.0 &
6397   //    (fsub x, (fadd x, y)) -> (fneg y) &
6398   //    (fsub x, (fadd y, x)) -> (fneg y)
6399   if (DAG.getTarget().Options.UnsafeFPMath) {
6400     if (N0 == N1)
6401       return DAG.getConstantFP(0.0f, VT);
6402
6403     if (N1.getOpcode() == ISD::FADD) {
6404       SDValue N10 = N1->getOperand(0);
6405       SDValue N11 = N1->getOperand(1);
6406
6407       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6408                                           &DAG.getTarget().Options))
6409         return GetNegatedExpression(N11, DAG, LegalOperations);
6410
6411       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6412                                           &DAG.getTarget().Options))
6413         return GetNegatedExpression(N10, DAG, LegalOperations);
6414     }
6415   }
6416
6417   // FSUB -> FMA combines:
6418   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6419        DAG.getTarget().Options.UnsafeFPMath) &&
6420       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6421       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6422
6423     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6424     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6425       return DAG.getNode(ISD::FMA, dl, VT,
6426                          N0.getOperand(0), N0.getOperand(1),
6427                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6428
6429     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6430     // Note: Commutes FSUB operands.
6431     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6432       return DAG.getNode(ISD::FMA, dl, VT,
6433                          DAG.getNode(ISD::FNEG, dl, VT,
6434                          N1.getOperand(0)),
6435                          N1.getOperand(1), N0);
6436
6437     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6438     if (N0.getOpcode() == ISD::FNEG &&
6439         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6440         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6441       SDValue N00 = N0.getOperand(0).getOperand(0);
6442       SDValue N01 = N0.getOperand(0).getOperand(1);
6443       return DAG.getNode(ISD::FMA, dl, VT,
6444                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6445                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6446     }
6447   }
6448
6449   return SDValue();
6450 }
6451
6452 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6453   SDValue N0 = N->getOperand(0);
6454   SDValue N1 = N->getOperand(1);
6455   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6456   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6457   EVT VT = N->getValueType(0);
6458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6459
6460   // fold vector ops
6461   if (VT.isVector()) {
6462     SDValue FoldedVOp = SimplifyVBinOp(N);
6463     if (FoldedVOp.getNode()) return FoldedVOp;
6464   }
6465
6466   // fold (fmul c1, c2) -> c1*c2
6467   if (N0CFP && N1CFP)
6468     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6469   // canonicalize constant to RHS
6470   if (N0CFP && !N1CFP)
6471     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6472   // fold (fmul A, 0) -> 0
6473   if (DAG.getTarget().Options.UnsafeFPMath &&
6474       N1CFP && N1CFP->getValueAPF().isZero())
6475     return N1;
6476   // fold (fmul A, 0) -> 0, vector edition.
6477   if (DAG.getTarget().Options.UnsafeFPMath &&
6478       ISD::isBuildVectorAllZeros(N1.getNode()))
6479     return N1;
6480   // fold (fmul A, 1.0) -> A
6481   if (N1CFP && N1CFP->isExactlyValue(1.0))
6482     return N0;
6483   // fold (fmul X, 2.0) -> (fadd X, X)
6484   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6485     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6486   // fold (fmul X, -1.0) -> (fneg X)
6487   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6488     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6489       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6490
6491   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6492   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6493                                        &DAG.getTarget().Options)) {
6494     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6495                                          &DAG.getTarget().Options)) {
6496       // Both can be negated for free, check to see if at least one is cheaper
6497       // negated.
6498       if (LHSNeg == 2 || RHSNeg == 2)
6499         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6500                            GetNegatedExpression(N0, DAG, LegalOperations),
6501                            GetNegatedExpression(N1, DAG, LegalOperations));
6502     }
6503   }
6504
6505   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6506   if (DAG.getTarget().Options.UnsafeFPMath &&
6507       N1CFP && N0.getOpcode() == ISD::FMUL &&
6508       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6509     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6510                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6511                                    N0.getOperand(1), N1));
6512
6513   return SDValue();
6514 }
6515
6516 SDValue DAGCombiner::visitFMA(SDNode *N) {
6517   SDValue N0 = N->getOperand(0);
6518   SDValue N1 = N->getOperand(1);
6519   SDValue N2 = N->getOperand(2);
6520   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6521   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6522   EVT VT = N->getValueType(0);
6523   SDLoc dl(N);
6524
6525   if (DAG.getTarget().Options.UnsafeFPMath) {
6526     if (N0CFP && N0CFP->isZero())
6527       return N2;
6528     if (N1CFP && N1CFP->isZero())
6529       return N2;
6530   }
6531   if (N0CFP && N0CFP->isExactlyValue(1.0))
6532     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6533   if (N1CFP && N1CFP->isExactlyValue(1.0))
6534     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6535
6536   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6537   if (N0CFP && !N1CFP)
6538     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6539
6540   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6541   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6542       N2.getOpcode() == ISD::FMUL &&
6543       N0 == N2.getOperand(0) &&
6544       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6545     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6546                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6547   }
6548
6549
6550   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6551   if (DAG.getTarget().Options.UnsafeFPMath &&
6552       N0.getOpcode() == ISD::FMUL && N1CFP &&
6553       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6554     return DAG.getNode(ISD::FMA, dl, VT,
6555                        N0.getOperand(0),
6556                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6557                        N2);
6558   }
6559
6560   // (fma x, 1, y) -> (fadd x, y)
6561   // (fma x, -1, y) -> (fadd (fneg x), y)
6562   if (N1CFP) {
6563     if (N1CFP->isExactlyValue(1.0))
6564       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6565
6566     if (N1CFP->isExactlyValue(-1.0) &&
6567         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6568       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6569       AddToWorkList(RHSNeg.getNode());
6570       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6571     }
6572   }
6573
6574   // (fma x, c, x) -> (fmul x, (c+1))
6575   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6576     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6577                        DAG.getNode(ISD::FADD, dl, VT,
6578                                    N1, DAG.getConstantFP(1.0, VT)));
6579
6580   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6581   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6582       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6583     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6584                        DAG.getNode(ISD::FADD, dl, VT,
6585                                    N1, DAG.getConstantFP(-1.0, VT)));
6586
6587
6588   return SDValue();
6589 }
6590
6591 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6592   SDValue N0 = N->getOperand(0);
6593   SDValue N1 = N->getOperand(1);
6594   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6595   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6596   EVT VT = N->getValueType(0);
6597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6598
6599   // fold vector ops
6600   if (VT.isVector()) {
6601     SDValue FoldedVOp = SimplifyVBinOp(N);
6602     if (FoldedVOp.getNode()) return FoldedVOp;
6603   }
6604
6605   // fold (fdiv c1, c2) -> c1/c2
6606   if (N0CFP && N1CFP)
6607     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6608
6609   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6610   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6611     // Compute the reciprocal 1.0 / c2.
6612     APFloat N1APF = N1CFP->getValueAPF();
6613     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6614     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6615     // Only do the transform if the reciprocal is a legal fp immediate that
6616     // isn't too nasty (eg NaN, denormal, ...).
6617     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6618         (!LegalOperations ||
6619          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6620          // backend)... we should handle this gracefully after Legalize.
6621          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6622          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6623          TLI.isFPImmLegal(Recip, VT)))
6624       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6625                          DAG.getConstantFP(Recip, VT));
6626   }
6627
6628   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6629   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6630                                        &DAG.getTarget().Options)) {
6631     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6632                                          &DAG.getTarget().Options)) {
6633       // Both can be negated for free, check to see if at least one is cheaper
6634       // negated.
6635       if (LHSNeg == 2 || RHSNeg == 2)
6636         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6637                            GetNegatedExpression(N0, DAG, LegalOperations),
6638                            GetNegatedExpression(N1, DAG, LegalOperations));
6639     }
6640   }
6641
6642   return SDValue();
6643 }
6644
6645 SDValue DAGCombiner::visitFREM(SDNode *N) {
6646   SDValue N0 = N->getOperand(0);
6647   SDValue N1 = N->getOperand(1);
6648   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6649   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6650   EVT VT = N->getValueType(0);
6651
6652   // fold (frem c1, c2) -> fmod(c1,c2)
6653   if (N0CFP && N1CFP)
6654     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6655
6656   return SDValue();
6657 }
6658
6659 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6660   SDValue N0 = N->getOperand(0);
6661   SDValue N1 = N->getOperand(1);
6662   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6663   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6664   EVT VT = N->getValueType(0);
6665
6666   if (N0CFP && N1CFP)  // Constant fold
6667     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6668
6669   if (N1CFP) {
6670     const APFloat& V = N1CFP->getValueAPF();
6671     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6672     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6673     if (!V.isNegative()) {
6674       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6675         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6676     } else {
6677       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6678         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6679                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6680     }
6681   }
6682
6683   // copysign(fabs(x), y) -> copysign(x, y)
6684   // copysign(fneg(x), y) -> copysign(x, y)
6685   // copysign(copysign(x,z), y) -> copysign(x, y)
6686   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6687       N0.getOpcode() == ISD::FCOPYSIGN)
6688     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6689                        N0.getOperand(0), N1);
6690
6691   // copysign(x, abs(y)) -> abs(x)
6692   if (N1.getOpcode() == ISD::FABS)
6693     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6694
6695   // copysign(x, copysign(y,z)) -> copysign(x, z)
6696   if (N1.getOpcode() == ISD::FCOPYSIGN)
6697     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6698                        N0, N1.getOperand(1));
6699
6700   // copysign(x, fp_extend(y)) -> copysign(x, y)
6701   // copysign(x, fp_round(y)) -> copysign(x, y)
6702   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6703     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6704                        N0, N1.getOperand(0));
6705
6706   return SDValue();
6707 }
6708
6709 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6710   SDValue N0 = N->getOperand(0);
6711   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6712   EVT VT = N->getValueType(0);
6713   EVT OpVT = N0.getValueType();
6714
6715   // fold (sint_to_fp c1) -> c1fp
6716   if (N0C &&
6717       // ...but only if the target supports immediate floating-point values
6718       (!LegalOperations ||
6719        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6720     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6721
6722   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6723   // but UINT_TO_FP is legal on this target, try to convert.
6724   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6725       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6726     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6727     if (DAG.SignBitIsZero(N0))
6728       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6729   }
6730
6731   // The next optimizations are desireable only if SELECT_CC can be lowered.
6732   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6733   // having to say they don't support SELECT_CC on every type the DAG knows
6734   // about, since there is no way to mark an opcode illegal at all value types
6735   // (See also visitSELECT)
6736   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6737     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6738     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6739         !VT.isVector() &&
6740         (!LegalOperations ||
6741          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6742       SDValue Ops[] =
6743         { N0.getOperand(0), N0.getOperand(1),
6744           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6745           N0.getOperand(2) };
6746       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6747     }
6748
6749     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6750     //      (select_cc x, y, 1.0, 0.0,, cc)
6751     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6752         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6753         (!LegalOperations ||
6754          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6755       SDValue Ops[] =
6756         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6757           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6758           N0.getOperand(0).getOperand(2) };
6759       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6760     }
6761   }
6762
6763   return SDValue();
6764 }
6765
6766 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6767   SDValue N0 = N->getOperand(0);
6768   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6769   EVT VT = N->getValueType(0);
6770   EVT OpVT = N0.getValueType();
6771
6772   // fold (uint_to_fp c1) -> c1fp
6773   if (N0C &&
6774       // ...but only if the target supports immediate floating-point values
6775       (!LegalOperations ||
6776        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6777     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6778
6779   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6780   // but SINT_TO_FP is legal on this target, try to convert.
6781   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6782       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6783     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6784     if (DAG.SignBitIsZero(N0))
6785       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6786   }
6787
6788   // The next optimizations are desireable only if SELECT_CC can be lowered.
6789   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6790   // having to say they don't support SELECT_CC on every type the DAG knows
6791   // about, since there is no way to mark an opcode illegal at all value types
6792   // (See also visitSELECT)
6793   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6794     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6795
6796     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6797         (!LegalOperations ||
6798          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6799       SDValue Ops[] =
6800         { N0.getOperand(0), N0.getOperand(1),
6801           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6802           N0.getOperand(2) };
6803       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6804     }
6805   }
6806
6807   return SDValue();
6808 }
6809
6810 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6811   SDValue N0 = N->getOperand(0);
6812   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6813   EVT VT = N->getValueType(0);
6814
6815   // fold (fp_to_sint c1fp) -> c1
6816   if (N0CFP)
6817     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6818
6819   return SDValue();
6820 }
6821
6822 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6823   SDValue N0 = N->getOperand(0);
6824   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6825   EVT VT = N->getValueType(0);
6826
6827   // fold (fp_to_uint c1fp) -> c1
6828   if (N0CFP)
6829     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6830
6831   return SDValue();
6832 }
6833
6834 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6835   SDValue N0 = N->getOperand(0);
6836   SDValue N1 = N->getOperand(1);
6837   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6838   EVT VT = N->getValueType(0);
6839
6840   // fold (fp_round c1fp) -> c1fp
6841   if (N0CFP)
6842     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6843
6844   // fold (fp_round (fp_extend x)) -> x
6845   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6846     return N0.getOperand(0);
6847
6848   // fold (fp_round (fp_round x)) -> (fp_round x)
6849   if (N0.getOpcode() == ISD::FP_ROUND) {
6850     // This is a value preserving truncation if both round's are.
6851     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6852                    N0.getNode()->getConstantOperandVal(1) == 1;
6853     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6854                        DAG.getIntPtrConstant(IsTrunc));
6855   }
6856
6857   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6858   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6859     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6860                               N0.getOperand(0), N1);
6861     AddToWorkList(Tmp.getNode());
6862     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6863                        Tmp, N0.getOperand(1));
6864   }
6865
6866   return SDValue();
6867 }
6868
6869 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6870   SDValue N0 = N->getOperand(0);
6871   EVT VT = N->getValueType(0);
6872   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6873   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6874
6875   // fold (fp_round_inreg c1fp) -> c1fp
6876   if (N0CFP && isTypeLegal(EVT)) {
6877     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6878     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6879   }
6880
6881   return SDValue();
6882 }
6883
6884 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6885   SDValue N0 = N->getOperand(0);
6886   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6887   EVT VT = N->getValueType(0);
6888
6889   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6890   if (N->hasOneUse() &&
6891       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6892     return SDValue();
6893
6894   // fold (fp_extend c1fp) -> c1fp
6895   if (N0CFP)
6896     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6897
6898   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6899   // value of X.
6900   if (N0.getOpcode() == ISD::FP_ROUND
6901       && N0.getNode()->getConstantOperandVal(1) == 1) {
6902     SDValue In = N0.getOperand(0);
6903     if (In.getValueType() == VT) return In;
6904     if (VT.bitsLT(In.getValueType()))
6905       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6906                          In, N0.getOperand(1));
6907     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6908   }
6909
6910   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6911   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6912       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6913        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6914     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6915     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6916                                      LN0->getChain(),
6917                                      LN0->getBasePtr(), N0.getValueType(),
6918                                      LN0->getMemOperand());
6919     CombineTo(N, ExtLoad);
6920     CombineTo(N0.getNode(),
6921               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6922                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6923               ExtLoad.getValue(1));
6924     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6925   }
6926
6927   return SDValue();
6928 }
6929
6930 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6931   SDValue N0 = N->getOperand(0);
6932   EVT VT = N->getValueType(0);
6933
6934   if (VT.isVector()) {
6935     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6936     if (FoldedVOp.getNode()) return FoldedVOp;
6937   }
6938
6939   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6940                          &DAG.getTarget().Options))
6941     return GetNegatedExpression(N0, DAG, LegalOperations);
6942
6943   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6944   // constant pool values.
6945   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6946       !VT.isVector() &&
6947       N0.getNode()->hasOneUse() &&
6948       N0.getOperand(0).getValueType().isInteger()) {
6949     SDValue Int = N0.getOperand(0);
6950     EVT IntVT = Int.getValueType();
6951     if (IntVT.isInteger() && !IntVT.isVector()) {
6952       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6953               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6954       AddToWorkList(Int.getNode());
6955       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6956                          VT, Int);
6957     }
6958   }
6959
6960   // (fneg (fmul c, x)) -> (fmul -c, x)
6961   if (N0.getOpcode() == ISD::FMUL) {
6962     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6963     if (CFP1)
6964       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6965                          N0.getOperand(0),
6966                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6967                                      N0.getOperand(1)));
6968   }
6969
6970   return SDValue();
6971 }
6972
6973 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6974   SDValue N0 = N->getOperand(0);
6975   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6976   EVT VT = N->getValueType(0);
6977
6978   // fold (fceil c1) -> fceil(c1)
6979   if (N0CFP)
6980     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6981
6982   return SDValue();
6983 }
6984
6985 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6986   SDValue N0 = N->getOperand(0);
6987   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6988   EVT VT = N->getValueType(0);
6989
6990   // fold (ftrunc c1) -> ftrunc(c1)
6991   if (N0CFP)
6992     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6993
6994   return SDValue();
6995 }
6996
6997 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6998   SDValue N0 = N->getOperand(0);
6999   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7000   EVT VT = N->getValueType(0);
7001
7002   // fold (ffloor c1) -> ffloor(c1)
7003   if (N0CFP)
7004     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7005
7006   return SDValue();
7007 }
7008
7009 SDValue DAGCombiner::visitFABS(SDNode *N) {
7010   SDValue N0 = N->getOperand(0);
7011   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7012   EVT VT = N->getValueType(0);
7013
7014   if (VT.isVector()) {
7015     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7016     if (FoldedVOp.getNode()) return FoldedVOp;
7017   }
7018
7019   // fold (fabs c1) -> fabs(c1)
7020   if (N0CFP)
7021     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7022   // fold (fabs (fabs x)) -> (fabs x)
7023   if (N0.getOpcode() == ISD::FABS)
7024     return N->getOperand(0);
7025   // fold (fabs (fneg x)) -> (fabs x)
7026   // fold (fabs (fcopysign x, y)) -> (fabs x)
7027   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7028     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7029
7030   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7031   // constant pool values.
7032   if (!TLI.isFAbsFree(VT) &&
7033       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7034       N0.getOperand(0).getValueType().isInteger() &&
7035       !N0.getOperand(0).getValueType().isVector()) {
7036     SDValue Int = N0.getOperand(0);
7037     EVT IntVT = Int.getValueType();
7038     if (IntVT.isInteger() && !IntVT.isVector()) {
7039       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7040              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7041       AddToWorkList(Int.getNode());
7042       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7043                          N->getValueType(0), Int);
7044     }
7045   }
7046
7047   return SDValue();
7048 }
7049
7050 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7051   SDValue Chain = N->getOperand(0);
7052   SDValue N1 = N->getOperand(1);
7053   SDValue N2 = N->getOperand(2);
7054
7055   // If N is a constant we could fold this into a fallthrough or unconditional
7056   // branch. However that doesn't happen very often in normal code, because
7057   // Instcombine/SimplifyCFG should have handled the available opportunities.
7058   // If we did this folding here, it would be necessary to update the
7059   // MachineBasicBlock CFG, which is awkward.
7060
7061   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7062   // on the target.
7063   if (N1.getOpcode() == ISD::SETCC &&
7064       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7065                                    N1.getOperand(0).getValueType())) {
7066     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7067                        Chain, N1.getOperand(2),
7068                        N1.getOperand(0), N1.getOperand(1), N2);
7069   }
7070
7071   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7072       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7073        (N1.getOperand(0).hasOneUse() &&
7074         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7075     SDNode *Trunc = 0;
7076     if (N1.getOpcode() == ISD::TRUNCATE) {
7077       // Look pass the truncate.
7078       Trunc = N1.getNode();
7079       N1 = N1.getOperand(0);
7080     }
7081
7082     // Match this pattern so that we can generate simpler code:
7083     //
7084     //   %a = ...
7085     //   %b = and i32 %a, 2
7086     //   %c = srl i32 %b, 1
7087     //   brcond i32 %c ...
7088     //
7089     // into
7090     //
7091     //   %a = ...
7092     //   %b = and i32 %a, 2
7093     //   %c = setcc eq %b, 0
7094     //   brcond %c ...
7095     //
7096     // This applies only when the AND constant value has one bit set and the
7097     // SRL constant is equal to the log2 of the AND constant. The back-end is
7098     // smart enough to convert the result into a TEST/JMP sequence.
7099     SDValue Op0 = N1.getOperand(0);
7100     SDValue Op1 = N1.getOperand(1);
7101
7102     if (Op0.getOpcode() == ISD::AND &&
7103         Op1.getOpcode() == ISD::Constant) {
7104       SDValue AndOp1 = Op0.getOperand(1);
7105
7106       if (AndOp1.getOpcode() == ISD::Constant) {
7107         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7108
7109         if (AndConst.isPowerOf2() &&
7110             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7111           SDValue SetCC =
7112             DAG.getSetCC(SDLoc(N),
7113                          getSetCCResultType(Op0.getValueType()),
7114                          Op0, DAG.getConstant(0, Op0.getValueType()),
7115                          ISD::SETNE);
7116
7117           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7118                                           MVT::Other, Chain, SetCC, N2);
7119           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7120           // will convert it back to (X & C1) >> C2.
7121           CombineTo(N, NewBRCond, false);
7122           // Truncate is dead.
7123           if (Trunc) {
7124             removeFromWorkList(Trunc);
7125             DAG.DeleteNode(Trunc);
7126           }
7127           // Replace the uses of SRL with SETCC
7128           WorkListRemover DeadNodes(*this);
7129           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7130           removeFromWorkList(N1.getNode());
7131           DAG.DeleteNode(N1.getNode());
7132           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7133         }
7134       }
7135     }
7136
7137     if (Trunc)
7138       // Restore N1 if the above transformation doesn't match.
7139       N1 = N->getOperand(1);
7140   }
7141
7142   // Transform br(xor(x, y)) -> br(x != y)
7143   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7144   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7145     SDNode *TheXor = N1.getNode();
7146     SDValue Op0 = TheXor->getOperand(0);
7147     SDValue Op1 = TheXor->getOperand(1);
7148     if (Op0.getOpcode() == Op1.getOpcode()) {
7149       // Avoid missing important xor optimizations.
7150       SDValue Tmp = visitXOR(TheXor);
7151       if (Tmp.getNode()) {
7152         if (Tmp.getNode() != TheXor) {
7153           DEBUG(dbgs() << "\nReplacing.8 ";
7154                 TheXor->dump(&DAG);
7155                 dbgs() << "\nWith: ";
7156                 Tmp.getNode()->dump(&DAG);
7157                 dbgs() << '\n');
7158           WorkListRemover DeadNodes(*this);
7159           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7160           removeFromWorkList(TheXor);
7161           DAG.DeleteNode(TheXor);
7162           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7163                              MVT::Other, Chain, Tmp, N2);
7164         }
7165
7166         // visitXOR has changed XOR's operands or replaced the XOR completely,
7167         // bail out.
7168         return SDValue(N, 0);
7169       }
7170     }
7171
7172     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7173       bool Equal = false;
7174       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7175         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7176             Op0.getOpcode() == ISD::XOR) {
7177           TheXor = Op0.getNode();
7178           Equal = true;
7179         }
7180
7181       EVT SetCCVT = N1.getValueType();
7182       if (LegalTypes)
7183         SetCCVT = getSetCCResultType(SetCCVT);
7184       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7185                                    SetCCVT,
7186                                    Op0, Op1,
7187                                    Equal ? ISD::SETEQ : ISD::SETNE);
7188       // Replace the uses of XOR with SETCC
7189       WorkListRemover DeadNodes(*this);
7190       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7191       removeFromWorkList(N1.getNode());
7192       DAG.DeleteNode(N1.getNode());
7193       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7194                          MVT::Other, Chain, SetCC, N2);
7195     }
7196   }
7197
7198   return SDValue();
7199 }
7200
7201 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7202 //
7203 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7204   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7205   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7206
7207   // If N is a constant we could fold this into a fallthrough or unconditional
7208   // branch. However that doesn't happen very often in normal code, because
7209   // Instcombine/SimplifyCFG should have handled the available opportunities.
7210   // If we did this folding here, it would be necessary to update the
7211   // MachineBasicBlock CFG, which is awkward.
7212
7213   // Use SimplifySetCC to simplify SETCC's.
7214   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7215                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7216                                false);
7217   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7218
7219   // fold to a simpler setcc
7220   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7221     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7222                        N->getOperand(0), Simp.getOperand(2),
7223                        Simp.getOperand(0), Simp.getOperand(1),
7224                        N->getOperand(4));
7225
7226   return SDValue();
7227 }
7228
7229 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7230 /// uses N as its base pointer and that N may be folded in the load / store
7231 /// addressing mode.
7232 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7233                                     SelectionDAG &DAG,
7234                                     const TargetLowering &TLI) {
7235   EVT VT;
7236   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7237     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7238       return false;
7239     VT = Use->getValueType(0);
7240   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7241     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7242       return false;
7243     VT = ST->getValue().getValueType();
7244   } else
7245     return false;
7246
7247   TargetLowering::AddrMode AM;
7248   if (N->getOpcode() == ISD::ADD) {
7249     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7250     if (Offset)
7251       // [reg +/- imm]
7252       AM.BaseOffs = Offset->getSExtValue();
7253     else
7254       // [reg +/- reg]
7255       AM.Scale = 1;
7256   } else if (N->getOpcode() == ISD::SUB) {
7257     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7258     if (Offset)
7259       // [reg +/- imm]
7260       AM.BaseOffs = -Offset->getSExtValue();
7261     else
7262       // [reg +/- reg]
7263       AM.Scale = 1;
7264   } else
7265     return false;
7266
7267   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7268 }
7269
7270 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7271 /// pre-indexed load / store when the base pointer is an add or subtract
7272 /// and it has other uses besides the load / store. After the
7273 /// transformation, the new indexed load / store has effectively folded
7274 /// the add / subtract in and all of its other uses are redirected to the
7275 /// new load / store.
7276 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7277   if (Level < AfterLegalizeDAG)
7278     return false;
7279
7280   bool isLoad = true;
7281   SDValue Ptr;
7282   EVT VT;
7283   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7284     if (LD->isIndexed())
7285       return false;
7286     VT = LD->getMemoryVT();
7287     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7288         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7289       return false;
7290     Ptr = LD->getBasePtr();
7291   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7292     if (ST->isIndexed())
7293       return false;
7294     VT = ST->getMemoryVT();
7295     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7296         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7297       return false;
7298     Ptr = ST->getBasePtr();
7299     isLoad = false;
7300   } else {
7301     return false;
7302   }
7303
7304   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7305   // out.  There is no reason to make this a preinc/predec.
7306   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7307       Ptr.getNode()->hasOneUse())
7308     return false;
7309
7310   // Ask the target to do addressing mode selection.
7311   SDValue BasePtr;
7312   SDValue Offset;
7313   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7314   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7315     return false;
7316
7317   // Backends without true r+i pre-indexed forms may need to pass a
7318   // constant base with a variable offset so that constant coercion
7319   // will work with the patterns in canonical form.
7320   bool Swapped = false;
7321   if (isa<ConstantSDNode>(BasePtr)) {
7322     std::swap(BasePtr, Offset);
7323     Swapped = true;
7324   }
7325
7326   // Don't create a indexed load / store with zero offset.
7327   if (isa<ConstantSDNode>(Offset) &&
7328       cast<ConstantSDNode>(Offset)->isNullValue())
7329     return false;
7330
7331   // Try turning it into a pre-indexed load / store except when:
7332   // 1) The new base ptr is a frame index.
7333   // 2) If N is a store and the new base ptr is either the same as or is a
7334   //    predecessor of the value being stored.
7335   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7336   //    that would create a cycle.
7337   // 4) All uses are load / store ops that use it as old base ptr.
7338
7339   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7340   // (plus the implicit offset) to a register to preinc anyway.
7341   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7342     return false;
7343
7344   // Check #2.
7345   if (!isLoad) {
7346     SDValue Val = cast<StoreSDNode>(N)->getValue();
7347     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7348       return false;
7349   }
7350
7351   // If the offset is a constant, there may be other adds of constants that
7352   // can be folded with this one. We should do this to avoid having to keep
7353   // a copy of the original base pointer.
7354   SmallVector<SDNode *, 16> OtherUses;
7355   if (isa<ConstantSDNode>(Offset))
7356     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7357          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7358       SDNode *Use = *I;
7359       if (Use == Ptr.getNode())
7360         continue;
7361
7362       if (Use->isPredecessorOf(N))
7363         continue;
7364
7365       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7366         OtherUses.clear();
7367         break;
7368       }
7369
7370       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7371       if (Op1.getNode() == BasePtr.getNode())
7372         std::swap(Op0, Op1);
7373       assert(Op0.getNode() == BasePtr.getNode() &&
7374              "Use of ADD/SUB but not an operand");
7375
7376       if (!isa<ConstantSDNode>(Op1)) {
7377         OtherUses.clear();
7378         break;
7379       }
7380
7381       // FIXME: In some cases, we can be smarter about this.
7382       if (Op1.getValueType() != Offset.getValueType()) {
7383         OtherUses.clear();
7384         break;
7385       }
7386
7387       OtherUses.push_back(Use);
7388     }
7389
7390   if (Swapped)
7391     std::swap(BasePtr, Offset);
7392
7393   // Now check for #3 and #4.
7394   bool RealUse = false;
7395
7396   // Caches for hasPredecessorHelper
7397   SmallPtrSet<const SDNode *, 32> Visited;
7398   SmallVector<const SDNode *, 16> Worklist;
7399
7400   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7401          E = Ptr.getNode()->use_end(); I != E; ++I) {
7402     SDNode *Use = *I;
7403     if (Use == N)
7404       continue;
7405     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7406       return false;
7407
7408     // If Ptr may be folded in addressing mode of other use, then it's
7409     // not profitable to do this transformation.
7410     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7411       RealUse = true;
7412   }
7413
7414   if (!RealUse)
7415     return false;
7416
7417   SDValue Result;
7418   if (isLoad)
7419     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7420                                 BasePtr, Offset, AM);
7421   else
7422     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7423                                  BasePtr, Offset, AM);
7424   ++PreIndexedNodes;
7425   ++NodesCombined;
7426   DEBUG(dbgs() << "\nReplacing.4 ";
7427         N->dump(&DAG);
7428         dbgs() << "\nWith: ";
7429         Result.getNode()->dump(&DAG);
7430         dbgs() << '\n');
7431   WorkListRemover DeadNodes(*this);
7432   if (isLoad) {
7433     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7434     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7435   } else {
7436     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7437   }
7438
7439   // Finally, since the node is now dead, remove it from the graph.
7440   DAG.DeleteNode(N);
7441
7442   if (Swapped)
7443     std::swap(BasePtr, Offset);
7444
7445   // Replace other uses of BasePtr that can be updated to use Ptr
7446   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7447     unsigned OffsetIdx = 1;
7448     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7449       OffsetIdx = 0;
7450     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7451            BasePtr.getNode() && "Expected BasePtr operand");
7452
7453     // We need to replace ptr0 in the following expression:
7454     //   x0 * offset0 + y0 * ptr0 = t0
7455     // knowing that
7456     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7457     //
7458     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7459     // indexed load/store and the expresion that needs to be re-written.
7460     //
7461     // Therefore, we have:
7462     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7463
7464     ConstantSDNode *CN =
7465       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7466     int X0, X1, Y0, Y1;
7467     APInt Offset0 = CN->getAPIntValue();
7468     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7469
7470     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7471     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7472     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7473     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7474
7475     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7476
7477     APInt CNV = Offset0;
7478     if (X0 < 0) CNV = -CNV;
7479     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7480     else CNV = CNV - Offset1;
7481
7482     // We can now generate the new expression.
7483     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7484     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7485
7486     SDValue NewUse = DAG.getNode(Opcode,
7487                                  SDLoc(OtherUses[i]),
7488                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7489     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7490     removeFromWorkList(OtherUses[i]);
7491     DAG.DeleteNode(OtherUses[i]);
7492   }
7493
7494   // Replace the uses of Ptr with uses of the updated base value.
7495   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7496   removeFromWorkList(Ptr.getNode());
7497   DAG.DeleteNode(Ptr.getNode());
7498
7499   return true;
7500 }
7501
7502 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7503 /// add / sub of the base pointer node into a post-indexed load / store.
7504 /// The transformation folded the add / subtract into the new indexed
7505 /// load / store effectively and all of its uses are redirected to the
7506 /// new load / store.
7507 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7508   if (Level < AfterLegalizeDAG)
7509     return false;
7510
7511   bool isLoad = true;
7512   SDValue Ptr;
7513   EVT VT;
7514   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7515     if (LD->isIndexed())
7516       return false;
7517     VT = LD->getMemoryVT();
7518     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7519         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7520       return false;
7521     Ptr = LD->getBasePtr();
7522   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7523     if (ST->isIndexed())
7524       return false;
7525     VT = ST->getMemoryVT();
7526     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7527         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7528       return false;
7529     Ptr = ST->getBasePtr();
7530     isLoad = false;
7531   } else {
7532     return false;
7533   }
7534
7535   if (Ptr.getNode()->hasOneUse())
7536     return false;
7537
7538   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7539          E = Ptr.getNode()->use_end(); I != E; ++I) {
7540     SDNode *Op = *I;
7541     if (Op == N ||
7542         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7543       continue;
7544
7545     SDValue BasePtr;
7546     SDValue Offset;
7547     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7548     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7549       // Don't create a indexed load / store with zero offset.
7550       if (isa<ConstantSDNode>(Offset) &&
7551           cast<ConstantSDNode>(Offset)->isNullValue())
7552         continue;
7553
7554       // Try turning it into a post-indexed load / store except when
7555       // 1) All uses are load / store ops that use it as base ptr (and
7556       //    it may be folded as addressing mmode).
7557       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7558       //    nor a successor of N. Otherwise, if Op is folded that would
7559       //    create a cycle.
7560
7561       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7562         continue;
7563
7564       // Check for #1.
7565       bool TryNext = false;
7566       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7567              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7568         SDNode *Use = *II;
7569         if (Use == Ptr.getNode())
7570           continue;
7571
7572         // If all the uses are load / store addresses, then don't do the
7573         // transformation.
7574         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7575           bool RealUse = false;
7576           for (SDNode::use_iterator III = Use->use_begin(),
7577                  EEE = Use->use_end(); III != EEE; ++III) {
7578             SDNode *UseUse = *III;
7579             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7580               RealUse = true;
7581           }
7582
7583           if (!RealUse) {
7584             TryNext = true;
7585             break;
7586           }
7587         }
7588       }
7589
7590       if (TryNext)
7591         continue;
7592
7593       // Check for #2
7594       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7595         SDValue Result = isLoad
7596           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7597                                BasePtr, Offset, AM)
7598           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7599                                 BasePtr, Offset, AM);
7600         ++PostIndexedNodes;
7601         ++NodesCombined;
7602         DEBUG(dbgs() << "\nReplacing.5 ";
7603               N->dump(&DAG);
7604               dbgs() << "\nWith: ";
7605               Result.getNode()->dump(&DAG);
7606               dbgs() << '\n');
7607         WorkListRemover DeadNodes(*this);
7608         if (isLoad) {
7609           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7610           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7611         } else {
7612           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7613         }
7614
7615         // Finally, since the node is now dead, remove it from the graph.
7616         DAG.DeleteNode(N);
7617
7618         // Replace the uses of Use with uses of the updated base value.
7619         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7620                                       Result.getValue(isLoad ? 1 : 0));
7621         removeFromWorkList(Op);
7622         DAG.DeleteNode(Op);
7623         return true;
7624       }
7625     }
7626   }
7627
7628   return false;
7629 }
7630
7631 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7632   LoadSDNode *LD  = cast<LoadSDNode>(N);
7633   SDValue Chain = LD->getChain();
7634   SDValue Ptr   = LD->getBasePtr();
7635
7636   // If load is not volatile and there are no uses of the loaded value (and
7637   // the updated indexed value in case of indexed loads), change uses of the
7638   // chain value into uses of the chain input (i.e. delete the dead load).
7639   if (!LD->isVolatile()) {
7640     if (N->getValueType(1) == MVT::Other) {
7641       // Unindexed loads.
7642       if (!N->hasAnyUseOfValue(0)) {
7643         // It's not safe to use the two value CombineTo variant here. e.g.
7644         // v1, chain2 = load chain1, loc
7645         // v2, chain3 = load chain2, loc
7646         // v3         = add v2, c
7647         // Now we replace use of chain2 with chain1.  This makes the second load
7648         // isomorphic to the one we are deleting, and thus makes this load live.
7649         DEBUG(dbgs() << "\nReplacing.6 ";
7650               N->dump(&DAG);
7651               dbgs() << "\nWith chain: ";
7652               Chain.getNode()->dump(&DAG);
7653               dbgs() << "\n");
7654         WorkListRemover DeadNodes(*this);
7655         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7656
7657         if (N->use_empty()) {
7658           removeFromWorkList(N);
7659           DAG.DeleteNode(N);
7660         }
7661
7662         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7663       }
7664     } else {
7665       // Indexed loads.
7666       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7667       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7668         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7669         DEBUG(dbgs() << "\nReplacing.7 ";
7670               N->dump(&DAG);
7671               dbgs() << "\nWith: ";
7672               Undef.getNode()->dump(&DAG);
7673               dbgs() << " and 2 other values\n");
7674         WorkListRemover DeadNodes(*this);
7675         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7676         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7677                                       DAG.getUNDEF(N->getValueType(1)));
7678         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7679         removeFromWorkList(N);
7680         DAG.DeleteNode(N);
7681         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7682       }
7683     }
7684   }
7685
7686   // If this load is directly stored, replace the load value with the stored
7687   // value.
7688   // TODO: Handle store large -> read small portion.
7689   // TODO: Handle TRUNCSTORE/LOADEXT
7690   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7691     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7692       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7693       if (PrevST->getBasePtr() == Ptr &&
7694           PrevST->getValue().getValueType() == N->getValueType(0))
7695       return CombineTo(N, Chain.getOperand(1), Chain);
7696     }
7697   }
7698
7699   // Try to infer better alignment information than the load already has.
7700   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7701     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7702       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7703         SDValue NewLoad =
7704                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7705                               LD->getValueType(0),
7706                               Chain, Ptr, LD->getPointerInfo(),
7707                               LD->getMemoryVT(),
7708                               LD->isVolatile(), LD->isNonTemporal(), Align,
7709                               LD->getTBAAInfo());
7710         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7711       }
7712     }
7713   }
7714
7715   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7716     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7717   if (UseAA) {
7718     // Walk up chain skipping non-aliasing memory nodes.
7719     SDValue BetterChain = FindBetterChain(N, Chain);
7720
7721     // If there is a better chain.
7722     if (Chain != BetterChain) {
7723       SDValue ReplLoad;
7724
7725       // Replace the chain to void dependency.
7726       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7727         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7728                                BetterChain, Ptr, LD->getMemOperand());
7729       } else {
7730         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7731                                   LD->getValueType(0),
7732                                   BetterChain, Ptr, LD->getMemoryVT(),
7733                                   LD->getMemOperand());
7734       }
7735
7736       // Create token factor to keep old chain connected.
7737       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7738                                   MVT::Other, Chain, ReplLoad.getValue(1));
7739
7740       // Make sure the new and old chains are cleaned up.
7741       AddToWorkList(Token.getNode());
7742
7743       // Replace uses with load result and token factor. Don't add users
7744       // to work list.
7745       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7746     }
7747   }
7748
7749   // Try transforming N to an indexed load.
7750   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7751     return SDValue(N, 0);
7752
7753   // Try to slice up N to more direct loads if the slices are mapped to
7754   // different register banks or pairing can take place.
7755   if (SliceUpLoad(N))
7756     return SDValue(N, 0);
7757
7758   return SDValue();
7759 }
7760
7761 namespace {
7762 /// \brief Helper structure used to slice a load in smaller loads.
7763 /// Basically a slice is obtained from the following sequence:
7764 /// Origin = load Ty1, Base
7765 /// Shift = srl Ty1 Origin, CstTy Amount
7766 /// Inst = trunc Shift to Ty2
7767 ///
7768 /// Then, it will be rewriten into:
7769 /// Slice = load SliceTy, Base + SliceOffset
7770 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7771 ///
7772 /// SliceTy is deduced from the number of bits that are actually used to
7773 /// build Inst.
7774 struct LoadedSlice {
7775   /// \brief Helper structure used to compute the cost of a slice.
7776   struct Cost {
7777     /// Are we optimizing for code size.
7778     bool ForCodeSize;
7779     /// Various cost.
7780     unsigned Loads;
7781     unsigned Truncates;
7782     unsigned CrossRegisterBanksCopies;
7783     unsigned ZExts;
7784     unsigned Shift;
7785
7786     Cost(bool ForCodeSize = false)
7787         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7788           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7789
7790     /// \brief Get the cost of one isolated slice.
7791     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7792         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7793           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7794       EVT TruncType = LS.Inst->getValueType(0);
7795       EVT LoadedType = LS.getLoadedType();
7796       if (TruncType != LoadedType &&
7797           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7798         ZExts = 1;
7799     }
7800
7801     /// \brief Account for slicing gain in the current cost.
7802     /// Slicing provide a few gains like removing a shift or a
7803     /// truncate. This method allows to grow the cost of the original
7804     /// load with the gain from this slice.
7805     void addSliceGain(const LoadedSlice &LS) {
7806       // Each slice saves a truncate.
7807       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7808       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7809                               LS.Inst->getOperand(0).getValueType()))
7810         ++Truncates;
7811       // If there is a shift amount, this slice gets rid of it.
7812       if (LS.Shift)
7813         ++Shift;
7814       // If this slice can merge a cross register bank copy, account for it.
7815       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7816         ++CrossRegisterBanksCopies;
7817     }
7818
7819     Cost &operator+=(const Cost &RHS) {
7820       Loads += RHS.Loads;
7821       Truncates += RHS.Truncates;
7822       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7823       ZExts += RHS.ZExts;
7824       Shift += RHS.Shift;
7825       return *this;
7826     }
7827
7828     bool operator==(const Cost &RHS) const {
7829       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7830              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7831              ZExts == RHS.ZExts && Shift == RHS.Shift;
7832     }
7833
7834     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7835
7836     bool operator<(const Cost &RHS) const {
7837       // Assume cross register banks copies are as expensive as loads.
7838       // FIXME: Do we want some more target hooks?
7839       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7840       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7841       // Unless we are optimizing for code size, consider the
7842       // expensive operation first.
7843       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7844         return ExpensiveOpsLHS < ExpensiveOpsRHS;
7845       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7846              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7847     }
7848
7849     bool operator>(const Cost &RHS) const { return RHS < *this; }
7850
7851     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7852
7853     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7854   };
7855   // The last instruction that represent the slice. This should be a
7856   // truncate instruction.
7857   SDNode *Inst;
7858   // The original load instruction.
7859   LoadSDNode *Origin;
7860   // The right shift amount in bits from the original load.
7861   unsigned Shift;
7862   // The DAG from which Origin came from.
7863   // This is used to get some contextual information about legal types, etc.
7864   SelectionDAG *DAG;
7865
7866   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7867               unsigned Shift = 0, SelectionDAG *DAG = NULL)
7868       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7869
7870   LoadedSlice(const LoadedSlice &LS)
7871       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7872
7873   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7874   /// \return Result is \p BitWidth and has used bits set to 1 and
7875   ///         not used bits set to 0.
7876   APInt getUsedBits() const {
7877     // Reproduce the trunc(lshr) sequence:
7878     // - Start from the truncated value.
7879     // - Zero extend to the desired bit width.
7880     // - Shift left.
7881     assert(Origin && "No original load to compare against.");
7882     unsigned BitWidth = Origin->getValueSizeInBits(0);
7883     assert(Inst && "This slice is not bound to an instruction");
7884     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7885            "Extracted slice is bigger than the whole type!");
7886     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7887     UsedBits.setAllBits();
7888     UsedBits = UsedBits.zext(BitWidth);
7889     UsedBits <<= Shift;
7890     return UsedBits;
7891   }
7892
7893   /// \brief Get the size of the slice to be loaded in bytes.
7894   unsigned getLoadedSize() const {
7895     unsigned SliceSize = getUsedBits().countPopulation();
7896     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7897     return SliceSize / 8;
7898   }
7899
7900   /// \brief Get the type that will be loaded for this slice.
7901   /// Note: This may not be the final type for the slice.
7902   EVT getLoadedType() const {
7903     assert(DAG && "Missing context");
7904     LLVMContext &Ctxt = *DAG->getContext();
7905     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7906   }
7907
7908   /// \brief Get the alignment of the load used for this slice.
7909   unsigned getAlignment() const {
7910     unsigned Alignment = Origin->getAlignment();
7911     unsigned Offset = getOffsetFromBase();
7912     if (Offset != 0)
7913       Alignment = MinAlign(Alignment, Alignment + Offset);
7914     return Alignment;
7915   }
7916
7917   /// \brief Check if this slice can be rewritten with legal operations.
7918   bool isLegal() const {
7919     // An invalid slice is not legal.
7920     if (!Origin || !Inst || !DAG)
7921       return false;
7922
7923     // Offsets are for indexed load only, we do not handle that.
7924     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7925       return false;
7926
7927     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7928
7929     // Check that the type is legal.
7930     EVT SliceType = getLoadedType();
7931     if (!TLI.isTypeLegal(SliceType))
7932       return false;
7933
7934     // Check that the load is legal for this type.
7935     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7936       return false;
7937
7938     // Check that the offset can be computed.
7939     // 1. Check its type.
7940     EVT PtrType = Origin->getBasePtr().getValueType();
7941     if (PtrType == MVT::Untyped || PtrType.isExtended())
7942       return false;
7943
7944     // 2. Check that it fits in the immediate.
7945     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7946       return false;
7947
7948     // 3. Check that the computation is legal.
7949     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7950       return false;
7951
7952     // Check that the zext is legal if it needs one.
7953     EVT TruncateType = Inst->getValueType(0);
7954     if (TruncateType != SliceType &&
7955         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7956       return false;
7957
7958     return true;
7959   }
7960
7961   /// \brief Get the offset in bytes of this slice in the original chunk of
7962   /// bits.
7963   /// \pre DAG != NULL.
7964   uint64_t getOffsetFromBase() const {
7965     assert(DAG && "Missing context.");
7966     bool IsBigEndian =
7967         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7968     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7969     uint64_t Offset = Shift / 8;
7970     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7971     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7972            "The size of the original loaded type is not a multiple of a"
7973            " byte.");
7974     // If Offset is bigger than TySizeInBytes, it means we are loading all
7975     // zeros. This should have been optimized before in the process.
7976     assert(TySizeInBytes > Offset &&
7977            "Invalid shift amount for given loaded size");
7978     if (IsBigEndian)
7979       Offset = TySizeInBytes - Offset - getLoadedSize();
7980     return Offset;
7981   }
7982
7983   /// \brief Generate the sequence of instructions to load the slice
7984   /// represented by this object and redirect the uses of this slice to
7985   /// this new sequence of instructions.
7986   /// \pre this->Inst && this->Origin are valid Instructions and this
7987   /// object passed the legal check: LoadedSlice::isLegal returned true.
7988   /// \return The last instruction of the sequence used to load the slice.
7989   SDValue loadSlice() const {
7990     assert(Inst && Origin && "Unable to replace a non-existing slice.");
7991     const SDValue &OldBaseAddr = Origin->getBasePtr();
7992     SDValue BaseAddr = OldBaseAddr;
7993     // Get the offset in that chunk of bytes w.r.t. the endianess.
7994     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7995     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7996     if (Offset) {
7997       // BaseAddr = BaseAddr + Offset.
7998       EVT ArithType = BaseAddr.getValueType();
7999       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8000                               DAG->getConstant(Offset, ArithType));
8001     }
8002
8003     // Create the type of the loaded slice according to its size.
8004     EVT SliceType = getLoadedType();
8005
8006     // Create the load for the slice.
8007     SDValue LastInst = DAG->getLoad(
8008         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8009         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8010         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8011     // If the final type is not the same as the loaded type, this means that
8012     // we have to pad with zero. Create a zero extend for that.
8013     EVT FinalType = Inst->getValueType(0);
8014     if (SliceType != FinalType)
8015       LastInst =
8016           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8017     return LastInst;
8018   }
8019
8020   /// \brief Check if this slice can be merged with an expensive cross register
8021   /// bank copy. E.g.,
8022   /// i = load i32
8023   /// f = bitcast i32 i to float
8024   bool canMergeExpensiveCrossRegisterBankCopy() const {
8025     if (!Inst || !Inst->hasOneUse())
8026       return false;
8027     SDNode *Use = *Inst->use_begin();
8028     if (Use->getOpcode() != ISD::BITCAST)
8029       return false;
8030     assert(DAG && "Missing context");
8031     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8032     EVT ResVT = Use->getValueType(0);
8033     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8034     const TargetRegisterClass *ArgRC =
8035         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8036     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8037       return false;
8038
8039     // At this point, we know that we perform a cross-register-bank copy.
8040     // Check if it is expensive.
8041     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8042     // Assume bitcasts are cheap, unless both register classes do not
8043     // explicitly share a common sub class.
8044     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8045       return false;
8046
8047     // Check if it will be merged with the load.
8048     // 1. Check the alignment constraint.
8049     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8050         ResVT.getTypeForEVT(*DAG->getContext()));
8051
8052     if (RequiredAlignment > getAlignment())
8053       return false;
8054
8055     // 2. Check that the load is a legal operation for that type.
8056     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8057       return false;
8058
8059     // 3. Check that we do not have a zext in the way.
8060     if (Inst->getValueType(0) != getLoadedType())
8061       return false;
8062
8063     return true;
8064   }
8065 };
8066 }
8067
8068 /// \brief Sorts LoadedSlice according to their offset.
8069 struct LoadedSliceSorter {
8070   bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8071     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8072     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8073   }
8074 };
8075
8076 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8077 /// \p UsedBits looks like 0..0 1..1 0..0.
8078 static bool areUsedBitsDense(const APInt &UsedBits) {
8079   // If all the bits are one, this is dense!
8080   if (UsedBits.isAllOnesValue())
8081     return true;
8082
8083   // Get rid of the unused bits on the right.
8084   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8085   // Get rid of the unused bits on the left.
8086   if (NarrowedUsedBits.countLeadingZeros())
8087     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8088   // Check that the chunk of bits is completely used.
8089   return NarrowedUsedBits.isAllOnesValue();
8090 }
8091
8092 /// \brief Check whether or not \p First and \p Second are next to each other
8093 /// in memory. This means that there is no hole between the bits loaded
8094 /// by \p First and the bits loaded by \p Second.
8095 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8096                                      const LoadedSlice &Second) {
8097   assert(First.Origin == Second.Origin && First.Origin &&
8098          "Unable to match different memory origins.");
8099   APInt UsedBits = First.getUsedBits();
8100   assert((UsedBits & Second.getUsedBits()) == 0 &&
8101          "Slices are not supposed to overlap.");
8102   UsedBits |= Second.getUsedBits();
8103   return areUsedBitsDense(UsedBits);
8104 }
8105
8106 /// \brief Adjust the \p GlobalLSCost according to the target
8107 /// paring capabilities and the layout of the slices.
8108 /// \pre \p GlobalLSCost should account for at least as many loads as
8109 /// there is in the slices in \p LoadedSlices.
8110 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8111                                  LoadedSlice::Cost &GlobalLSCost) {
8112   unsigned NumberOfSlices = LoadedSlices.size();
8113   // If there is less than 2 elements, no pairing is possible.
8114   if (NumberOfSlices < 2)
8115     return;
8116
8117   // Sort the slices so that elements that are likely to be next to each
8118   // other in memory are next to each other in the list.
8119   std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8120   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8121   // First (resp. Second) is the first (resp. Second) potentially candidate
8122   // to be placed in a paired load.
8123   const LoadedSlice *First = NULL;
8124   const LoadedSlice *Second = NULL;
8125   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8126                 // Set the beginning of the pair.
8127                                                            First = Second) {
8128
8129     Second = &LoadedSlices[CurrSlice];
8130
8131     // If First is NULL, it means we start a new pair.
8132     // Get to the next slice.
8133     if (!First)
8134       continue;
8135
8136     EVT LoadedType = First->getLoadedType();
8137
8138     // If the types of the slices are different, we cannot pair them.
8139     if (LoadedType != Second->getLoadedType())
8140       continue;
8141
8142     // Check if the target supplies paired loads for this type.
8143     unsigned RequiredAlignment = 0;
8144     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8145       // move to the next pair, this type is hopeless.
8146       Second = NULL;
8147       continue;
8148     }
8149     // Check if we meet the alignment requirement.
8150     if (RequiredAlignment > First->getAlignment())
8151       continue;
8152
8153     // Check that both loads are next to each other in memory.
8154     if (!areSlicesNextToEachOther(*First, *Second))
8155       continue;
8156
8157     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8158     --GlobalLSCost.Loads;
8159     // Move to the next pair.
8160     Second = NULL;
8161   }
8162 }
8163
8164 /// \brief Check the profitability of all involved LoadedSlice.
8165 /// Currently, it is considered profitable if there is exactly two
8166 /// involved slices (1) which are (2) next to each other in memory, and
8167 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8168 ///
8169 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8170 /// the elements themselves.
8171 ///
8172 /// FIXME: When the cost model will be mature enough, we can relax
8173 /// constraints (1) and (2).
8174 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8175                                 const APInt &UsedBits, bool ForCodeSize) {
8176   unsigned NumberOfSlices = LoadedSlices.size();
8177   if (StressLoadSlicing)
8178     return NumberOfSlices > 1;
8179
8180   // Check (1).
8181   if (NumberOfSlices != 2)
8182     return false;
8183
8184   // Check (2).
8185   if (!areUsedBitsDense(UsedBits))
8186     return false;
8187
8188   // Check (3).
8189   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8190   // The original code has one big load.
8191   OrigCost.Loads = 1;
8192   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8193     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8194     // Accumulate the cost of all the slices.
8195     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8196     GlobalSlicingCost += SliceCost;
8197
8198     // Account as cost in the original configuration the gain obtained
8199     // with the current slices.
8200     OrigCost.addSliceGain(LS);
8201   }
8202
8203   // If the target supports paired load, adjust the cost accordingly.
8204   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8205   return OrigCost > GlobalSlicingCost;
8206 }
8207
8208 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8209 /// operations, split it in the various pieces being extracted.
8210 ///
8211 /// This sort of thing is introduced by SROA.
8212 /// This slicing takes care not to insert overlapping loads.
8213 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8214 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8215   if (Level < AfterLegalizeDAG)
8216     return false;
8217
8218   LoadSDNode *LD = cast<LoadSDNode>(N);
8219   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8220       !LD->getValueType(0).isInteger())
8221     return false;
8222
8223   // Keep track of already used bits to detect overlapping values.
8224   // In that case, we will just abort the transformation.
8225   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8226
8227   SmallVector<LoadedSlice, 4> LoadedSlices;
8228
8229   // Check if this load is used as several smaller chunks of bits.
8230   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8231   // of computation for each trunc.
8232   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8233        UI != UIEnd; ++UI) {
8234     // Skip the uses of the chain.
8235     if (UI.getUse().getResNo() != 0)
8236       continue;
8237
8238     SDNode *User = *UI;
8239     unsigned Shift = 0;
8240
8241     // Check if this is a trunc(lshr).
8242     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8243         isa<ConstantSDNode>(User->getOperand(1))) {
8244       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8245       User = *User->use_begin();
8246     }
8247
8248     // At this point, User is a Truncate, iff we encountered, trunc or
8249     // trunc(lshr).
8250     if (User->getOpcode() != ISD::TRUNCATE)
8251       return false;
8252
8253     // The width of the type must be a power of 2 and greater than 8-bits.
8254     // Otherwise the load cannot be represented in LLVM IR.
8255     // Moreover, if we shifted with a non-8-bits multiple, the slice
8256     // will be accross several bytes. We do not support that.
8257     unsigned Width = User->getValueSizeInBits(0);
8258     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8259       return 0;
8260
8261     // Build the slice for this chain of computations.
8262     LoadedSlice LS(User, LD, Shift, &DAG);
8263     APInt CurrentUsedBits = LS.getUsedBits();
8264
8265     // Check if this slice overlaps with another.
8266     if ((CurrentUsedBits & UsedBits) != 0)
8267       return false;
8268     // Update the bits used globally.
8269     UsedBits |= CurrentUsedBits;
8270
8271     // Check if the new slice would be legal.
8272     if (!LS.isLegal())
8273       return false;
8274
8275     // Record the slice.
8276     LoadedSlices.push_back(LS);
8277   }
8278
8279   // Abort slicing if it does not seem to be profitable.
8280   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8281     return false;
8282
8283   ++SlicedLoads;
8284
8285   // Rewrite each chain to use an independent load.
8286   // By construction, each chain can be represented by a unique load.
8287
8288   // Prepare the argument for the new token factor for all the slices.
8289   SmallVector<SDValue, 8> ArgChains;
8290   for (SmallVectorImpl<LoadedSlice>::const_iterator
8291            LSIt = LoadedSlices.begin(),
8292            LSItEnd = LoadedSlices.end();
8293        LSIt != LSItEnd; ++LSIt) {
8294     SDValue SliceInst = LSIt->loadSlice();
8295     CombineTo(LSIt->Inst, SliceInst, true);
8296     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8297       SliceInst = SliceInst.getOperand(0);
8298     assert(SliceInst->getOpcode() == ISD::LOAD &&
8299            "It takes more than a zext to get to the loaded slice!!");
8300     ArgChains.push_back(SliceInst.getValue(1));
8301   }
8302
8303   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8304                               &ArgChains[0], ArgChains.size());
8305   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8306   return true;
8307 }
8308
8309 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8310 /// load is having specific bytes cleared out.  If so, return the byte size
8311 /// being masked out and the shift amount.
8312 static std::pair<unsigned, unsigned>
8313 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8314   std::pair<unsigned, unsigned> Result(0, 0);
8315
8316   // Check for the structure we're looking for.
8317   if (V->getOpcode() != ISD::AND ||
8318       !isa<ConstantSDNode>(V->getOperand(1)) ||
8319       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8320     return Result;
8321
8322   // Check the chain and pointer.
8323   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8324   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8325
8326   // The store should be chained directly to the load or be an operand of a
8327   // tokenfactor.
8328   if (LD == Chain.getNode())
8329     ; // ok.
8330   else if (Chain->getOpcode() != ISD::TokenFactor)
8331     return Result; // Fail.
8332   else {
8333     bool isOk = false;
8334     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8335       if (Chain->getOperand(i).getNode() == LD) {
8336         isOk = true;
8337         break;
8338       }
8339     if (!isOk) return Result;
8340   }
8341
8342   // This only handles simple types.
8343   if (V.getValueType() != MVT::i16 &&
8344       V.getValueType() != MVT::i32 &&
8345       V.getValueType() != MVT::i64)
8346     return Result;
8347
8348   // Check the constant mask.  Invert it so that the bits being masked out are
8349   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8350   // follow the sign bit for uniformity.
8351   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8352   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8353   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8354   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8355   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8356   if (NotMaskLZ == 64) return Result;  // All zero mask.
8357
8358   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8359   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8360     return Result;
8361
8362   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8363   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8364     NotMaskLZ -= 64-V.getValueSizeInBits();
8365
8366   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8367   switch (MaskedBytes) {
8368   case 1:
8369   case 2:
8370   case 4: break;
8371   default: return Result; // All one mask, or 5-byte mask.
8372   }
8373
8374   // Verify that the first bit starts at a multiple of mask so that the access
8375   // is aligned the same as the access width.
8376   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8377
8378   Result.first = MaskedBytes;
8379   Result.second = NotMaskTZ/8;
8380   return Result;
8381 }
8382
8383
8384 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8385 /// provides a value as specified by MaskInfo.  If so, replace the specified
8386 /// store with a narrower store of truncated IVal.
8387 static SDNode *
8388 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8389                                 SDValue IVal, StoreSDNode *St,
8390                                 DAGCombiner *DC) {
8391   unsigned NumBytes = MaskInfo.first;
8392   unsigned ByteShift = MaskInfo.second;
8393   SelectionDAG &DAG = DC->getDAG();
8394
8395   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8396   // that uses this.  If not, this is not a replacement.
8397   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8398                                   ByteShift*8, (ByteShift+NumBytes)*8);
8399   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8400
8401   // Check that it is legal on the target to do this.  It is legal if the new
8402   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8403   // legalization.
8404   MVT VT = MVT::getIntegerVT(NumBytes*8);
8405   if (!DC->isTypeLegal(VT))
8406     return 0;
8407
8408   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8409   // shifted by ByteShift and truncated down to NumBytes.
8410   if (ByteShift)
8411     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8412                        DAG.getConstant(ByteShift*8,
8413                                     DC->getShiftAmountTy(IVal.getValueType())));
8414
8415   // Figure out the offset for the store and the alignment of the access.
8416   unsigned StOffset;
8417   unsigned NewAlign = St->getAlignment();
8418
8419   if (DAG.getTargetLoweringInfo().isLittleEndian())
8420     StOffset = ByteShift;
8421   else
8422     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8423
8424   SDValue Ptr = St->getBasePtr();
8425   if (StOffset) {
8426     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8427                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8428     NewAlign = MinAlign(NewAlign, StOffset);
8429   }
8430
8431   // Truncate down to the new size.
8432   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8433
8434   ++OpsNarrowed;
8435   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8436                       St->getPointerInfo().getWithOffset(StOffset),
8437                       false, false, NewAlign).getNode();
8438 }
8439
8440
8441 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8442 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8443 /// of the loaded bits, try narrowing the load and store if it would end up
8444 /// being a win for performance or code size.
8445 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8446   StoreSDNode *ST  = cast<StoreSDNode>(N);
8447   if (ST->isVolatile())
8448     return SDValue();
8449
8450   SDValue Chain = ST->getChain();
8451   SDValue Value = ST->getValue();
8452   SDValue Ptr   = ST->getBasePtr();
8453   EVT VT = Value.getValueType();
8454
8455   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8456     return SDValue();
8457
8458   unsigned Opc = Value.getOpcode();
8459
8460   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8461   // is a byte mask indicating a consecutive number of bytes, check to see if
8462   // Y is known to provide just those bytes.  If so, we try to replace the
8463   // load + replace + store sequence with a single (narrower) store, which makes
8464   // the load dead.
8465   if (Opc == ISD::OR) {
8466     std::pair<unsigned, unsigned> MaskedLoad;
8467     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8468     if (MaskedLoad.first)
8469       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8470                                                   Value.getOperand(1), ST,this))
8471         return SDValue(NewST, 0);
8472
8473     // Or is commutative, so try swapping X and Y.
8474     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8475     if (MaskedLoad.first)
8476       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8477                                                   Value.getOperand(0), ST,this))
8478         return SDValue(NewST, 0);
8479   }
8480
8481   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8482       Value.getOperand(1).getOpcode() != ISD::Constant)
8483     return SDValue();
8484
8485   SDValue N0 = Value.getOperand(0);
8486   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8487       Chain == SDValue(N0.getNode(), 1)) {
8488     LoadSDNode *LD = cast<LoadSDNode>(N0);
8489     if (LD->getBasePtr() != Ptr ||
8490         LD->getPointerInfo().getAddrSpace() !=
8491         ST->getPointerInfo().getAddrSpace())
8492       return SDValue();
8493
8494     // Find the type to narrow it the load / op / store to.
8495     SDValue N1 = Value.getOperand(1);
8496     unsigned BitWidth = N1.getValueSizeInBits();
8497     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8498     if (Opc == ISD::AND)
8499       Imm ^= APInt::getAllOnesValue(BitWidth);
8500     if (Imm == 0 || Imm.isAllOnesValue())
8501       return SDValue();
8502     unsigned ShAmt = Imm.countTrailingZeros();
8503     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8504     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8505     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8506     while (NewBW < BitWidth &&
8507            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8508              TLI.isNarrowingProfitable(VT, NewVT))) {
8509       NewBW = NextPowerOf2(NewBW);
8510       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8511     }
8512     if (NewBW >= BitWidth)
8513       return SDValue();
8514
8515     // If the lsb changed does not start at the type bitwidth boundary,
8516     // start at the previous one.
8517     if (ShAmt % NewBW)
8518       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8519     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8520                                    std::min(BitWidth, ShAmt + NewBW));
8521     if ((Imm & Mask) == Imm) {
8522       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8523       if (Opc == ISD::AND)
8524         NewImm ^= APInt::getAllOnesValue(NewBW);
8525       uint64_t PtrOff = ShAmt / 8;
8526       // For big endian targets, we need to adjust the offset to the pointer to
8527       // load the correct bytes.
8528       if (TLI.isBigEndian())
8529         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8530
8531       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8532       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8533       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8534         return SDValue();
8535
8536       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8537                                    Ptr.getValueType(), Ptr,
8538                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8539       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8540                                   LD->getChain(), NewPtr,
8541                                   LD->getPointerInfo().getWithOffset(PtrOff),
8542                                   LD->isVolatile(), LD->isNonTemporal(),
8543                                   LD->isInvariant(), NewAlign,
8544                                   LD->getTBAAInfo());
8545       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8546                                    DAG.getConstant(NewImm, NewVT));
8547       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8548                                    NewVal, NewPtr,
8549                                    ST->getPointerInfo().getWithOffset(PtrOff),
8550                                    false, false, NewAlign);
8551
8552       AddToWorkList(NewPtr.getNode());
8553       AddToWorkList(NewLD.getNode());
8554       AddToWorkList(NewVal.getNode());
8555       WorkListRemover DeadNodes(*this);
8556       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8557       ++OpsNarrowed;
8558       return NewST;
8559     }
8560   }
8561
8562   return SDValue();
8563 }
8564
8565 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8566 /// if the load value isn't used by any other operations, then consider
8567 /// transforming the pair to integer load / store operations if the target
8568 /// deems the transformation profitable.
8569 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8570   StoreSDNode *ST  = cast<StoreSDNode>(N);
8571   SDValue Chain = ST->getChain();
8572   SDValue Value = ST->getValue();
8573   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8574       Value.hasOneUse() &&
8575       Chain == SDValue(Value.getNode(), 1)) {
8576     LoadSDNode *LD = cast<LoadSDNode>(Value);
8577     EVT VT = LD->getMemoryVT();
8578     if (!VT.isFloatingPoint() ||
8579         VT != ST->getMemoryVT() ||
8580         LD->isNonTemporal() ||
8581         ST->isNonTemporal() ||
8582         LD->getPointerInfo().getAddrSpace() != 0 ||
8583         ST->getPointerInfo().getAddrSpace() != 0)
8584       return SDValue();
8585
8586     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8587     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8588         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8589         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8590         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8591       return SDValue();
8592
8593     unsigned LDAlign = LD->getAlignment();
8594     unsigned STAlign = ST->getAlignment();
8595     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8596     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8597     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8598       return SDValue();
8599
8600     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8601                                 LD->getChain(), LD->getBasePtr(),
8602                                 LD->getPointerInfo(),
8603                                 false, false, false, LDAlign);
8604
8605     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8606                                  NewLD, ST->getBasePtr(),
8607                                  ST->getPointerInfo(),
8608                                  false, false, STAlign);
8609
8610     AddToWorkList(NewLD.getNode());
8611     AddToWorkList(NewST.getNode());
8612     WorkListRemover DeadNodes(*this);
8613     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8614     ++LdStFP2Int;
8615     return NewST;
8616   }
8617
8618   return SDValue();
8619 }
8620
8621 /// Helper struct to parse and store a memory address as base + index + offset.
8622 /// We ignore sign extensions when it is safe to do so.
8623 /// The following two expressions are not equivalent. To differentiate we need
8624 /// to store whether there was a sign extension involved in the index
8625 /// computation.
8626 ///  (load (i64 add (i64 copyfromreg %c)
8627 ///                 (i64 signextend (add (i8 load %index)
8628 ///                                      (i8 1))))
8629 /// vs
8630 ///
8631 /// (load (i64 add (i64 copyfromreg %c)
8632 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8633 ///                                         (i32 1)))))
8634 struct BaseIndexOffset {
8635   SDValue Base;
8636   SDValue Index;
8637   int64_t Offset;
8638   bool IsIndexSignExt;
8639
8640   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8641
8642   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8643                   bool IsIndexSignExt) :
8644     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8645
8646   bool equalBaseIndex(const BaseIndexOffset &Other) {
8647     return Other.Base == Base && Other.Index == Index &&
8648       Other.IsIndexSignExt == IsIndexSignExt;
8649   }
8650
8651   /// Parses tree in Ptr for base, index, offset addresses.
8652   static BaseIndexOffset match(SDValue Ptr) {
8653     bool IsIndexSignExt = false;
8654
8655     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8656     // instruction, then it could be just the BASE or everything else we don't
8657     // know how to handle. Just use Ptr as BASE and give up.
8658     if (Ptr->getOpcode() != ISD::ADD)
8659       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8660
8661     // We know that we have at least an ADD instruction. Try to pattern match
8662     // the simple case of BASE + OFFSET.
8663     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8664       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8665       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8666                               IsIndexSignExt);
8667     }
8668
8669     // Inside a loop the current BASE pointer is calculated using an ADD and a
8670     // MUL instruction. In this case Ptr is the actual BASE pointer.
8671     // (i64 add (i64 %array_ptr)
8672     //          (i64 mul (i64 %induction_var)
8673     //                   (i64 %element_size)))
8674     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8675       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8676
8677     // Look at Base + Index + Offset cases.
8678     SDValue Base = Ptr->getOperand(0);
8679     SDValue IndexOffset = Ptr->getOperand(1);
8680
8681     // Skip signextends.
8682     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8683       IndexOffset = IndexOffset->getOperand(0);
8684       IsIndexSignExt = true;
8685     }
8686
8687     // Either the case of Base + Index (no offset) or something else.
8688     if (IndexOffset->getOpcode() != ISD::ADD)
8689       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8690
8691     // Now we have the case of Base + Index + offset.
8692     SDValue Index = IndexOffset->getOperand(0);
8693     SDValue Offset = IndexOffset->getOperand(1);
8694
8695     if (!isa<ConstantSDNode>(Offset))
8696       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8697
8698     // Ignore signextends.
8699     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8700       Index = Index->getOperand(0);
8701       IsIndexSignExt = true;
8702     } else IsIndexSignExt = false;
8703
8704     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8705     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8706   }
8707 };
8708
8709 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8710 /// is located in a sequence of memory operations connected by a chain.
8711 struct MemOpLink {
8712   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8713     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8714   // Ptr to the mem node.
8715   LSBaseSDNode *MemNode;
8716   // Offset from the base ptr.
8717   int64_t OffsetFromBase;
8718   // What is the sequence number of this mem node.
8719   // Lowest mem operand in the DAG starts at zero.
8720   unsigned SequenceNum;
8721 };
8722
8723 /// Sorts store nodes in a link according to their offset from a shared
8724 // base ptr.
8725 struct ConsecutiveMemoryChainSorter {
8726   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8727     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8728   }
8729 };
8730
8731 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8732   EVT MemVT = St->getMemoryVT();
8733   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8734   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8735     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8736
8737   // Don't merge vectors into wider inputs.
8738   if (MemVT.isVector() || !MemVT.isSimple())
8739     return false;
8740
8741   // Perform an early exit check. Do not bother looking at stored values that
8742   // are not constants or loads.
8743   SDValue StoredVal = St->getValue();
8744   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8745   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8746       !IsLoadSrc)
8747     return false;
8748
8749   // Only look at ends of store sequences.
8750   SDValue Chain = SDValue(St, 1);
8751   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8752     return false;
8753
8754   // This holds the base pointer, index, and the offset in bytes from the base
8755   // pointer.
8756   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8757
8758   // We must have a base and an offset.
8759   if (!BasePtr.Base.getNode())
8760     return false;
8761
8762   // Do not handle stores to undef base pointers.
8763   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8764     return false;
8765
8766   // Save the LoadSDNodes that we find in the chain.
8767   // We need to make sure that these nodes do not interfere with
8768   // any of the store nodes.
8769   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8770
8771   // Save the StoreSDNodes that we find in the chain.
8772   SmallVector<MemOpLink, 8> StoreNodes;
8773
8774   // Walk up the chain and look for nodes with offsets from the same
8775   // base pointer. Stop when reaching an instruction with a different kind
8776   // or instruction which has a different base pointer.
8777   unsigned Seq = 0;
8778   StoreSDNode *Index = St;
8779   while (Index) {
8780     // If the chain has more than one use, then we can't reorder the mem ops.
8781     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8782       break;
8783
8784     // Find the base pointer and offset for this memory node.
8785     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8786
8787     // Check that the base pointer is the same as the original one.
8788     if (!Ptr.equalBaseIndex(BasePtr))
8789       break;
8790
8791     // Check that the alignment is the same.
8792     if (Index->getAlignment() != St->getAlignment())
8793       break;
8794
8795     // The memory operands must not be volatile.
8796     if (Index->isVolatile() || Index->isIndexed())
8797       break;
8798
8799     // No truncation.
8800     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8801       if (St->isTruncatingStore())
8802         break;
8803
8804     // The stored memory type must be the same.
8805     if (Index->getMemoryVT() != MemVT)
8806       break;
8807
8808     // We do not allow unaligned stores because we want to prevent overriding
8809     // stores.
8810     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8811       break;
8812
8813     // We found a potential memory operand to merge.
8814     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8815
8816     // Find the next memory operand in the chain. If the next operand in the
8817     // chain is a store then move up and continue the scan with the next
8818     // memory operand. If the next operand is a load save it and use alias
8819     // information to check if it interferes with anything.
8820     SDNode *NextInChain = Index->getChain().getNode();
8821     while (1) {
8822       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8823         // We found a store node. Use it for the next iteration.
8824         Index = STn;
8825         break;
8826       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8827         if (Ldn->isVolatile()) {
8828           Index = NULL;
8829           break;
8830         }
8831
8832         // Save the load node for later. Continue the scan.
8833         AliasLoadNodes.push_back(Ldn);
8834         NextInChain = Ldn->getChain().getNode();
8835         continue;
8836       } else {
8837         Index = NULL;
8838         break;
8839       }
8840     }
8841   }
8842
8843   // Check if there is anything to merge.
8844   if (StoreNodes.size() < 2)
8845     return false;
8846
8847   // Sort the memory operands according to their distance from the base pointer.
8848   std::sort(StoreNodes.begin(), StoreNodes.end(),
8849             ConsecutiveMemoryChainSorter());
8850
8851   // Scan the memory operations on the chain and find the first non-consecutive
8852   // store memory address.
8853   unsigned LastConsecutiveStore = 0;
8854   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8855   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8856
8857     // Check that the addresses are consecutive starting from the second
8858     // element in the list of stores.
8859     if (i > 0) {
8860       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8861       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8862         break;
8863     }
8864
8865     bool Alias = false;
8866     // Check if this store interferes with any of the loads that we found.
8867     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8868       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8869         Alias = true;
8870         break;
8871       }
8872     // We found a load that alias with this store. Stop the sequence.
8873     if (Alias)
8874       break;
8875
8876     // Mark this node as useful.
8877     LastConsecutiveStore = i;
8878   }
8879
8880   // The node with the lowest store address.
8881   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8882
8883   // Store the constants into memory as one consecutive store.
8884   if (!IsLoadSrc) {
8885     unsigned LastLegalType = 0;
8886     unsigned LastLegalVectorType = 0;
8887     bool NonZero = false;
8888     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8889       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8890       SDValue StoredVal = St->getValue();
8891
8892       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8893         NonZero |= !C->isNullValue();
8894       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8895         NonZero |= !C->getConstantFPValue()->isNullValue();
8896       } else {
8897         // Non-constant.
8898         break;
8899       }
8900
8901       // Find a legal type for the constant store.
8902       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8903       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8904       if (TLI.isTypeLegal(StoreTy))
8905         LastLegalType = i+1;
8906       // Or check whether a truncstore is legal.
8907       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8908                TargetLowering::TypePromoteInteger) {
8909         EVT LegalizedStoredValueTy =
8910           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8911         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8912           LastLegalType = i+1;
8913       }
8914
8915       // Find a legal type for the vector store.
8916       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8917       if (TLI.isTypeLegal(Ty))
8918         LastLegalVectorType = i + 1;
8919     }
8920
8921     // We only use vectors if the constant is known to be zero and the
8922     // function is not marked with the noimplicitfloat attribute.
8923     if (NonZero || NoVectors)
8924       LastLegalVectorType = 0;
8925
8926     // Check if we found a legal integer type to store.
8927     if (LastLegalType == 0 && LastLegalVectorType == 0)
8928       return false;
8929
8930     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8931     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8932
8933     // Make sure we have something to merge.
8934     if (NumElem < 2)
8935       return false;
8936
8937     unsigned EarliestNodeUsed = 0;
8938     for (unsigned i=0; i < NumElem; ++i) {
8939       // Find a chain for the new wide-store operand. Notice that some
8940       // of the store nodes that we found may not be selected for inclusion
8941       // in the wide store. The chain we use needs to be the chain of the
8942       // earliest store node which is *used* and replaced by the wide store.
8943       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8944         EarliestNodeUsed = i;
8945     }
8946
8947     // The earliest Node in the DAG.
8948     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8949     SDLoc DL(StoreNodes[0].MemNode);
8950
8951     SDValue StoredVal;
8952     if (UseVector) {
8953       // Find a legal type for the vector store.
8954       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8955       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8956       StoredVal = DAG.getConstant(0, Ty);
8957     } else {
8958       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8959       APInt StoreInt(StoreBW, 0);
8960
8961       // Construct a single integer constant which is made of the smaller
8962       // constant inputs.
8963       bool IsLE = TLI.isLittleEndian();
8964       for (unsigned i = 0; i < NumElem ; ++i) {
8965         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8966         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8967         SDValue Val = St->getValue();
8968         StoreInt<<=ElementSizeBytes*8;
8969         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8970           StoreInt|=C->getAPIntValue().zext(StoreBW);
8971         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8972           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8973         } else {
8974           assert(false && "Invalid constant element type");
8975         }
8976       }
8977
8978       // Create the new Load and Store operations.
8979       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8980       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8981     }
8982
8983     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8984                                     FirstInChain->getBasePtr(),
8985                                     FirstInChain->getPointerInfo(),
8986                                     false, false,
8987                                     FirstInChain->getAlignment());
8988
8989     // Replace the first store with the new store
8990     CombineTo(EarliestOp, NewStore);
8991     // Erase all other stores.
8992     for (unsigned i = 0; i < NumElem ; ++i) {
8993       if (StoreNodes[i].MemNode == EarliestOp)
8994         continue;
8995       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8996       // ReplaceAllUsesWith will replace all uses that existed when it was
8997       // called, but graph optimizations may cause new ones to appear. For
8998       // example, the case in pr14333 looks like
8999       //
9000       //  St's chain -> St -> another store -> X
9001       //
9002       // And the only difference from St to the other store is the chain.
9003       // When we change it's chain to be St's chain they become identical,
9004       // get CSEed and the net result is that X is now a use of St.
9005       // Since we know that St is redundant, just iterate.
9006       while (!St->use_empty())
9007         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9008       removeFromWorkList(St);
9009       DAG.DeleteNode(St);
9010     }
9011
9012     return true;
9013   }
9014
9015   // Below we handle the case of multiple consecutive stores that
9016   // come from multiple consecutive loads. We merge them into a single
9017   // wide load and a single wide store.
9018
9019   // Look for load nodes which are used by the stored values.
9020   SmallVector<MemOpLink, 8> LoadNodes;
9021
9022   // Find acceptable loads. Loads need to have the same chain (token factor),
9023   // must not be zext, volatile, indexed, and they must be consecutive.
9024   BaseIndexOffset LdBasePtr;
9025   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9026     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9027     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9028     if (!Ld) break;
9029
9030     // Loads must only have one use.
9031     if (!Ld->hasNUsesOfValue(1, 0))
9032       break;
9033
9034     // Check that the alignment is the same as the stores.
9035     if (Ld->getAlignment() != St->getAlignment())
9036       break;
9037
9038     // The memory operands must not be volatile.
9039     if (Ld->isVolatile() || Ld->isIndexed())
9040       break;
9041
9042     // We do not accept ext loads.
9043     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9044       break;
9045
9046     // The stored memory type must be the same.
9047     if (Ld->getMemoryVT() != MemVT)
9048       break;
9049
9050     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9051     // If this is not the first ptr that we check.
9052     if (LdBasePtr.Base.getNode()) {
9053       // The base ptr must be the same.
9054       if (!LdPtr.equalBaseIndex(LdBasePtr))
9055         break;
9056     } else {
9057       // Check that all other base pointers are the same as this one.
9058       LdBasePtr = LdPtr;
9059     }
9060
9061     // We found a potential memory operand to merge.
9062     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9063   }
9064
9065   if (LoadNodes.size() < 2)
9066     return false;
9067
9068   // Scan the memory operations on the chain and find the first non-consecutive
9069   // load memory address. These variables hold the index in the store node
9070   // array.
9071   unsigned LastConsecutiveLoad = 0;
9072   // This variable refers to the size and not index in the array.
9073   unsigned LastLegalVectorType = 0;
9074   unsigned LastLegalIntegerType = 0;
9075   StartAddress = LoadNodes[0].OffsetFromBase;
9076   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9077   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9078     // All loads much share the same chain.
9079     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9080       break;
9081
9082     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9083     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9084       break;
9085     LastConsecutiveLoad = i;
9086
9087     // Find a legal type for the vector store.
9088     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9089     if (TLI.isTypeLegal(StoreTy))
9090       LastLegalVectorType = i + 1;
9091
9092     // Find a legal type for the integer store.
9093     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9094     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9095     if (TLI.isTypeLegal(StoreTy))
9096       LastLegalIntegerType = i + 1;
9097     // Or check whether a truncstore and extload is legal.
9098     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9099              TargetLowering::TypePromoteInteger) {
9100       EVT LegalizedStoredValueTy =
9101         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9102       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9103           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9104           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9105           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9106         LastLegalIntegerType = i+1;
9107     }
9108   }
9109
9110   // Only use vector types if the vector type is larger than the integer type.
9111   // If they are the same, use integers.
9112   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9113   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9114
9115   // We add +1 here because the LastXXX variables refer to location while
9116   // the NumElem refers to array/index size.
9117   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9118   NumElem = std::min(LastLegalType, NumElem);
9119
9120   if (NumElem < 2)
9121     return false;
9122
9123   // The earliest Node in the DAG.
9124   unsigned EarliestNodeUsed = 0;
9125   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9126   for (unsigned i=1; i<NumElem; ++i) {
9127     // Find a chain for the new wide-store operand. Notice that some
9128     // of the store nodes that we found may not be selected for inclusion
9129     // in the wide store. The chain we use needs to be the chain of the
9130     // earliest store node which is *used* and replaced by the wide store.
9131     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9132       EarliestNodeUsed = i;
9133   }
9134
9135   // Find if it is better to use vectors or integers to load and store
9136   // to memory.
9137   EVT JointMemOpVT;
9138   if (UseVectorTy) {
9139     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9140   } else {
9141     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9142     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9143   }
9144
9145   SDLoc LoadDL(LoadNodes[0].MemNode);
9146   SDLoc StoreDL(StoreNodes[0].MemNode);
9147
9148   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9149   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9150                                 FirstLoad->getChain(),
9151                                 FirstLoad->getBasePtr(),
9152                                 FirstLoad->getPointerInfo(),
9153                                 false, false, false,
9154                                 FirstLoad->getAlignment());
9155
9156   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9157                                   FirstInChain->getBasePtr(),
9158                                   FirstInChain->getPointerInfo(), false, false,
9159                                   FirstInChain->getAlignment());
9160
9161   // Replace one of the loads with the new load.
9162   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9163   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9164                                 SDValue(NewLoad.getNode(), 1));
9165
9166   // Remove the rest of the load chains.
9167   for (unsigned i = 1; i < NumElem ; ++i) {
9168     // Replace all chain users of the old load nodes with the chain of the new
9169     // load node.
9170     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9171     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9172   }
9173
9174   // Replace the first store with the new store.
9175   CombineTo(EarliestOp, NewStore);
9176   // Erase all other stores.
9177   for (unsigned i = 0; i < NumElem ; ++i) {
9178     // Remove all Store nodes.
9179     if (StoreNodes[i].MemNode == EarliestOp)
9180       continue;
9181     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9182     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9183     removeFromWorkList(St);
9184     DAG.DeleteNode(St);
9185   }
9186
9187   return true;
9188 }
9189
9190 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9191   StoreSDNode *ST  = cast<StoreSDNode>(N);
9192   SDValue Chain = ST->getChain();
9193   SDValue Value = ST->getValue();
9194   SDValue Ptr   = ST->getBasePtr();
9195
9196   // If this is a store of a bit convert, store the input value if the
9197   // resultant store does not need a higher alignment than the original.
9198   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9199       ST->isUnindexed()) {
9200     unsigned OrigAlign = ST->getAlignment();
9201     EVT SVT = Value.getOperand(0).getValueType();
9202     unsigned Align = TLI.getDataLayout()->
9203       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9204     if (Align <= OrigAlign &&
9205         ((!LegalOperations && !ST->isVolatile()) ||
9206          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9207       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9208                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9209                           ST->isNonTemporal(), OrigAlign,
9210                           ST->getTBAAInfo());
9211   }
9212
9213   // Turn 'store undef, Ptr' -> nothing.
9214   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9215     return Chain;
9216
9217   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9218   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9219     // NOTE: If the original store is volatile, this transform must not increase
9220     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9221     // processor operation but an i64 (which is not legal) requires two.  So the
9222     // transform should not be done in this case.
9223     if (Value.getOpcode() != ISD::TargetConstantFP) {
9224       SDValue Tmp;
9225       switch (CFP->getSimpleValueType(0).SimpleTy) {
9226       default: llvm_unreachable("Unknown FP type");
9227       case MVT::f16:    // We don't do this for these yet.
9228       case MVT::f80:
9229       case MVT::f128:
9230       case MVT::ppcf128:
9231         break;
9232       case MVT::f32:
9233         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9234             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9235           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9236                               bitcastToAPInt().getZExtValue(), MVT::i32);
9237           return DAG.getStore(Chain, SDLoc(N), Tmp,
9238                               Ptr, ST->getMemOperand());
9239         }
9240         break;
9241       case MVT::f64:
9242         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9243              !ST->isVolatile()) ||
9244             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9245           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9246                                 getZExtValue(), MVT::i64);
9247           return DAG.getStore(Chain, SDLoc(N), Tmp,
9248                               Ptr, ST->getMemOperand());
9249         }
9250
9251         if (!ST->isVolatile() &&
9252             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9253           // Many FP stores are not made apparent until after legalize, e.g. for
9254           // argument passing.  Since this is so common, custom legalize the
9255           // 64-bit integer store into two 32-bit stores.
9256           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9257           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9258           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9259           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9260
9261           unsigned Alignment = ST->getAlignment();
9262           bool isVolatile = ST->isVolatile();
9263           bool isNonTemporal = ST->isNonTemporal();
9264           const MDNode *TBAAInfo = ST->getTBAAInfo();
9265
9266           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9267                                      Ptr, ST->getPointerInfo(),
9268                                      isVolatile, isNonTemporal,
9269                                      ST->getAlignment(), TBAAInfo);
9270           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9271                             DAG.getConstant(4, Ptr.getValueType()));
9272           Alignment = MinAlign(Alignment, 4U);
9273           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9274                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9275                                      isVolatile, isNonTemporal,
9276                                      Alignment, TBAAInfo);
9277           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9278                              St0, St1);
9279         }
9280
9281         break;
9282       }
9283     }
9284   }
9285
9286   // Try to infer better alignment information than the store already has.
9287   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9288     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9289       if (Align > ST->getAlignment())
9290         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9291                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9292                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9293                                  ST->getTBAAInfo());
9294     }
9295   }
9296
9297   // Try transforming a pair floating point load / store ops to integer
9298   // load / store ops.
9299   SDValue NewST = TransformFPLoadStorePair(N);
9300   if (NewST.getNode())
9301     return NewST;
9302
9303   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9304     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9305   if (UseAA) {
9306     // Walk up chain skipping non-aliasing memory nodes.
9307     SDValue BetterChain = FindBetterChain(N, Chain);
9308
9309     // If there is a better chain.
9310     if (Chain != BetterChain) {
9311       SDValue ReplStore;
9312
9313       // Replace the chain to avoid dependency.
9314       if (ST->isTruncatingStore()) {
9315         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9316                                       ST->getMemoryVT(), ST->getMemOperand());
9317       } else {
9318         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9319                                  ST->getMemOperand());
9320       }
9321
9322       // Create token to keep both nodes around.
9323       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9324                                   MVT::Other, Chain, ReplStore);
9325
9326       // Make sure the new and old chains are cleaned up.
9327       AddToWorkList(Token.getNode());
9328
9329       // Don't add users to work list.
9330       return CombineTo(N, Token, false);
9331     }
9332   }
9333
9334   // Try transforming N to an indexed store.
9335   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9336     return SDValue(N, 0);
9337
9338   // FIXME: is there such a thing as a truncating indexed store?
9339   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9340       Value.getValueType().isInteger()) {
9341     // See if we can simplify the input to this truncstore with knowledge that
9342     // only the low bits are being used.  For example:
9343     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9344     SDValue Shorter =
9345       GetDemandedBits(Value,
9346                       APInt::getLowBitsSet(
9347                         Value.getValueType().getScalarType().getSizeInBits(),
9348                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9349     AddToWorkList(Value.getNode());
9350     if (Shorter.getNode())
9351       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9352                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9353
9354     // Otherwise, see if we can simplify the operation with
9355     // SimplifyDemandedBits, which only works if the value has a single use.
9356     if (SimplifyDemandedBits(Value,
9357                         APInt::getLowBitsSet(
9358                           Value.getValueType().getScalarType().getSizeInBits(),
9359                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9360       return SDValue(N, 0);
9361   }
9362
9363   // If this is a load followed by a store to the same location, then the store
9364   // is dead/noop.
9365   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9366     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9367         ST->isUnindexed() && !ST->isVolatile() &&
9368         // There can't be any side effects between the load and store, such as
9369         // a call or store.
9370         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9371       // The store is dead, remove it.
9372       return Chain;
9373     }
9374   }
9375
9376   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9377   // truncating store.  We can do this even if this is already a truncstore.
9378   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9379       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9380       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9381                             ST->getMemoryVT())) {
9382     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9383                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9384   }
9385
9386   // Only perform this optimization before the types are legal, because we
9387   // don't want to perform this optimization on every DAGCombine invocation.
9388   if (!LegalTypes) {
9389     bool EverChanged = false;
9390
9391     do {
9392       // There can be multiple store sequences on the same chain.
9393       // Keep trying to merge store sequences until we are unable to do so
9394       // or until we merge the last store on the chain.
9395       bool Changed = MergeConsecutiveStores(ST);
9396       EverChanged |= Changed;
9397       if (!Changed) break;
9398     } while (ST->getOpcode() != ISD::DELETED_NODE);
9399
9400     if (EverChanged)
9401       return SDValue(N, 0);
9402   }
9403
9404   return ReduceLoadOpStoreWidth(N);
9405 }
9406
9407 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9408   SDValue InVec = N->getOperand(0);
9409   SDValue InVal = N->getOperand(1);
9410   SDValue EltNo = N->getOperand(2);
9411   SDLoc dl(N);
9412
9413   // If the inserted element is an UNDEF, just use the input vector.
9414   if (InVal.getOpcode() == ISD::UNDEF)
9415     return InVec;
9416
9417   EVT VT = InVec.getValueType();
9418
9419   // If we can't generate a legal BUILD_VECTOR, exit
9420   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9421     return SDValue();
9422
9423   // Check that we know which element is being inserted
9424   if (!isa<ConstantSDNode>(EltNo))
9425     return SDValue();
9426   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9427
9428   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9429   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9430   // vector elements.
9431   SmallVector<SDValue, 8> Ops;
9432   // Do not combine these two vectors if the output vector will not replace
9433   // the input vector.
9434   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9435     Ops.append(InVec.getNode()->op_begin(),
9436                InVec.getNode()->op_end());
9437   } else if (InVec.getOpcode() == ISD::UNDEF) {
9438     unsigned NElts = VT.getVectorNumElements();
9439     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9440   } else {
9441     return SDValue();
9442   }
9443
9444   // Insert the element
9445   if (Elt < Ops.size()) {
9446     // All the operands of BUILD_VECTOR must have the same type;
9447     // we enforce that here.
9448     EVT OpVT = Ops[0].getValueType();
9449     if (InVal.getValueType() != OpVT)
9450       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9451                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9452                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9453     Ops[Elt] = InVal;
9454   }
9455
9456   // Return the new vector
9457   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9458                      VT, &Ops[0], Ops.size());
9459 }
9460
9461 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9462   // (vextract (scalar_to_vector val, 0) -> val
9463   SDValue InVec = N->getOperand(0);
9464   EVT VT = InVec.getValueType();
9465   EVT NVT = N->getValueType(0);
9466
9467   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9468     // Check if the result type doesn't match the inserted element type. A
9469     // SCALAR_TO_VECTOR may truncate the inserted element and the
9470     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9471     SDValue InOp = InVec.getOperand(0);
9472     if (InOp.getValueType() != NVT) {
9473       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9474       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9475     }
9476     return InOp;
9477   }
9478
9479   SDValue EltNo = N->getOperand(1);
9480   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9481
9482   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9483   // We only perform this optimization before the op legalization phase because
9484   // we may introduce new vector instructions which are not backed by TD
9485   // patterns. For example on AVX, extracting elements from a wide vector
9486   // without using extract_subvector.
9487   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9488       && ConstEltNo && !LegalOperations) {
9489     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9490     int NumElem = VT.getVectorNumElements();
9491     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9492     // Find the new index to extract from.
9493     int OrigElt = SVOp->getMaskElt(Elt);
9494
9495     // Extracting an undef index is undef.
9496     if (OrigElt == -1)
9497       return DAG.getUNDEF(NVT);
9498
9499     // Select the right vector half to extract from.
9500     if (OrigElt < NumElem) {
9501       InVec = InVec->getOperand(0);
9502     } else {
9503       InVec = InVec->getOperand(1);
9504       OrigElt -= NumElem;
9505     }
9506
9507     EVT IndexTy = TLI.getVectorIdxTy();
9508     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9509                        InVec, DAG.getConstant(OrigElt, IndexTy));
9510   }
9511
9512   // Perform only after legalization to ensure build_vector / vector_shuffle
9513   // optimizations have already been done.
9514   if (!LegalOperations) return SDValue();
9515
9516   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9517   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9518   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9519
9520   if (ConstEltNo) {
9521     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9522     bool NewLoad = false;
9523     bool BCNumEltsChanged = false;
9524     EVT ExtVT = VT.getVectorElementType();
9525     EVT LVT = ExtVT;
9526
9527     // If the result of load has to be truncated, then it's not necessarily
9528     // profitable.
9529     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9530       return SDValue();
9531
9532     if (InVec.getOpcode() == ISD::BITCAST) {
9533       // Don't duplicate a load with other uses.
9534       if (!InVec.hasOneUse())
9535         return SDValue();
9536
9537       EVT BCVT = InVec.getOperand(0).getValueType();
9538       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9539         return SDValue();
9540       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9541         BCNumEltsChanged = true;
9542       InVec = InVec.getOperand(0);
9543       ExtVT = BCVT.getVectorElementType();
9544       NewLoad = true;
9545     }
9546
9547     LoadSDNode *LN0 = NULL;
9548     const ShuffleVectorSDNode *SVN = NULL;
9549     if (ISD::isNormalLoad(InVec.getNode())) {
9550       LN0 = cast<LoadSDNode>(InVec);
9551     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9552                InVec.getOperand(0).getValueType() == ExtVT &&
9553                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9554       // Don't duplicate a load with other uses.
9555       if (!InVec.hasOneUse())
9556         return SDValue();
9557
9558       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9559     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9560       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9561       // =>
9562       // (load $addr+1*size)
9563
9564       // Don't duplicate a load with other uses.
9565       if (!InVec.hasOneUse())
9566         return SDValue();
9567
9568       // If the bit convert changed the number of elements, it is unsafe
9569       // to examine the mask.
9570       if (BCNumEltsChanged)
9571         return SDValue();
9572
9573       // Select the input vector, guarding against out of range extract vector.
9574       unsigned NumElems = VT.getVectorNumElements();
9575       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9576       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9577
9578       if (InVec.getOpcode() == ISD::BITCAST) {
9579         // Don't duplicate a load with other uses.
9580         if (!InVec.hasOneUse())
9581           return SDValue();
9582
9583         InVec = InVec.getOperand(0);
9584       }
9585       if (ISD::isNormalLoad(InVec.getNode())) {
9586         LN0 = cast<LoadSDNode>(InVec);
9587         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9588       }
9589     }
9590
9591     // Make sure we found a non-volatile load and the extractelement is
9592     // the only use.
9593     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9594       return SDValue();
9595
9596     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9597     if (Elt == -1)
9598       return DAG.getUNDEF(LVT);
9599
9600     unsigned Align = LN0->getAlignment();
9601     if (NewLoad) {
9602       // Check the resultant load doesn't need a higher alignment than the
9603       // original load.
9604       unsigned NewAlign =
9605         TLI.getDataLayout()
9606             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9607
9608       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9609         return SDValue();
9610
9611       Align = NewAlign;
9612     }
9613
9614     SDValue NewPtr = LN0->getBasePtr();
9615     unsigned PtrOff = 0;
9616
9617     if (Elt) {
9618       PtrOff = LVT.getSizeInBits() * Elt / 8;
9619       EVT PtrType = NewPtr.getValueType();
9620       if (TLI.isBigEndian())
9621         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9622       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9623                            DAG.getConstant(PtrOff, PtrType));
9624     }
9625
9626     // The replacement we need to do here is a little tricky: we need to
9627     // replace an extractelement of a load with a load.
9628     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9629     // Note that this replacement assumes that the extractvalue is the only
9630     // use of the load; that's okay because we don't want to perform this
9631     // transformation in other cases anyway.
9632     SDValue Load;
9633     SDValue Chain;
9634     if (NVT.bitsGT(LVT)) {
9635       // If the result type of vextract is wider than the load, then issue an
9636       // extending load instead.
9637       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9638         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9639       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9640                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9641                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9642                             Align, LN0->getTBAAInfo());
9643       Chain = Load.getValue(1);
9644     } else {
9645       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9646                          LN0->getPointerInfo().getWithOffset(PtrOff),
9647                          LN0->isVolatile(), LN0->isNonTemporal(),
9648                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9649       Chain = Load.getValue(1);
9650       if (NVT.bitsLT(LVT))
9651         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9652       else
9653         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9654     }
9655     WorkListRemover DeadNodes(*this);
9656     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9657     SDValue To[] = { Load, Chain };
9658     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9659     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9660     // worklist explicitly as well.
9661     AddToWorkList(Load.getNode());
9662     AddUsersToWorkList(Load.getNode()); // Add users too
9663     // Make sure to revisit this node to clean it up; it will usually be dead.
9664     AddToWorkList(N);
9665     return SDValue(N, 0);
9666   }
9667
9668   return SDValue();
9669 }
9670
9671 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9672 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9673   // We perform this optimization post type-legalization because
9674   // the type-legalizer often scalarizes integer-promoted vectors.
9675   // Performing this optimization before may create bit-casts which
9676   // will be type-legalized to complex code sequences.
9677   // We perform this optimization only before the operation legalizer because we
9678   // may introduce illegal operations.
9679   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9680     return SDValue();
9681
9682   unsigned NumInScalars = N->getNumOperands();
9683   SDLoc dl(N);
9684   EVT VT = N->getValueType(0);
9685
9686   // Check to see if this is a BUILD_VECTOR of a bunch of values
9687   // which come from any_extend or zero_extend nodes. If so, we can create
9688   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9689   // optimizations. We do not handle sign-extend because we can't fill the sign
9690   // using shuffles.
9691   EVT SourceType = MVT::Other;
9692   bool AllAnyExt = true;
9693
9694   for (unsigned i = 0; i != NumInScalars; ++i) {
9695     SDValue In = N->getOperand(i);
9696     // Ignore undef inputs.
9697     if (In.getOpcode() == ISD::UNDEF) continue;
9698
9699     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9700     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9701
9702     // Abort if the element is not an extension.
9703     if (!ZeroExt && !AnyExt) {
9704       SourceType = MVT::Other;
9705       break;
9706     }
9707
9708     // The input is a ZeroExt or AnyExt. Check the original type.
9709     EVT InTy = In.getOperand(0).getValueType();
9710
9711     // Check that all of the widened source types are the same.
9712     if (SourceType == MVT::Other)
9713       // First time.
9714       SourceType = InTy;
9715     else if (InTy != SourceType) {
9716       // Multiple income types. Abort.
9717       SourceType = MVT::Other;
9718       break;
9719     }
9720
9721     // Check if all of the extends are ANY_EXTENDs.
9722     AllAnyExt &= AnyExt;
9723   }
9724
9725   // In order to have valid types, all of the inputs must be extended from the
9726   // same source type and all of the inputs must be any or zero extend.
9727   // Scalar sizes must be a power of two.
9728   EVT OutScalarTy = VT.getScalarType();
9729   bool ValidTypes = SourceType != MVT::Other &&
9730                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9731                  isPowerOf2_32(SourceType.getSizeInBits());
9732
9733   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9734   // turn into a single shuffle instruction.
9735   if (!ValidTypes)
9736     return SDValue();
9737
9738   bool isLE = TLI.isLittleEndian();
9739   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9740   assert(ElemRatio > 1 && "Invalid element size ratio");
9741   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9742                                DAG.getConstant(0, SourceType);
9743
9744   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9745   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9746
9747   // Populate the new build_vector
9748   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9749     SDValue Cast = N->getOperand(i);
9750     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9751             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9752             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9753     SDValue In;
9754     if (Cast.getOpcode() == ISD::UNDEF)
9755       In = DAG.getUNDEF(SourceType);
9756     else
9757       In = Cast->getOperand(0);
9758     unsigned Index = isLE ? (i * ElemRatio) :
9759                             (i * ElemRatio + (ElemRatio - 1));
9760
9761     assert(Index < Ops.size() && "Invalid index");
9762     Ops[Index] = In;
9763   }
9764
9765   // The type of the new BUILD_VECTOR node.
9766   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9767   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9768          "Invalid vector size");
9769   // Check if the new vector type is legal.
9770   if (!isTypeLegal(VecVT)) return SDValue();
9771
9772   // Make the new BUILD_VECTOR.
9773   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9774
9775   // The new BUILD_VECTOR node has the potential to be further optimized.
9776   AddToWorkList(BV.getNode());
9777   // Bitcast to the desired type.
9778   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9779 }
9780
9781 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9782   EVT VT = N->getValueType(0);
9783
9784   unsigned NumInScalars = N->getNumOperands();
9785   SDLoc dl(N);
9786
9787   EVT SrcVT = MVT::Other;
9788   unsigned Opcode = ISD::DELETED_NODE;
9789   unsigned NumDefs = 0;
9790
9791   for (unsigned i = 0; i != NumInScalars; ++i) {
9792     SDValue In = N->getOperand(i);
9793     unsigned Opc = In.getOpcode();
9794
9795     if (Opc == ISD::UNDEF)
9796       continue;
9797
9798     // If all scalar values are floats and converted from integers.
9799     if (Opcode == ISD::DELETED_NODE &&
9800         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9801       Opcode = Opc;
9802     }
9803
9804     if (Opc != Opcode)
9805       return SDValue();
9806
9807     EVT InVT = In.getOperand(0).getValueType();
9808
9809     // If all scalar values are typed differently, bail out. It's chosen to
9810     // simplify BUILD_VECTOR of integer types.
9811     if (SrcVT == MVT::Other)
9812       SrcVT = InVT;
9813     if (SrcVT != InVT)
9814       return SDValue();
9815     NumDefs++;
9816   }
9817
9818   // If the vector has just one element defined, it's not worth to fold it into
9819   // a vectorized one.
9820   if (NumDefs < 2)
9821     return SDValue();
9822
9823   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9824          && "Should only handle conversion from integer to float.");
9825   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9826
9827   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9828
9829   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9830     return SDValue();
9831
9832   SmallVector<SDValue, 8> Opnds;
9833   for (unsigned i = 0; i != NumInScalars; ++i) {
9834     SDValue In = N->getOperand(i);
9835
9836     if (In.getOpcode() == ISD::UNDEF)
9837       Opnds.push_back(DAG.getUNDEF(SrcVT));
9838     else
9839       Opnds.push_back(In.getOperand(0));
9840   }
9841   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9842                            &Opnds[0], Opnds.size());
9843   AddToWorkList(BV.getNode());
9844
9845   return DAG.getNode(Opcode, dl, VT, BV);
9846 }
9847
9848 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9849   unsigned NumInScalars = N->getNumOperands();
9850   SDLoc dl(N);
9851   EVT VT = N->getValueType(0);
9852
9853   // A vector built entirely of undefs is undef.
9854   if (ISD::allOperandsUndef(N))
9855     return DAG.getUNDEF(VT);
9856
9857   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9858   if (V.getNode())
9859     return V;
9860
9861   V = reduceBuildVecConvertToConvertBuildVec(N);
9862   if (V.getNode())
9863     return V;
9864
9865   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9866   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9867   // at most two distinct vectors, turn this into a shuffle node.
9868
9869   // May only combine to shuffle after legalize if shuffle is legal.
9870   if (LegalOperations &&
9871       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9872     return SDValue();
9873
9874   SDValue VecIn1, VecIn2;
9875   for (unsigned i = 0; i != NumInScalars; ++i) {
9876     // Ignore undef inputs.
9877     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9878
9879     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9880     // constant index, bail out.
9881     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9882         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9883       VecIn1 = VecIn2 = SDValue(0, 0);
9884       break;
9885     }
9886
9887     // We allow up to two distinct input vectors.
9888     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9889     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9890       continue;
9891
9892     if (VecIn1.getNode() == 0) {
9893       VecIn1 = ExtractedFromVec;
9894     } else if (VecIn2.getNode() == 0) {
9895       VecIn2 = ExtractedFromVec;
9896     } else {
9897       // Too many inputs.
9898       VecIn1 = VecIn2 = SDValue(0, 0);
9899       break;
9900     }
9901   }
9902
9903     // If everything is good, we can make a shuffle operation.
9904   if (VecIn1.getNode()) {
9905     SmallVector<int, 8> Mask;
9906     for (unsigned i = 0; i != NumInScalars; ++i) {
9907       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9908         Mask.push_back(-1);
9909         continue;
9910       }
9911
9912       // If extracting from the first vector, just use the index directly.
9913       SDValue Extract = N->getOperand(i);
9914       SDValue ExtVal = Extract.getOperand(1);
9915       if (Extract.getOperand(0) == VecIn1) {
9916         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9917         if (ExtIndex > VT.getVectorNumElements())
9918           return SDValue();
9919
9920         Mask.push_back(ExtIndex);
9921         continue;
9922       }
9923
9924       // Otherwise, use InIdx + VecSize
9925       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9926       Mask.push_back(Idx+NumInScalars);
9927     }
9928
9929     // We can't generate a shuffle node with mismatched input and output types.
9930     // Attempt to transform a single input vector to the correct type.
9931     if ((VT != VecIn1.getValueType())) {
9932       // We don't support shuffeling between TWO values of different types.
9933       if (VecIn2.getNode() != 0)
9934         return SDValue();
9935
9936       // We only support widening of vectors which are half the size of the
9937       // output registers. For example XMM->YMM widening on X86 with AVX.
9938       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9939         return SDValue();
9940
9941       // If the input vector type has a different base type to the output
9942       // vector type, bail out.
9943       if (VecIn1.getValueType().getVectorElementType() !=
9944           VT.getVectorElementType())
9945         return SDValue();
9946
9947       // Widen the input vector by adding undef values.
9948       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9949                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9950     }
9951
9952     // If VecIn2 is unused then change it to undef.
9953     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9954
9955     // Check that we were able to transform all incoming values to the same
9956     // type.
9957     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9958         VecIn1.getValueType() != VT)
9959           return SDValue();
9960
9961     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9962     if (!isTypeLegal(VT))
9963       return SDValue();
9964
9965     // Return the new VECTOR_SHUFFLE node.
9966     SDValue Ops[2];
9967     Ops[0] = VecIn1;
9968     Ops[1] = VecIn2;
9969     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9970   }
9971
9972   return SDValue();
9973 }
9974
9975 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9976   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9977   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9978   // inputs come from at most two distinct vectors, turn this into a shuffle
9979   // node.
9980
9981   // If we only have one input vector, we don't need to do any concatenation.
9982   if (N->getNumOperands() == 1)
9983     return N->getOperand(0);
9984
9985   // Check if all of the operands are undefs.
9986   EVT VT = N->getValueType(0);
9987   if (ISD::allOperandsUndef(N))
9988     return DAG.getUNDEF(VT);
9989
9990   // Optimize concat_vectors where one of the vectors is undef.
9991   if (N->getNumOperands() == 2 &&
9992       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9993     SDValue In = N->getOperand(0);
9994     assert(In.getValueType().isVector() && "Must concat vectors");
9995
9996     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9997     if (In->getOpcode() == ISD::BITCAST &&
9998         !In->getOperand(0)->getValueType(0).isVector()) {
9999       SDValue Scalar = In->getOperand(0);
10000       EVT SclTy = Scalar->getValueType(0);
10001
10002       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10003         return SDValue();
10004
10005       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10006                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10007       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10008         return SDValue();
10009
10010       SDLoc dl = SDLoc(N);
10011       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10012       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10013     }
10014   }
10015
10016   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10017   // nodes often generate nop CONCAT_VECTOR nodes.
10018   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10019   // place the incoming vectors at the exact same location.
10020   SDValue SingleSource = SDValue();
10021   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10022
10023   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10024     SDValue Op = N->getOperand(i);
10025
10026     if (Op.getOpcode() == ISD::UNDEF)
10027       continue;
10028
10029     // Check if this is the identity extract:
10030     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10031       return SDValue();
10032
10033     // Find the single incoming vector for the extract_subvector.
10034     if (SingleSource.getNode()) {
10035       if (Op.getOperand(0) != SingleSource)
10036         return SDValue();
10037     } else {
10038       SingleSource = Op.getOperand(0);
10039
10040       // Check the source type is the same as the type of the result.
10041       // If not, this concat may extend the vector, so we can not
10042       // optimize it away.
10043       if (SingleSource.getValueType() != N->getValueType(0))
10044         return SDValue();
10045     }
10046
10047     unsigned IdentityIndex = i * PartNumElem;
10048     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10049     // The extract index must be constant.
10050     if (!CS)
10051       return SDValue();
10052
10053     // Check that we are reading from the identity index.
10054     if (CS->getZExtValue() != IdentityIndex)
10055       return SDValue();
10056   }
10057
10058   if (SingleSource.getNode())
10059     return SingleSource;
10060
10061   return SDValue();
10062 }
10063
10064 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10065   EVT NVT = N->getValueType(0);
10066   SDValue V = N->getOperand(0);
10067
10068   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10069     // Combine:
10070     //    (extract_subvec (concat V1, V2, ...), i)
10071     // Into:
10072     //    Vi if possible
10073     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10074     // type.
10075     if (V->getOperand(0).getValueType() != NVT)
10076       return SDValue();
10077     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10078     unsigned NumElems = NVT.getVectorNumElements();
10079     assert((Idx % NumElems) == 0 &&
10080            "IDX in concat is not a multiple of the result vector length.");
10081     return V->getOperand(Idx / NumElems);
10082   }
10083
10084   // Skip bitcasting
10085   if (V->getOpcode() == ISD::BITCAST)
10086     V = V.getOperand(0);
10087
10088   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10089     SDLoc dl(N);
10090     // Handle only simple case where vector being inserted and vector
10091     // being extracted are of same type, and are half size of larger vectors.
10092     EVT BigVT = V->getOperand(0).getValueType();
10093     EVT SmallVT = V->getOperand(1).getValueType();
10094     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10095       return SDValue();
10096
10097     // Only handle cases where both indexes are constants with the same type.
10098     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10099     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10100
10101     if (InsIdx && ExtIdx &&
10102         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10103         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10104       // Combine:
10105       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10106       // Into:
10107       //    indices are equal or bit offsets are equal => V1
10108       //    otherwise => (extract_subvec V1, ExtIdx)
10109       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10110           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10111         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10112       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10113                          DAG.getNode(ISD::BITCAST, dl,
10114                                      N->getOperand(0).getValueType(),
10115                                      V->getOperand(0)), N->getOperand(1));
10116     }
10117   }
10118
10119   return SDValue();
10120 }
10121
10122 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10123 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10124   EVT VT = N->getValueType(0);
10125   unsigned NumElts = VT.getVectorNumElements();
10126
10127   SDValue N0 = N->getOperand(0);
10128   SDValue N1 = N->getOperand(1);
10129   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10130
10131   SmallVector<SDValue, 4> Ops;
10132   EVT ConcatVT = N0.getOperand(0).getValueType();
10133   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10134   unsigned NumConcats = NumElts / NumElemsPerConcat;
10135
10136   // Look at every vector that's inserted. We're looking for exact
10137   // subvector-sized copies from a concatenated vector
10138   for (unsigned I = 0; I != NumConcats; ++I) {
10139     // Make sure we're dealing with a copy.
10140     unsigned Begin = I * NumElemsPerConcat;
10141     bool AllUndef = true, NoUndef = true;
10142     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10143       if (SVN->getMaskElt(J) >= 0)
10144         AllUndef = false;
10145       else
10146         NoUndef = false;
10147     }
10148
10149     if (NoUndef) {
10150       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10151         return SDValue();
10152
10153       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10154         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10155           return SDValue();
10156
10157       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10158       if (FirstElt < N0.getNumOperands())
10159         Ops.push_back(N0.getOperand(FirstElt));
10160       else
10161         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10162
10163     } else if (AllUndef) {
10164       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10165     } else { // Mixed with general masks and undefs, can't do optimization.
10166       return SDValue();
10167     }
10168   }
10169
10170   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10171                      Ops.size());
10172 }
10173
10174 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10175   EVT VT = N->getValueType(0);
10176   unsigned NumElts = VT.getVectorNumElements();
10177
10178   SDValue N0 = N->getOperand(0);
10179   SDValue N1 = N->getOperand(1);
10180
10181   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10182
10183   // Canonicalize shuffle undef, undef -> undef
10184   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10185     return DAG.getUNDEF(VT);
10186
10187   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10188
10189   // Canonicalize shuffle v, v -> v, undef
10190   if (N0 == N1) {
10191     SmallVector<int, 8> NewMask;
10192     for (unsigned i = 0; i != NumElts; ++i) {
10193       int Idx = SVN->getMaskElt(i);
10194       if (Idx >= (int)NumElts) Idx -= NumElts;
10195       NewMask.push_back(Idx);
10196     }
10197     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10198                                 &NewMask[0]);
10199   }
10200
10201   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10202   if (N0.getOpcode() == ISD::UNDEF) {
10203     SmallVector<int, 8> NewMask;
10204     for (unsigned i = 0; i != NumElts; ++i) {
10205       int Idx = SVN->getMaskElt(i);
10206       if (Idx >= 0) {
10207         if (Idx >= (int)NumElts)
10208           Idx -= NumElts;
10209         else
10210           Idx = -1; // remove reference to lhs
10211       }
10212       NewMask.push_back(Idx);
10213     }
10214     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10215                                 &NewMask[0]);
10216   }
10217
10218   // Remove references to rhs if it is undef
10219   if (N1.getOpcode() == ISD::UNDEF) {
10220     bool Changed = false;
10221     SmallVector<int, 8> NewMask;
10222     for (unsigned i = 0; i != NumElts; ++i) {
10223       int Idx = SVN->getMaskElt(i);
10224       if (Idx >= (int)NumElts) {
10225         Idx = -1;
10226         Changed = true;
10227       }
10228       NewMask.push_back(Idx);
10229     }
10230     if (Changed)
10231       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10232   }
10233
10234   // If it is a splat, check if the argument vector is another splat or a
10235   // build_vector with all scalar elements the same.
10236   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10237     SDNode *V = N0.getNode();
10238
10239     // If this is a bit convert that changes the element type of the vector but
10240     // not the number of vector elements, look through it.  Be careful not to
10241     // look though conversions that change things like v4f32 to v2f64.
10242     if (V->getOpcode() == ISD::BITCAST) {
10243       SDValue ConvInput = V->getOperand(0);
10244       if (ConvInput.getValueType().isVector() &&
10245           ConvInput.getValueType().getVectorNumElements() == NumElts)
10246         V = ConvInput.getNode();
10247     }
10248
10249     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10250       assert(V->getNumOperands() == NumElts &&
10251              "BUILD_VECTOR has wrong number of operands");
10252       SDValue Base;
10253       bool AllSame = true;
10254       for (unsigned i = 0; i != NumElts; ++i) {
10255         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10256           Base = V->getOperand(i);
10257           break;
10258         }
10259       }
10260       // Splat of <u, u, u, u>, return <u, u, u, u>
10261       if (!Base.getNode())
10262         return N0;
10263       for (unsigned i = 0; i != NumElts; ++i) {
10264         if (V->getOperand(i) != Base) {
10265           AllSame = false;
10266           break;
10267         }
10268       }
10269       // Splat of <x, x, x, x>, return <x, x, x, x>
10270       if (AllSame)
10271         return N0;
10272     }
10273   }
10274
10275   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10276       Level < AfterLegalizeVectorOps &&
10277       (N1.getOpcode() == ISD::UNDEF ||
10278       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10279        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10280     SDValue V = partitionShuffleOfConcats(N, DAG);
10281
10282     if (V.getNode())
10283       return V;
10284   }
10285
10286   // If this shuffle node is simply a swizzle of another shuffle node,
10287   // and it reverses the swizzle of the previous shuffle then we can
10288   // optimize shuffle(shuffle(x, undef), undef) -> x.
10289   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10290       N1.getOpcode() == ISD::UNDEF) {
10291
10292     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10293
10294     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10295     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10296       return SDValue();
10297
10298     // The incoming shuffle must be of the same type as the result of the
10299     // current shuffle.
10300     assert(OtherSV->getOperand(0).getValueType() == VT &&
10301            "Shuffle types don't match");
10302
10303     for (unsigned i = 0; i != NumElts; ++i) {
10304       int Idx = SVN->getMaskElt(i);
10305       assert(Idx < (int)NumElts && "Index references undef operand");
10306       // Next, this index comes from the first value, which is the incoming
10307       // shuffle. Adopt the incoming index.
10308       if (Idx >= 0)
10309         Idx = OtherSV->getMaskElt(Idx);
10310
10311       // The combined shuffle must map each index to itself.
10312       if (Idx >= 0 && (unsigned)Idx != i)
10313         return SDValue();
10314     }
10315
10316     return OtherSV->getOperand(0);
10317   }
10318
10319   return SDValue();
10320 }
10321
10322 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10323 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10324 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10325 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10326 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10327   EVT VT = N->getValueType(0);
10328   SDLoc dl(N);
10329   SDValue LHS = N->getOperand(0);
10330   SDValue RHS = N->getOperand(1);
10331   if (N->getOpcode() == ISD::AND) {
10332     if (RHS.getOpcode() == ISD::BITCAST)
10333       RHS = RHS.getOperand(0);
10334     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10335       SmallVector<int, 8> Indices;
10336       unsigned NumElts = RHS.getNumOperands();
10337       for (unsigned i = 0; i != NumElts; ++i) {
10338         SDValue Elt = RHS.getOperand(i);
10339         if (!isa<ConstantSDNode>(Elt))
10340           return SDValue();
10341
10342         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10343           Indices.push_back(i);
10344         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10345           Indices.push_back(NumElts);
10346         else
10347           return SDValue();
10348       }
10349
10350       // Let's see if the target supports this vector_shuffle.
10351       EVT RVT = RHS.getValueType();
10352       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10353         return SDValue();
10354
10355       // Return the new VECTOR_SHUFFLE node.
10356       EVT EltVT = RVT.getVectorElementType();
10357       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10358                                      DAG.getConstant(0, EltVT));
10359       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10360                                  RVT, &ZeroOps[0], ZeroOps.size());
10361       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10362       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10363       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10364     }
10365   }
10366
10367   return SDValue();
10368 }
10369
10370 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10371 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10372   assert(N->getValueType(0).isVector() &&
10373          "SimplifyVBinOp only works on vectors!");
10374
10375   SDValue LHS = N->getOperand(0);
10376   SDValue RHS = N->getOperand(1);
10377   SDValue Shuffle = XformToShuffleWithZero(N);
10378   if (Shuffle.getNode()) return Shuffle;
10379
10380   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10381   // this operation.
10382   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10383       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10384     SmallVector<SDValue, 8> Ops;
10385     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10386       SDValue LHSOp = LHS.getOperand(i);
10387       SDValue RHSOp = RHS.getOperand(i);
10388       // If these two elements can't be folded, bail out.
10389       if ((LHSOp.getOpcode() != ISD::UNDEF &&
10390            LHSOp.getOpcode() != ISD::Constant &&
10391            LHSOp.getOpcode() != ISD::ConstantFP) ||
10392           (RHSOp.getOpcode() != ISD::UNDEF &&
10393            RHSOp.getOpcode() != ISD::Constant &&
10394            RHSOp.getOpcode() != ISD::ConstantFP))
10395         break;
10396
10397       // Can't fold divide by zero.
10398       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10399           N->getOpcode() == ISD::FDIV) {
10400         if ((RHSOp.getOpcode() == ISD::Constant &&
10401              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10402             (RHSOp.getOpcode() == ISD::ConstantFP &&
10403              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10404           break;
10405       }
10406
10407       EVT VT = LHSOp.getValueType();
10408       EVT RVT = RHSOp.getValueType();
10409       if (RVT != VT) {
10410         // Integer BUILD_VECTOR operands may have types larger than the element
10411         // size (e.g., when the element type is not legal).  Prior to type
10412         // legalization, the types may not match between the two BUILD_VECTORS.
10413         // Truncate one of the operands to make them match.
10414         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10415           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10416         } else {
10417           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10418           VT = RVT;
10419         }
10420       }
10421       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10422                                    LHSOp, RHSOp);
10423       if (FoldOp.getOpcode() != ISD::UNDEF &&
10424           FoldOp.getOpcode() != ISD::Constant &&
10425           FoldOp.getOpcode() != ISD::ConstantFP)
10426         break;
10427       Ops.push_back(FoldOp);
10428       AddToWorkList(FoldOp.getNode());
10429     }
10430
10431     if (Ops.size() == LHS.getNumOperands())
10432       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10433                          LHS.getValueType(), &Ops[0], Ops.size());
10434   }
10435
10436   return SDValue();
10437 }
10438
10439 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10440 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10441   assert(N->getValueType(0).isVector() &&
10442          "SimplifyVUnaryOp only works on vectors!");
10443
10444   SDValue N0 = N->getOperand(0);
10445
10446   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10447     return SDValue();
10448
10449   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10450   SmallVector<SDValue, 8> Ops;
10451   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10452     SDValue Op = N0.getOperand(i);
10453     if (Op.getOpcode() != ISD::UNDEF &&
10454         Op.getOpcode() != ISD::ConstantFP)
10455       break;
10456     EVT EltVT = Op.getValueType();
10457     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10458     if (FoldOp.getOpcode() != ISD::UNDEF &&
10459         FoldOp.getOpcode() != ISD::ConstantFP)
10460       break;
10461     Ops.push_back(FoldOp);
10462     AddToWorkList(FoldOp.getNode());
10463   }
10464
10465   if (Ops.size() != N0.getNumOperands())
10466     return SDValue();
10467
10468   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10469                      N0.getValueType(), &Ops[0], Ops.size());
10470 }
10471
10472 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10473                                     SDValue N1, SDValue N2){
10474   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10475
10476   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10477                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10478
10479   // If we got a simplified select_cc node back from SimplifySelectCC, then
10480   // break it down into a new SETCC node, and a new SELECT node, and then return
10481   // the SELECT node, since we were called with a SELECT node.
10482   if (SCC.getNode()) {
10483     // Check to see if we got a select_cc back (to turn into setcc/select).
10484     // Otherwise, just return whatever node we got back, like fabs.
10485     if (SCC.getOpcode() == ISD::SELECT_CC) {
10486       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10487                                   N0.getValueType(),
10488                                   SCC.getOperand(0), SCC.getOperand(1),
10489                                   SCC.getOperand(4));
10490       AddToWorkList(SETCC.getNode());
10491       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10492                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10493     }
10494
10495     return SCC;
10496   }
10497   return SDValue();
10498 }
10499
10500 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10501 /// are the two values being selected between, see if we can simplify the
10502 /// select.  Callers of this should assume that TheSelect is deleted if this
10503 /// returns true.  As such, they should return the appropriate thing (e.g. the
10504 /// node) back to the top-level of the DAG combiner loop to avoid it being
10505 /// looked at.
10506 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10507                                     SDValue RHS) {
10508
10509   // Cannot simplify select with vector condition
10510   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10511
10512   // If this is a select from two identical things, try to pull the operation
10513   // through the select.
10514   if (LHS.getOpcode() != RHS.getOpcode() ||
10515       !LHS.hasOneUse() || !RHS.hasOneUse())
10516     return false;
10517
10518   // If this is a load and the token chain is identical, replace the select
10519   // of two loads with a load through a select of the address to load from.
10520   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10521   // constants have been dropped into the constant pool.
10522   if (LHS.getOpcode() == ISD::LOAD) {
10523     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10524     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10525
10526     // Token chains must be identical.
10527     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10528         // Do not let this transformation reduce the number of volatile loads.
10529         LLD->isVolatile() || RLD->isVolatile() ||
10530         // If this is an EXTLOAD, the VT's must match.
10531         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10532         // If this is an EXTLOAD, the kind of extension must match.
10533         (LLD->getExtensionType() != RLD->getExtensionType() &&
10534          // The only exception is if one of the extensions is anyext.
10535          LLD->getExtensionType() != ISD::EXTLOAD &&
10536          RLD->getExtensionType() != ISD::EXTLOAD) ||
10537         // FIXME: this discards src value information.  This is
10538         // over-conservative. It would be beneficial to be able to remember
10539         // both potential memory locations.  Since we are discarding
10540         // src value info, don't do the transformation if the memory
10541         // locations are not in the default address space.
10542         LLD->getPointerInfo().getAddrSpace() != 0 ||
10543         RLD->getPointerInfo().getAddrSpace() != 0 ||
10544         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10545                                       LLD->getBasePtr().getValueType()))
10546       return false;
10547
10548     // Check that the select condition doesn't reach either load.  If so,
10549     // folding this will induce a cycle into the DAG.  If not, this is safe to
10550     // xform, so create a select of the addresses.
10551     SDValue Addr;
10552     if (TheSelect->getOpcode() == ISD::SELECT) {
10553       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10554       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10555           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10556         return false;
10557       // The loads must not depend on one another.
10558       if (LLD->isPredecessorOf(RLD) ||
10559           RLD->isPredecessorOf(LLD))
10560         return false;
10561       Addr = DAG.getSelect(SDLoc(TheSelect),
10562                            LLD->getBasePtr().getValueType(),
10563                            TheSelect->getOperand(0), LLD->getBasePtr(),
10564                            RLD->getBasePtr());
10565     } else {  // Otherwise SELECT_CC
10566       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10567       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10568
10569       if ((LLD->hasAnyUseOfValue(1) &&
10570            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10571           (RLD->hasAnyUseOfValue(1) &&
10572            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10573         return false;
10574
10575       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10576                          LLD->getBasePtr().getValueType(),
10577                          TheSelect->getOperand(0),
10578                          TheSelect->getOperand(1),
10579                          LLD->getBasePtr(), RLD->getBasePtr(),
10580                          TheSelect->getOperand(4));
10581     }
10582
10583     SDValue Load;
10584     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10585       Load = DAG.getLoad(TheSelect->getValueType(0),
10586                          SDLoc(TheSelect),
10587                          // FIXME: Discards pointer and TBAA info.
10588                          LLD->getChain(), Addr, MachinePointerInfo(),
10589                          LLD->isVolatile(), LLD->isNonTemporal(),
10590                          LLD->isInvariant(), LLD->getAlignment());
10591     } else {
10592       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10593                             RLD->getExtensionType() : LLD->getExtensionType(),
10594                             SDLoc(TheSelect),
10595                             TheSelect->getValueType(0),
10596                             // FIXME: Discards pointer and TBAA info.
10597                             LLD->getChain(), Addr, MachinePointerInfo(),
10598                             LLD->getMemoryVT(), LLD->isVolatile(),
10599                             LLD->isNonTemporal(), LLD->getAlignment());
10600     }
10601
10602     // Users of the select now use the result of the load.
10603     CombineTo(TheSelect, Load);
10604
10605     // Users of the old loads now use the new load's chain.  We know the
10606     // old-load value is dead now.
10607     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10608     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10609     return true;
10610   }
10611
10612   return false;
10613 }
10614
10615 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10616 /// where 'cond' is the comparison specified by CC.
10617 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10618                                       SDValue N2, SDValue N3,
10619                                       ISD::CondCode CC, bool NotExtCompare) {
10620   // (x ? y : y) -> y.
10621   if (N2 == N3) return N2;
10622
10623   EVT VT = N2.getValueType();
10624   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10625   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10626   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10627
10628   // Determine if the condition we're dealing with is constant
10629   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10630                               N0, N1, CC, DL, false);
10631   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10632   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10633
10634   // fold select_cc true, x, y -> x
10635   if (SCCC && !SCCC->isNullValue())
10636     return N2;
10637   // fold select_cc false, x, y -> y
10638   if (SCCC && SCCC->isNullValue())
10639     return N3;
10640
10641   // Check to see if we can simplify the select into an fabs node
10642   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10643     // Allow either -0.0 or 0.0
10644     if (CFP->getValueAPF().isZero()) {
10645       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10646       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10647           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10648           N2 == N3.getOperand(0))
10649         return DAG.getNode(ISD::FABS, DL, VT, N0);
10650
10651       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10652       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10653           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10654           N2.getOperand(0) == N3)
10655         return DAG.getNode(ISD::FABS, DL, VT, N3);
10656     }
10657   }
10658
10659   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10660   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10661   // in it.  This is a win when the constant is not otherwise available because
10662   // it replaces two constant pool loads with one.  We only do this if the FP
10663   // type is known to be legal, because if it isn't, then we are before legalize
10664   // types an we want the other legalization to happen first (e.g. to avoid
10665   // messing with soft float) and if the ConstantFP is not legal, because if
10666   // it is legal, we may not need to store the FP constant in a constant pool.
10667   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10668     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10669       if (TLI.isTypeLegal(N2.getValueType()) &&
10670           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10671            TargetLowering::Legal) &&
10672           // If both constants have multiple uses, then we won't need to do an
10673           // extra load, they are likely around in registers for other users.
10674           (TV->hasOneUse() || FV->hasOneUse())) {
10675         Constant *Elts[] = {
10676           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10677           const_cast<ConstantFP*>(TV->getConstantFPValue())
10678         };
10679         Type *FPTy = Elts[0]->getType();
10680         const DataLayout &TD = *TLI.getDataLayout();
10681
10682         // Create a ConstantArray of the two constants.
10683         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10684         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10685                                             TD.getPrefTypeAlignment(FPTy));
10686         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10687
10688         // Get the offsets to the 0 and 1 element of the array so that we can
10689         // select between them.
10690         SDValue Zero = DAG.getIntPtrConstant(0);
10691         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10692         SDValue One = DAG.getIntPtrConstant(EltSize);
10693
10694         SDValue Cond = DAG.getSetCC(DL,
10695                                     getSetCCResultType(N0.getValueType()),
10696                                     N0, N1, CC);
10697         AddToWorkList(Cond.getNode());
10698         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10699                                           Cond, One, Zero);
10700         AddToWorkList(CstOffset.getNode());
10701         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10702                             CstOffset);
10703         AddToWorkList(CPIdx.getNode());
10704         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10705                            MachinePointerInfo::getConstantPool(), false,
10706                            false, false, Alignment);
10707
10708       }
10709     }
10710
10711   // Check to see if we can perform the "gzip trick", transforming
10712   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10713   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10714       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10715        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10716     EVT XType = N0.getValueType();
10717     EVT AType = N2.getValueType();
10718     if (XType.bitsGE(AType)) {
10719       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10720       // single-bit constant.
10721       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10722         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10723         ShCtV = XType.getSizeInBits()-ShCtV-1;
10724         SDValue ShCt = DAG.getConstant(ShCtV,
10725                                        getShiftAmountTy(N0.getValueType()));
10726         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10727                                     XType, N0, ShCt);
10728         AddToWorkList(Shift.getNode());
10729
10730         if (XType.bitsGT(AType)) {
10731           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10732           AddToWorkList(Shift.getNode());
10733         }
10734
10735         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10736       }
10737
10738       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10739                                   XType, N0,
10740                                   DAG.getConstant(XType.getSizeInBits()-1,
10741                                          getShiftAmountTy(N0.getValueType())));
10742       AddToWorkList(Shift.getNode());
10743
10744       if (XType.bitsGT(AType)) {
10745         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10746         AddToWorkList(Shift.getNode());
10747       }
10748
10749       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10750     }
10751   }
10752
10753   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10754   // where y is has a single bit set.
10755   // A plaintext description would be, we can turn the SELECT_CC into an AND
10756   // when the condition can be materialized as an all-ones register.  Any
10757   // single bit-test can be materialized as an all-ones register with
10758   // shift-left and shift-right-arith.
10759   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10760       N0->getValueType(0) == VT &&
10761       N1C && N1C->isNullValue() &&
10762       N2C && N2C->isNullValue()) {
10763     SDValue AndLHS = N0->getOperand(0);
10764     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10765     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10766       // Shift the tested bit over the sign bit.
10767       APInt AndMask = ConstAndRHS->getAPIntValue();
10768       SDValue ShlAmt =
10769         DAG.getConstant(AndMask.countLeadingZeros(),
10770                         getShiftAmountTy(AndLHS.getValueType()));
10771       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10772
10773       // Now arithmetic right shift it all the way over, so the result is either
10774       // all-ones, or zero.
10775       SDValue ShrAmt =
10776         DAG.getConstant(AndMask.getBitWidth()-1,
10777                         getShiftAmountTy(Shl.getValueType()));
10778       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10779
10780       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10781     }
10782   }
10783
10784   // fold select C, 16, 0 -> shl C, 4
10785   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10786     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10787       TargetLowering::ZeroOrOneBooleanContent) {
10788
10789     // If the caller doesn't want us to simplify this into a zext of a compare,
10790     // don't do it.
10791     if (NotExtCompare && N2C->getAPIntValue() == 1)
10792       return SDValue();
10793
10794     // Get a SetCC of the condition
10795     // NOTE: Don't create a SETCC if it's not legal on this target.
10796     if (!LegalOperations ||
10797         TLI.isOperationLegal(ISD::SETCC,
10798           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10799       SDValue Temp, SCC;
10800       // cast from setcc result type to select result type
10801       if (LegalTypes) {
10802         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10803                             N0, N1, CC);
10804         if (N2.getValueType().bitsLT(SCC.getValueType()))
10805           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10806                                         N2.getValueType());
10807         else
10808           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10809                              N2.getValueType(), SCC);
10810       } else {
10811         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10812         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10813                            N2.getValueType(), SCC);
10814       }
10815
10816       AddToWorkList(SCC.getNode());
10817       AddToWorkList(Temp.getNode());
10818
10819       if (N2C->getAPIntValue() == 1)
10820         return Temp;
10821
10822       // shl setcc result by log2 n2c
10823       return DAG.getNode(
10824           ISD::SHL, DL, N2.getValueType(), Temp,
10825           DAG.getConstant(N2C->getAPIntValue().logBase2(),
10826                           getShiftAmountTy(Temp.getValueType())));
10827     }
10828   }
10829
10830   // Check to see if this is the equivalent of setcc
10831   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10832   // otherwise, go ahead with the folds.
10833   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10834     EVT XType = N0.getValueType();
10835     if (!LegalOperations ||
10836         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10837       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10838       if (Res.getValueType() != VT)
10839         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10840       return Res;
10841     }
10842
10843     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10844     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10845         (!LegalOperations ||
10846          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10847       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10848       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10849                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10850                                        getShiftAmountTy(Ctlz.getValueType())));
10851     }
10852     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10853     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10854       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10855                                   XType, DAG.getConstant(0, XType), N0);
10856       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10857       return DAG.getNode(ISD::SRL, DL, XType,
10858                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10859                          DAG.getConstant(XType.getSizeInBits()-1,
10860                                          getShiftAmountTy(XType)));
10861     }
10862     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10863     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10864       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10865                                  DAG.getConstant(XType.getSizeInBits()-1,
10866                                          getShiftAmountTy(N0.getValueType())));
10867       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10868     }
10869   }
10870
10871   // Check to see if this is an integer abs.
10872   // select_cc setg[te] X,  0,  X, -X ->
10873   // select_cc setgt    X, -1,  X, -X ->
10874   // select_cc setl[te] X,  0, -X,  X ->
10875   // select_cc setlt    X,  1, -X,  X ->
10876   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10877   if (N1C) {
10878     ConstantSDNode *SubC = NULL;
10879     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10880          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10881         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10882       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10883     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10884               (N1C->isOne() && CC == ISD::SETLT)) &&
10885              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10886       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10887
10888     EVT XType = N0.getValueType();
10889     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10890       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10891                                   N0,
10892                                   DAG.getConstant(XType.getSizeInBits()-1,
10893                                          getShiftAmountTy(N0.getValueType())));
10894       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10895                                 XType, N0, Shift);
10896       AddToWorkList(Shift.getNode());
10897       AddToWorkList(Add.getNode());
10898       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10899     }
10900   }
10901
10902   return SDValue();
10903 }
10904
10905 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10906 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10907                                    SDValue N1, ISD::CondCode Cond,
10908                                    SDLoc DL, bool foldBooleans) {
10909   TargetLowering::DAGCombinerInfo
10910     DagCombineInfo(DAG, Level, false, this);
10911   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10912 }
10913
10914 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10915 /// return a DAG expression to select that will generate the same value by
10916 /// multiplying by a magic number.  See:
10917 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10918 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10919   std::vector<SDNode*> Built;
10920   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10921
10922   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10923        ii != ee; ++ii)
10924     AddToWorkList(*ii);
10925   return S;
10926 }
10927
10928 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10929 /// return a DAG expression to select that will generate the same value by
10930 /// multiplying by a magic number.  See:
10931 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10932 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10933   std::vector<SDNode*> Built;
10934   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10935
10936   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10937        ii != ee; ++ii)
10938     AddToWorkList(*ii);
10939   return S;
10940 }
10941
10942 /// FindBaseOffset - Return true if base is a frame index, which is known not
10943 // to alias with anything but itself.  Provides base object and offset as
10944 // results.
10945 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10946                            const GlobalValue *&GV, const void *&CV) {
10947   // Assume it is a primitive operation.
10948   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10949
10950   // If it's an adding a simple constant then integrate the offset.
10951   if (Base.getOpcode() == ISD::ADD) {
10952     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10953       Base = Base.getOperand(0);
10954       Offset += C->getZExtValue();
10955     }
10956   }
10957
10958   // Return the underlying GlobalValue, and update the Offset.  Return false
10959   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10960   // by multiple nodes with different offsets.
10961   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10962     GV = G->getGlobal();
10963     Offset += G->getOffset();
10964     return false;
10965   }
10966
10967   // Return the underlying Constant value, and update the Offset.  Return false
10968   // for ConstantSDNodes since the same constant pool entry may be represented
10969   // by multiple nodes with different offsets.
10970   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10971     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10972                                          : (const void *)C->getConstVal();
10973     Offset += C->getOffset();
10974     return false;
10975   }
10976   // If it's any of the following then it can't alias with anything but itself.
10977   return isa<FrameIndexSDNode>(Base);
10978 }
10979
10980 /// isAlias - Return true if there is any possibility that the two addresses
10981 /// overlap.
10982 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10983                           const Value *SrcValue1, int SrcValueOffset1,
10984                           unsigned SrcValueAlign1,
10985                           const MDNode *TBAAInfo1,
10986                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10987                           const Value *SrcValue2, int SrcValueOffset2,
10988                           unsigned SrcValueAlign2,
10989                           const MDNode *TBAAInfo2) const {
10990   // If they are the same then they must be aliases.
10991   if (Ptr1 == Ptr2) return true;
10992
10993   // If they are both volatile then they cannot be reordered.
10994   if (IsVolatile1 && IsVolatile2) return true;
10995
10996   // Gather base node and offset information.
10997   SDValue Base1, Base2;
10998   int64_t Offset1, Offset2;
10999   const GlobalValue *GV1, *GV2;
11000   const void *CV1, *CV2;
11001   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11002   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11003
11004   // If they have a same base address then check to see if they overlap.
11005   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11006     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11007
11008   // It is possible for different frame indices to alias each other, mostly
11009   // when tail call optimization reuses return address slots for arguments.
11010   // To catch this case, look up the actual index of frame indices to compute
11011   // the real alias relationship.
11012   if (isFrameIndex1 && isFrameIndex2) {
11013     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11014     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11015     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11016     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11017   }
11018
11019   // Otherwise, if we know what the bases are, and they aren't identical, then
11020   // we know they cannot alias.
11021   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11022     return false;
11023
11024   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11025   // compared to the size and offset of the access, we may be able to prove they
11026   // do not alias.  This check is conservative for now to catch cases created by
11027   // splitting vector types.
11028   if ((SrcValueAlign1 == SrcValueAlign2) &&
11029       (SrcValueOffset1 != SrcValueOffset2) &&
11030       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11031     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11032     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11033
11034     // There is no overlap between these relatively aligned accesses of similar
11035     // size, return no alias.
11036     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11037       return false;
11038   }
11039
11040   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11041     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11042   if (UseAA && SrcValue1 && SrcValue2) {
11043     // Use alias analysis information.
11044     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11045     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11046     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11047     AliasAnalysis::AliasResult AAResult =
11048       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
11049                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
11050     if (AAResult == AliasAnalysis::NoAlias)
11051       return false;
11052   }
11053
11054   // Otherwise we have to assume they alias.
11055   return true;
11056 }
11057
11058 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11059   SDValue Ptr0, Ptr1;
11060   int64_t Size0, Size1;
11061   bool IsVolatile0, IsVolatile1;
11062   const Value *SrcValue0, *SrcValue1;
11063   int SrcValueOffset0, SrcValueOffset1;
11064   unsigned SrcValueAlign0, SrcValueAlign1;
11065   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11066   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11067                 SrcValueAlign0, SrcTBAAInfo0);
11068   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11069                 SrcValueAlign1, SrcTBAAInfo1);
11070   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11071                  SrcValueAlign0, SrcTBAAInfo0,
11072                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11073                  SrcValueAlign1, SrcTBAAInfo1);
11074 }
11075
11076 /// FindAliasInfo - Extracts the relevant alias information from the memory
11077 /// node.  Returns true if the operand was a nonvolatile load.
11078 bool DAGCombiner::FindAliasInfo(SDNode *N,
11079                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11080                                 const Value *&SrcValue,
11081                                 int &SrcValueOffset,
11082                                 unsigned &SrcValueAlign,
11083                                 const MDNode *&TBAAInfo) const {
11084   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11085
11086   Ptr = LS->getBasePtr();
11087   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11088   IsVolatile = LS->isVolatile();
11089   SrcValue = LS->getSrcValue();
11090   SrcValueOffset = LS->getSrcValueOffset();
11091   SrcValueAlign = LS->getOriginalAlignment();
11092   TBAAInfo = LS->getTBAAInfo();
11093   return isa<LoadSDNode>(LS) && !IsVolatile;
11094 }
11095
11096 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11097 /// looking for aliasing nodes and adding them to the Aliases vector.
11098 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11099                                    SmallVectorImpl<SDValue> &Aliases) {
11100   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11101   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11102
11103   // Get alias information for node.
11104   SDValue Ptr;
11105   int64_t Size;
11106   bool IsVolatile;
11107   const Value *SrcValue;
11108   int SrcValueOffset;
11109   unsigned SrcValueAlign;
11110   const MDNode *SrcTBAAInfo;
11111   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11112                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11113
11114   // Starting off.
11115   Chains.push_back(OriginalChain);
11116   unsigned Depth = 0;
11117
11118   // Look at each chain and determine if it is an alias.  If so, add it to the
11119   // aliases list.  If not, then continue up the chain looking for the next
11120   // candidate.
11121   while (!Chains.empty()) {
11122     SDValue Chain = Chains.back();
11123     Chains.pop_back();
11124
11125     // For TokenFactor nodes, look at each operand and only continue up the
11126     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11127     // find more and revert to original chain since the xform is unlikely to be
11128     // profitable.
11129     //
11130     // FIXME: The depth check could be made to return the last non-aliasing
11131     // chain we found before we hit a tokenfactor rather than the original
11132     // chain.
11133     if (Depth > 6 || Aliases.size() == 2) {
11134       Aliases.clear();
11135       Aliases.push_back(OriginalChain);
11136       break;
11137     }
11138
11139     // Don't bother if we've been before.
11140     if (!Visited.insert(Chain.getNode()))
11141       continue;
11142
11143     switch (Chain.getOpcode()) {
11144     case ISD::EntryToken:
11145       // Entry token is ideal chain operand, but handled in FindBetterChain.
11146       break;
11147
11148     case ISD::LOAD:
11149     case ISD::STORE: {
11150       // Get alias information for Chain.
11151       SDValue OpPtr;
11152       int64_t OpSize;
11153       bool OpIsVolatile;
11154       const Value *OpSrcValue;
11155       int OpSrcValueOffset;
11156       unsigned OpSrcValueAlign;
11157       const MDNode *OpSrcTBAAInfo;
11158       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11159                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11160                                     OpSrcValueAlign,
11161                                     OpSrcTBAAInfo);
11162
11163       // If chain is alias then stop here.
11164       if (!(IsLoad && IsOpLoad) &&
11165           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11166                   SrcValueAlign, SrcTBAAInfo,
11167                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11168                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11169         Aliases.push_back(Chain);
11170       } else {
11171         // Look further up the chain.
11172         Chains.push_back(Chain.getOperand(0));
11173         ++Depth;
11174       }
11175       break;
11176     }
11177
11178     case ISD::TokenFactor:
11179       // We have to check each of the operands of the token factor for "small"
11180       // token factors, so we queue them up.  Adding the operands to the queue
11181       // (stack) in reverse order maintains the original order and increases the
11182       // likelihood that getNode will find a matching token factor (CSE.)
11183       if (Chain.getNumOperands() > 16) {
11184         Aliases.push_back(Chain);
11185         break;
11186       }
11187       for (unsigned n = Chain.getNumOperands(); n;)
11188         Chains.push_back(Chain.getOperand(--n));
11189       ++Depth;
11190       break;
11191
11192     default:
11193       // For all other instructions we will just have to take what we can get.
11194       Aliases.push_back(Chain);
11195       break;
11196     }
11197   }
11198 }
11199
11200 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11201 /// for a better chain (aliasing node.)
11202 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11203   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11204
11205   // Accumulate all the aliases to this node.
11206   GatherAllAliases(N, OldChain, Aliases);
11207
11208   // If no operands then chain to entry token.
11209   if (Aliases.size() == 0)
11210     return DAG.getEntryNode();
11211
11212   // If a single operand then chain to it.  We don't need to revisit it.
11213   if (Aliases.size() == 1)
11214     return Aliases[0];
11215
11216   // Construct a custom tailored token factor.
11217   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11218                      &Aliases[0], Aliases.size());
11219 }
11220
11221 // SelectionDAG::Combine - This is the entry point for the file.
11222 //
11223 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11224                            CodeGenOpt::Level OptLevel) {
11225   /// run - This is the main entry point to this class.
11226   ///
11227   DAGCombiner(*this, AA, OptLevel).Run(Level);
11228 }