A DAGCombine optimization for merging consecutive stores. This optimization is not...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 using namespace llvm;
39
40 STATISTIC(NodesCombined   , "Number of dag nodes combined");
41 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
42 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
43 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
44 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
45
46 namespace {
47   static cl::opt<bool>
48     CombinerAA("combiner-alias-analysis", cl::Hidden,
49                cl::desc("Turn on alias analysis during testing"));
50
51   static cl::opt<bool>
52     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53                cl::desc("Include global information in alias analysis"));
54
55 //------------------------------ DAGCombiner ---------------------------------//
56
57   class DAGCombiner {
58     SelectionDAG &DAG;
59     const TargetLowering &TLI;
60     CombineLevel Level;
61     CodeGenOpt::Level OptLevel;
62     bool LegalOperations;
63     bool LegalTypes;
64
65     // Worklist of all of the nodes that need to be simplified.
66     //
67     // This has the semantics that when adding to the worklist,
68     // the item added must be next to be processed. It should
69     // also only appear once. The naive approach to this takes
70     // linear time.
71     //
72     // To reduce the insert/remove time to logarithmic, we use
73     // a set and a vector to maintain our worklist.
74     //
75     // The set contains the items on the worklist, but does not
76     // maintain the order they should be visited.
77     //
78     // The vector maintains the order nodes should be visited, but may
79     // contain duplicate or removed nodes. When choosing a node to
80     // visit, we pop off the order stack until we find an item that is
81     // also in the contents set. All operations are O(log N).
82     SmallPtrSet<SDNode*, 64> WorkListContents;
83     SmallVector<SDNode*, 64> WorkListOrder;
84
85     // AA - Used for DAG load/store alias analysis.
86     AliasAnalysis &AA;
87
88     /// AddUsersToWorkList - When an instruction is simplified, add all users of
89     /// the instruction to the work lists because they might get more simplified
90     /// now.
91     ///
92     void AddUsersToWorkList(SDNode *N) {
93       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
94            UI != UE; ++UI)
95         AddToWorkList(*UI);
96     }
97
98     /// visit - call the node-specific routine that knows how to fold each
99     /// particular type of node.
100     SDValue visit(SDNode *N);
101
102   public:
103     /// AddToWorkList - Add to the work list making sure its instance is at the
104     /// back (next to be processed.)
105     void AddToWorkList(SDNode *N) {
106       WorkListContents.insert(N);
107       WorkListOrder.push_back(N);
108     }
109
110     /// removeFromWorkList - remove all instances of N from the worklist.
111     ///
112     void removeFromWorkList(SDNode *N) {
113       WorkListContents.erase(N);
114     }
115
116     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
117                       bool AddTo = true);
118
119     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
120       return CombineTo(N, &Res, 1, AddTo);
121     }
122
123     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
124                       bool AddTo = true) {
125       SDValue To[] = { Res0, Res1 };
126       return CombineTo(N, To, 2, AddTo);
127     }
128
129     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
130
131   private:
132
133     /// SimplifyDemandedBits - Check the specified integer node value to see if
134     /// it can be simplified or if things it uses can be simplified by bit
135     /// propagation.  If so, return true.
136     bool SimplifyDemandedBits(SDValue Op) {
137       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
138       APInt Demanded = APInt::getAllOnesValue(BitWidth);
139       return SimplifyDemandedBits(Op, Demanded);
140     }
141
142     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
143
144     bool CombineToPreIndexedLoadStore(SDNode *N);
145     bool CombineToPostIndexedLoadStore(SDNode *N);
146
147     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
148     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
149     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
150     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
151     SDValue PromoteIntBinOp(SDValue Op);
152     SDValue PromoteIntShiftOp(SDValue Op);
153     SDValue PromoteExtend(SDValue Op);
154     bool PromoteLoad(SDValue Op);
155
156     void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
157                          SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
158                          ISD::NodeType ExtType);
159
160     /// combine - call the node-specific routine that knows how to fold each
161     /// particular type of node. If that doesn't do anything, try the
162     /// target-specific DAG combines.
163     SDValue combine(SDNode *N);
164
165     // Visitation implementation - Implement dag node combining for different
166     // node types.  The semantics are as follows:
167     // Return Value:
168     //   SDValue.getNode() == 0 - No change was made
169     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
170     //   otherwise              - N should be replaced by the returned Operand.
171     //
172     SDValue visitTokenFactor(SDNode *N);
173     SDValue visitMERGE_VALUES(SDNode *N);
174     SDValue visitADD(SDNode *N);
175     SDValue visitSUB(SDNode *N);
176     SDValue visitADDC(SDNode *N);
177     SDValue visitSUBC(SDNode *N);
178     SDValue visitADDE(SDNode *N);
179     SDValue visitSUBE(SDNode *N);
180     SDValue visitMUL(SDNode *N);
181     SDValue visitSDIV(SDNode *N);
182     SDValue visitUDIV(SDNode *N);
183     SDValue visitSREM(SDNode *N);
184     SDValue visitUREM(SDNode *N);
185     SDValue visitMULHU(SDNode *N);
186     SDValue visitMULHS(SDNode *N);
187     SDValue visitSMUL_LOHI(SDNode *N);
188     SDValue visitUMUL_LOHI(SDNode *N);
189     SDValue visitSMULO(SDNode *N);
190     SDValue visitUMULO(SDNode *N);
191     SDValue visitSDIVREM(SDNode *N);
192     SDValue visitUDIVREM(SDNode *N);
193     SDValue visitAND(SDNode *N);
194     SDValue visitOR(SDNode *N);
195     SDValue visitXOR(SDNode *N);
196     SDValue SimplifyVBinOp(SDNode *N);
197     SDValue SimplifyVUnaryOp(SDNode *N);
198     SDValue visitSHL(SDNode *N);
199     SDValue visitSRA(SDNode *N);
200     SDValue visitSRL(SDNode *N);
201     SDValue visitCTLZ(SDNode *N);
202     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
203     SDValue visitCTTZ(SDNode *N);
204     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
205     SDValue visitCTPOP(SDNode *N);
206     SDValue visitSELECT(SDNode *N);
207     SDValue visitSELECT_CC(SDNode *N);
208     SDValue visitSETCC(SDNode *N);
209     SDValue visitSIGN_EXTEND(SDNode *N);
210     SDValue visitZERO_EXTEND(SDNode *N);
211     SDValue visitANY_EXTEND(SDNode *N);
212     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
213     SDValue visitTRUNCATE(SDNode *N);
214     SDValue visitBITCAST(SDNode *N);
215     SDValue visitBUILD_PAIR(SDNode *N);
216     SDValue visitFADD(SDNode *N);
217     SDValue visitFSUB(SDNode *N);
218     SDValue visitFMUL(SDNode *N);
219     SDValue visitFMA(SDNode *N);
220     SDValue visitFDIV(SDNode *N);
221     SDValue visitFREM(SDNode *N);
222     SDValue visitFCOPYSIGN(SDNode *N);
223     SDValue visitSINT_TO_FP(SDNode *N);
224     SDValue visitUINT_TO_FP(SDNode *N);
225     SDValue visitFP_TO_SINT(SDNode *N);
226     SDValue visitFP_TO_UINT(SDNode *N);
227     SDValue visitFP_ROUND(SDNode *N);
228     SDValue visitFP_ROUND_INREG(SDNode *N);
229     SDValue visitFP_EXTEND(SDNode *N);
230     SDValue visitFNEG(SDNode *N);
231     SDValue visitFABS(SDNode *N);
232     SDValue visitFCEIL(SDNode *N);
233     SDValue visitFTRUNC(SDNode *N);
234     SDValue visitFFLOOR(SDNode *N);
235     SDValue visitBRCOND(SDNode *N);
236     SDValue visitBR_CC(SDNode *N);
237     SDValue visitLOAD(SDNode *N);
238     SDValue visitSTORE(SDNode *N);
239     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
240     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
241     SDValue visitBUILD_VECTOR(SDNode *N);
242     SDValue visitCONCAT_VECTORS(SDNode *N);
243     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
244     SDValue visitVECTOR_SHUFFLE(SDNode *N);
245     SDValue visitMEMBARRIER(SDNode *N);
246
247     SDValue XformToShuffleWithZero(SDNode *N);
248     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
249
250     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
251
252     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
253     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
254     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
255     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
256                              SDValue N3, ISD::CondCode CC,
257                              bool NotExtCompare = false);
258     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
259                           DebugLoc DL, bool foldBooleans = true);
260     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
261                                          unsigned HiOp);
262     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
263     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
264     SDValue BuildSDIV(SDNode *N);
265     SDValue BuildUDIV(SDNode *N);
266     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
267                                bool DemandHighBits = true);
268     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
269     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
270     SDValue ReduceLoadWidth(SDNode *N);
271     SDValue ReduceLoadOpStoreWidth(SDNode *N);
272     SDValue TransformFPLoadStorePair(SDNode *N);
273
274     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
275
276     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
277     /// looking for aliasing nodes and adding them to the Aliases vector.
278     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
279                           SmallVector<SDValue, 8> &Aliases);
280
281     /// isAlias - Return true if there is any possibility that the two addresses
282     /// overlap.
283     bool isAlias(SDValue Ptr1, int64_t Size1,
284                  const Value *SrcValue1, int SrcValueOffset1,
285                  unsigned SrcValueAlign1,
286                  const MDNode *TBAAInfo1,
287                  SDValue Ptr2, int64_t Size2,
288                  const Value *SrcValue2, int SrcValueOffset2,
289                  unsigned SrcValueAlign2,
290                  const MDNode *TBAAInfo2) const;
291
292     /// FindAliasInfo - Extracts the relevant alias information from the memory
293     /// node.  Returns true if the operand was a load.
294     bool FindAliasInfo(SDNode *N,
295                        SDValue &Ptr, int64_t &Size,
296                        const Value *&SrcValue, int &SrcValueOffset,
297                        unsigned &SrcValueAlignment,
298                        const MDNode *&TBAAInfo) const;
299
300     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
301     /// looking for a better chain (aliasing node.)
302     SDValue FindBetterChain(SDNode *N, SDValue Chain);
303
304     /// Merge consecutive store operations into a wide store.
305     /// \return True if some memory operations were changed.
306     bool MergeConsecutiveStores(StoreSDNode *N);
307
308   public:
309     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
310       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
311         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
312
313     /// Run - runs the dag combiner on all nodes in the work list
314     void Run(CombineLevel AtLevel);
315
316     SelectionDAG &getDAG() const { return DAG; }
317
318     /// getShiftAmountTy - Returns a type large enough to hold any valid
319     /// shift amount - before type legalization these can be huge.
320     EVT getShiftAmountTy(EVT LHSTy) {
321       return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
322     }
323
324     /// isTypeLegal - This method returns true if we are running before type
325     /// legalization or if the specified VT is legal.
326     bool isTypeLegal(const EVT &VT) {
327       if (!LegalTypes) return true;
328       return TLI.isTypeLegal(VT);
329     }
330   };
331 }
332
333
334 namespace {
335 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
336 /// nodes from the worklist.
337 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
338   DAGCombiner &DC;
339 public:
340   explicit WorkListRemover(DAGCombiner &dc)
341     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
342
343   virtual void NodeDeleted(SDNode *N, SDNode *E) {
344     DC.removeFromWorkList(N);
345   }
346 };
347 }
348
349 //===----------------------------------------------------------------------===//
350 //  TargetLowering::DAGCombinerInfo implementation
351 //===----------------------------------------------------------------------===//
352
353 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
354   ((DAGCombiner*)DC)->AddToWorkList(N);
355 }
356
357 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
358   ((DAGCombiner*)DC)->removeFromWorkList(N);
359 }
360
361 SDValue TargetLowering::DAGCombinerInfo::
362 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
363   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
364 }
365
366 SDValue TargetLowering::DAGCombinerInfo::
367 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
368   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
369 }
370
371
372 SDValue TargetLowering::DAGCombinerInfo::
373 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
374   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
375 }
376
377 void TargetLowering::DAGCombinerInfo::
378 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
379   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
380 }
381
382 //===----------------------------------------------------------------------===//
383 // Helper Functions
384 //===----------------------------------------------------------------------===//
385
386 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
387 /// specified expression for the same cost as the expression itself, or 2 if we
388 /// can compute the negated form more cheaply than the expression itself.
389 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
390                                const TargetLowering &TLI,
391                                const TargetOptions *Options,
392                                unsigned Depth = 0) {
393   // No compile time optimizations on this type.
394   if (Op.getValueType() == MVT::ppcf128)
395     return 0;
396
397   // fneg is removable even if it has multiple uses.
398   if (Op.getOpcode() == ISD::FNEG) return 2;
399
400   // Don't allow anything with multiple uses.
401   if (!Op.hasOneUse()) return 0;
402
403   // Don't recurse exponentially.
404   if (Depth > 6) return 0;
405
406   switch (Op.getOpcode()) {
407   default: return false;
408   case ISD::ConstantFP:
409     // Don't invert constant FP values after legalize.  The negated constant
410     // isn't necessarily legal.
411     return LegalOperations ? 0 : 1;
412   case ISD::FADD:
413     // FIXME: determine better conditions for this xform.
414     if (!Options->UnsafeFPMath) return 0;
415
416     // After operation legalization, it might not be legal to create new FSUBs.
417     if (LegalOperations &&
418         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
419       return 0;
420
421     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
422     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
423                                     Options, Depth + 1))
424       return V;
425     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
426     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
427                               Depth + 1);
428   case ISD::FSUB:
429     // We can't turn -(A-B) into B-A when we honor signed zeros.
430     if (!Options->UnsafeFPMath) return 0;
431
432     // fold (fneg (fsub A, B)) -> (fsub B, A)
433     return 1;
434
435   case ISD::FMUL:
436   case ISD::FDIV:
437     if (Options->HonorSignDependentRoundingFPMath()) return 0;
438
439     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
440     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
441                                     Options, Depth + 1))
442       return V;
443
444     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
445                               Depth + 1);
446
447   case ISD::FP_EXTEND:
448   case ISD::FP_ROUND:
449   case ISD::FSIN:
450     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
451                               Depth + 1);
452   }
453 }
454
455 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
456 /// returns the newly negated expression.
457 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
458                                     bool LegalOperations, unsigned Depth = 0) {
459   // fneg is removable even if it has multiple uses.
460   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
461
462   // Don't allow anything with multiple uses.
463   assert(Op.hasOneUse() && "Unknown reuse!");
464
465   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
466   switch (Op.getOpcode()) {
467   default: llvm_unreachable("Unknown code");
468   case ISD::ConstantFP: {
469     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
470     V.changeSign();
471     return DAG.getConstantFP(V, Op.getValueType());
472   }
473   case ISD::FADD:
474     // FIXME: determine better conditions for this xform.
475     assert(DAG.getTarget().Options.UnsafeFPMath);
476
477     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
478     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
479                            DAG.getTargetLoweringInfo(),
480                            &DAG.getTarget().Options, Depth+1))
481       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
482                          GetNegatedExpression(Op.getOperand(0), DAG,
483                                               LegalOperations, Depth+1),
484                          Op.getOperand(1));
485     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
486     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
487                        GetNegatedExpression(Op.getOperand(1), DAG,
488                                             LegalOperations, Depth+1),
489                        Op.getOperand(0));
490   case ISD::FSUB:
491     // We can't turn -(A-B) into B-A when we honor signed zeros.
492     assert(DAG.getTarget().Options.UnsafeFPMath);
493
494     // fold (fneg (fsub 0, B)) -> B
495     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
496       if (N0CFP->getValueAPF().isZero())
497         return Op.getOperand(1);
498
499     // fold (fneg (fsub A, B)) -> (fsub B, A)
500     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
501                        Op.getOperand(1), Op.getOperand(0));
502
503   case ISD::FMUL:
504   case ISD::FDIV:
505     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
506
507     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
508     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
509                            DAG.getTargetLoweringInfo(),
510                            &DAG.getTarget().Options, Depth+1))
511       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
512                          GetNegatedExpression(Op.getOperand(0), DAG,
513                                               LegalOperations, Depth+1),
514                          Op.getOperand(1));
515
516     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
517     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
518                        Op.getOperand(0),
519                        GetNegatedExpression(Op.getOperand(1), DAG,
520                                             LegalOperations, Depth+1));
521
522   case ISD::FP_EXTEND:
523   case ISD::FSIN:
524     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
525                        GetNegatedExpression(Op.getOperand(0), DAG,
526                                             LegalOperations, Depth+1));
527   case ISD::FP_ROUND:
528       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
529                          GetNegatedExpression(Op.getOperand(0), DAG,
530                                               LegalOperations, Depth+1),
531                          Op.getOperand(1));
532   }
533 }
534
535
536 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
537 // that selects between the values 1 and 0, making it equivalent to a setcc.
538 // Also, set the incoming LHS, RHS, and CC references to the appropriate
539 // nodes based on the type of node we are checking.  This simplifies life a
540 // bit for the callers.
541 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
542                               SDValue &CC) {
543   if (N.getOpcode() == ISD::SETCC) {
544     LHS = N.getOperand(0);
545     RHS = N.getOperand(1);
546     CC  = N.getOperand(2);
547     return true;
548   }
549   if (N.getOpcode() == ISD::SELECT_CC &&
550       N.getOperand(2).getOpcode() == ISD::Constant &&
551       N.getOperand(3).getOpcode() == ISD::Constant &&
552       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
553       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
554     LHS = N.getOperand(0);
555     RHS = N.getOperand(1);
556     CC  = N.getOperand(4);
557     return true;
558   }
559   return false;
560 }
561
562 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
563 // one use.  If this is true, it allows the users to invert the operation for
564 // free when it is profitable to do so.
565 static bool isOneUseSetCC(SDValue N) {
566   SDValue N0, N1, N2;
567   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
568     return true;
569   return false;
570 }
571
572 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
573                                     SDValue N0, SDValue N1) {
574   EVT VT = N0.getValueType();
575   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
576     if (isa<ConstantSDNode>(N1)) {
577       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
578       SDValue OpNode =
579         DAG.FoldConstantArithmetic(Opc, VT,
580                                    cast<ConstantSDNode>(N0.getOperand(1)),
581                                    cast<ConstantSDNode>(N1));
582       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
583     }
584     if (N0.hasOneUse()) {
585       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
586       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
587                                    N0.getOperand(0), N1);
588       AddToWorkList(OpNode.getNode());
589       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
590     }
591   }
592
593   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
594     if (isa<ConstantSDNode>(N0)) {
595       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
596       SDValue OpNode =
597         DAG.FoldConstantArithmetic(Opc, VT,
598                                    cast<ConstantSDNode>(N1.getOperand(1)),
599                                    cast<ConstantSDNode>(N0));
600       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
601     }
602     if (N1.hasOneUse()) {
603       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
604       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
605                                    N1.getOperand(0), N0);
606       AddToWorkList(OpNode.getNode());
607       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
608     }
609   }
610
611   return SDValue();
612 }
613
614 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
615                                bool AddTo) {
616   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
617   ++NodesCombined;
618   DEBUG(dbgs() << "\nReplacing.1 ";
619         N->dump(&DAG);
620         dbgs() << "\nWith: ";
621         To[0].getNode()->dump(&DAG);
622         dbgs() << " and " << NumTo-1 << " other values\n";
623         for (unsigned i = 0, e = NumTo; i != e; ++i)
624           assert((!To[i].getNode() ||
625                   N->getValueType(i) == To[i].getValueType()) &&
626                  "Cannot combine value to value of different type!"));
627   WorkListRemover DeadNodes(*this);
628   DAG.ReplaceAllUsesWith(N, To);
629   if (AddTo) {
630     // Push the new nodes and any users onto the worklist
631     for (unsigned i = 0, e = NumTo; i != e; ++i) {
632       if (To[i].getNode()) {
633         AddToWorkList(To[i].getNode());
634         AddUsersToWorkList(To[i].getNode());
635       }
636     }
637   }
638
639   // Finally, if the node is now dead, remove it from the graph.  The node
640   // may not be dead if the replacement process recursively simplified to
641   // something else needing this node.
642   if (N->use_empty()) {
643     // Nodes can be reintroduced into the worklist.  Make sure we do not
644     // process a node that has been replaced.
645     removeFromWorkList(N);
646
647     // Finally, since the node is now dead, remove it from the graph.
648     DAG.DeleteNode(N);
649   }
650   return SDValue(N, 0);
651 }
652
653 void DAGCombiner::
654 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
655   // Replace all uses.  If any nodes become isomorphic to other nodes and
656   // are deleted, make sure to remove them from our worklist.
657   WorkListRemover DeadNodes(*this);
658   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
659
660   // Push the new node and any (possibly new) users onto the worklist.
661   AddToWorkList(TLO.New.getNode());
662   AddUsersToWorkList(TLO.New.getNode());
663
664   // Finally, if the node is now dead, remove it from the graph.  The node
665   // may not be dead if the replacement process recursively simplified to
666   // something else needing this node.
667   if (TLO.Old.getNode()->use_empty()) {
668     removeFromWorkList(TLO.Old.getNode());
669
670     // If the operands of this node are only used by the node, they will now
671     // be dead.  Make sure to visit them first to delete dead nodes early.
672     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
673       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
674         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
675
676     DAG.DeleteNode(TLO.Old.getNode());
677   }
678 }
679
680 /// SimplifyDemandedBits - Check the specified integer node value to see if
681 /// it can be simplified or if things it uses can be simplified by bit
682 /// propagation.  If so, return true.
683 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
684   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
685   APInt KnownZero, KnownOne;
686   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
687     return false;
688
689   // Revisit the node.
690   AddToWorkList(Op.getNode());
691
692   // Replace the old value with the new one.
693   ++NodesCombined;
694   DEBUG(dbgs() << "\nReplacing.2 ";
695         TLO.Old.getNode()->dump(&DAG);
696         dbgs() << "\nWith: ";
697         TLO.New.getNode()->dump(&DAG);
698         dbgs() << '\n');
699
700   CommitTargetLoweringOpt(TLO);
701   return true;
702 }
703
704 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
705   DebugLoc dl = Load->getDebugLoc();
706   EVT VT = Load->getValueType(0);
707   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
708
709   DEBUG(dbgs() << "\nReplacing.9 ";
710         Load->dump(&DAG);
711         dbgs() << "\nWith: ";
712         Trunc.getNode()->dump(&DAG);
713         dbgs() << '\n');
714   WorkListRemover DeadNodes(*this);
715   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
716   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
717   removeFromWorkList(Load);
718   DAG.DeleteNode(Load);
719   AddToWorkList(Trunc.getNode());
720 }
721
722 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
723   Replace = false;
724   DebugLoc dl = Op.getDebugLoc();
725   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
726     EVT MemVT = LD->getMemoryVT();
727     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
728       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
729                                                   : ISD::EXTLOAD)
730       : LD->getExtensionType();
731     Replace = true;
732     return DAG.getExtLoad(ExtType, dl, PVT,
733                           LD->getChain(), LD->getBasePtr(),
734                           LD->getPointerInfo(),
735                           MemVT, LD->isVolatile(),
736                           LD->isNonTemporal(), LD->getAlignment());
737   }
738
739   unsigned Opc = Op.getOpcode();
740   switch (Opc) {
741   default: break;
742   case ISD::AssertSext:
743     return DAG.getNode(ISD::AssertSext, dl, PVT,
744                        SExtPromoteOperand(Op.getOperand(0), PVT),
745                        Op.getOperand(1));
746   case ISD::AssertZext:
747     return DAG.getNode(ISD::AssertZext, dl, PVT,
748                        ZExtPromoteOperand(Op.getOperand(0), PVT),
749                        Op.getOperand(1));
750   case ISD::Constant: {
751     unsigned ExtOpc =
752       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
753     return DAG.getNode(ExtOpc, dl, PVT, Op);
754   }
755   }
756
757   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
758     return SDValue();
759   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
760 }
761
762 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
763   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
764     return SDValue();
765   EVT OldVT = Op.getValueType();
766   DebugLoc dl = Op.getDebugLoc();
767   bool Replace = false;
768   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
769   if (NewOp.getNode() == 0)
770     return SDValue();
771   AddToWorkList(NewOp.getNode());
772
773   if (Replace)
774     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
775   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
776                      DAG.getValueType(OldVT));
777 }
778
779 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
780   EVT OldVT = Op.getValueType();
781   DebugLoc dl = Op.getDebugLoc();
782   bool Replace = false;
783   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
784   if (NewOp.getNode() == 0)
785     return SDValue();
786   AddToWorkList(NewOp.getNode());
787
788   if (Replace)
789     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
790   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
791 }
792
793 /// PromoteIntBinOp - Promote the specified integer binary operation if the
794 /// target indicates it is beneficial. e.g. On x86, it's usually better to
795 /// promote i16 operations to i32 since i16 instructions are longer.
796 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
797   if (!LegalOperations)
798     return SDValue();
799
800   EVT VT = Op.getValueType();
801   if (VT.isVector() || !VT.isInteger())
802     return SDValue();
803
804   // If operation type is 'undesirable', e.g. i16 on x86, consider
805   // promoting it.
806   unsigned Opc = Op.getOpcode();
807   if (TLI.isTypeDesirableForOp(Opc, VT))
808     return SDValue();
809
810   EVT PVT = VT;
811   // Consult target whether it is a good idea to promote this operation and
812   // what's the right type to promote it to.
813   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
814     assert(PVT != VT && "Don't know what type to promote to!");
815
816     bool Replace0 = false;
817     SDValue N0 = Op.getOperand(0);
818     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
819     if (NN0.getNode() == 0)
820       return SDValue();
821
822     bool Replace1 = false;
823     SDValue N1 = Op.getOperand(1);
824     SDValue NN1;
825     if (N0 == N1)
826       NN1 = NN0;
827     else {
828       NN1 = PromoteOperand(N1, PVT, Replace1);
829       if (NN1.getNode() == 0)
830         return SDValue();
831     }
832
833     AddToWorkList(NN0.getNode());
834     if (NN1.getNode())
835       AddToWorkList(NN1.getNode());
836
837     if (Replace0)
838       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
839     if (Replace1)
840       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
841
842     DEBUG(dbgs() << "\nPromoting ";
843           Op.getNode()->dump(&DAG));
844     DebugLoc dl = Op.getDebugLoc();
845     return DAG.getNode(ISD::TRUNCATE, dl, VT,
846                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
847   }
848   return SDValue();
849 }
850
851 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
852 /// target indicates it is beneficial. e.g. On x86, it's usually better to
853 /// promote i16 operations to i32 since i16 instructions are longer.
854 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
855   if (!LegalOperations)
856     return SDValue();
857
858   EVT VT = Op.getValueType();
859   if (VT.isVector() || !VT.isInteger())
860     return SDValue();
861
862   // If operation type is 'undesirable', e.g. i16 on x86, consider
863   // promoting it.
864   unsigned Opc = Op.getOpcode();
865   if (TLI.isTypeDesirableForOp(Opc, VT))
866     return SDValue();
867
868   EVT PVT = VT;
869   // Consult target whether it is a good idea to promote this operation and
870   // what's the right type to promote it to.
871   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
872     assert(PVT != VT && "Don't know what type to promote to!");
873
874     bool Replace = false;
875     SDValue N0 = Op.getOperand(0);
876     if (Opc == ISD::SRA)
877       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
878     else if (Opc == ISD::SRL)
879       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
880     else
881       N0 = PromoteOperand(N0, PVT, Replace);
882     if (N0.getNode() == 0)
883       return SDValue();
884
885     AddToWorkList(N0.getNode());
886     if (Replace)
887       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
888
889     DEBUG(dbgs() << "\nPromoting ";
890           Op.getNode()->dump(&DAG));
891     DebugLoc dl = Op.getDebugLoc();
892     return DAG.getNode(ISD::TRUNCATE, dl, VT,
893                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
894   }
895   return SDValue();
896 }
897
898 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
899   if (!LegalOperations)
900     return SDValue();
901
902   EVT VT = Op.getValueType();
903   if (VT.isVector() || !VT.isInteger())
904     return SDValue();
905
906   // If operation type is 'undesirable', e.g. i16 on x86, consider
907   // promoting it.
908   unsigned Opc = Op.getOpcode();
909   if (TLI.isTypeDesirableForOp(Opc, VT))
910     return SDValue();
911
912   EVT PVT = VT;
913   // Consult target whether it is a good idea to promote this operation and
914   // what's the right type to promote it to.
915   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
916     assert(PVT != VT && "Don't know what type to promote to!");
917     // fold (aext (aext x)) -> (aext x)
918     // fold (aext (zext x)) -> (zext x)
919     // fold (aext (sext x)) -> (sext x)
920     DEBUG(dbgs() << "\nPromoting ";
921           Op.getNode()->dump(&DAG));
922     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
923   }
924   return SDValue();
925 }
926
927 bool DAGCombiner::PromoteLoad(SDValue Op) {
928   if (!LegalOperations)
929     return false;
930
931   EVT VT = Op.getValueType();
932   if (VT.isVector() || !VT.isInteger())
933     return false;
934
935   // If operation type is 'undesirable', e.g. i16 on x86, consider
936   // promoting it.
937   unsigned Opc = Op.getOpcode();
938   if (TLI.isTypeDesirableForOp(Opc, VT))
939     return false;
940
941   EVT PVT = VT;
942   // Consult target whether it is a good idea to promote this operation and
943   // what's the right type to promote it to.
944   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
945     assert(PVT != VT && "Don't know what type to promote to!");
946
947     DebugLoc dl = Op.getDebugLoc();
948     SDNode *N = Op.getNode();
949     LoadSDNode *LD = cast<LoadSDNode>(N);
950     EVT MemVT = LD->getMemoryVT();
951     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
952       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
953                                                   : ISD::EXTLOAD)
954       : LD->getExtensionType();
955     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
956                                    LD->getChain(), LD->getBasePtr(),
957                                    LD->getPointerInfo(),
958                                    MemVT, LD->isVolatile(),
959                                    LD->isNonTemporal(), LD->getAlignment());
960     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
961
962     DEBUG(dbgs() << "\nPromoting ";
963           N->dump(&DAG);
964           dbgs() << "\nTo: ";
965           Result.getNode()->dump(&DAG);
966           dbgs() << '\n');
967     WorkListRemover DeadNodes(*this);
968     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
969     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
970     removeFromWorkList(N);
971     DAG.DeleteNode(N);
972     AddToWorkList(Result.getNode());
973     return true;
974   }
975   return false;
976 }
977
978
979 //===----------------------------------------------------------------------===//
980 //  Main DAG Combiner implementation
981 //===----------------------------------------------------------------------===//
982
983 void DAGCombiner::Run(CombineLevel AtLevel) {
984   // set the instance variables, so that the various visit routines may use it.
985   Level = AtLevel;
986   LegalOperations = Level >= AfterLegalizeVectorOps;
987   LegalTypes = Level >= AfterLegalizeTypes;
988
989   // Add all the dag nodes to the worklist.
990   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
991        E = DAG.allnodes_end(); I != E; ++I)
992     AddToWorkList(I);
993
994   // Create a dummy node (which is not added to allnodes), that adds a reference
995   // to the root node, preventing it from being deleted, and tracking any
996   // changes of the root.
997   HandleSDNode Dummy(DAG.getRoot());
998
999   // The root of the dag may dangle to deleted nodes until the dag combiner is
1000   // done.  Set it to null to avoid confusion.
1001   DAG.setRoot(SDValue());
1002
1003   // while the worklist isn't empty, find a node and
1004   // try and combine it.
1005   while (!WorkListContents.empty()) {
1006     SDNode *N;
1007     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1008     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1009     // worklist *should* contain, and check the node we want to visit is should
1010     // actually be visited.
1011     do {
1012       N = WorkListOrder.pop_back_val();
1013     } while (!WorkListContents.erase(N));
1014
1015     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1016     // N is deleted from the DAG, since they too may now be dead or may have a
1017     // reduced number of uses, allowing other xforms.
1018     if (N->use_empty() && N != &Dummy) {
1019       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1020         AddToWorkList(N->getOperand(i).getNode());
1021
1022       DAG.DeleteNode(N);
1023       continue;
1024     }
1025
1026     SDValue RV = combine(N);
1027
1028     if (RV.getNode() == 0)
1029       continue;
1030
1031     ++NodesCombined;
1032
1033     // If we get back the same node we passed in, rather than a new node or
1034     // zero, we know that the node must have defined multiple values and
1035     // CombineTo was used.  Since CombineTo takes care of the worklist
1036     // mechanics for us, we have no work to do in this case.
1037     if (RV.getNode() == N)
1038       continue;
1039
1040     assert(N->getOpcode() != ISD::DELETED_NODE &&
1041            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1042            "Node was deleted but visit returned new node!");
1043
1044     DEBUG(dbgs() << "\nReplacing.3 ";
1045           N->dump(&DAG);
1046           dbgs() << "\nWith: ";
1047           RV.getNode()->dump(&DAG);
1048           dbgs() << '\n');
1049
1050     // Transfer debug value.
1051     DAG.TransferDbgValues(SDValue(N, 0), RV);
1052     WorkListRemover DeadNodes(*this);
1053     if (N->getNumValues() == RV.getNode()->getNumValues())
1054       DAG.ReplaceAllUsesWith(N, RV.getNode());
1055     else {
1056       assert(N->getValueType(0) == RV.getValueType() &&
1057              N->getNumValues() == 1 && "Type mismatch");
1058       SDValue OpV = RV;
1059       DAG.ReplaceAllUsesWith(N, &OpV);
1060     }
1061
1062     // Push the new node and any users onto the worklist
1063     AddToWorkList(RV.getNode());
1064     AddUsersToWorkList(RV.getNode());
1065
1066     // Add any uses of the old node to the worklist in case this node is the
1067     // last one that uses them.  They may become dead after this node is
1068     // deleted.
1069     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1070       AddToWorkList(N->getOperand(i).getNode());
1071
1072     // Finally, if the node is now dead, remove it from the graph.  The node
1073     // may not be dead if the replacement process recursively simplified to
1074     // something else needing this node.
1075     if (N->use_empty()) {
1076       // Nodes can be reintroduced into the worklist.  Make sure we do not
1077       // process a node that has been replaced.
1078       removeFromWorkList(N);
1079
1080       // Finally, since the node is now dead, remove it from the graph.
1081       DAG.DeleteNode(N);
1082     }
1083   }
1084
1085   // If the root changed (e.g. it was a dead load, update the root).
1086   DAG.setRoot(Dummy.getValue());
1087   DAG.RemoveDeadNodes();
1088 }
1089
1090 SDValue DAGCombiner::visit(SDNode *N) {
1091   switch (N->getOpcode()) {
1092   default: break;
1093   case ISD::TokenFactor:        return visitTokenFactor(N);
1094   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1095   case ISD::ADD:                return visitADD(N);
1096   case ISD::SUB:                return visitSUB(N);
1097   case ISD::ADDC:               return visitADDC(N);
1098   case ISD::SUBC:               return visitSUBC(N);
1099   case ISD::ADDE:               return visitADDE(N);
1100   case ISD::SUBE:               return visitSUBE(N);
1101   case ISD::MUL:                return visitMUL(N);
1102   case ISD::SDIV:               return visitSDIV(N);
1103   case ISD::UDIV:               return visitUDIV(N);
1104   case ISD::SREM:               return visitSREM(N);
1105   case ISD::UREM:               return visitUREM(N);
1106   case ISD::MULHU:              return visitMULHU(N);
1107   case ISD::MULHS:              return visitMULHS(N);
1108   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1109   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1110   case ISD::SMULO:              return visitSMULO(N);
1111   case ISD::UMULO:              return visitUMULO(N);
1112   case ISD::SDIVREM:            return visitSDIVREM(N);
1113   case ISD::UDIVREM:            return visitUDIVREM(N);
1114   case ISD::AND:                return visitAND(N);
1115   case ISD::OR:                 return visitOR(N);
1116   case ISD::XOR:                return visitXOR(N);
1117   case ISD::SHL:                return visitSHL(N);
1118   case ISD::SRA:                return visitSRA(N);
1119   case ISD::SRL:                return visitSRL(N);
1120   case ISD::CTLZ:               return visitCTLZ(N);
1121   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1122   case ISD::CTTZ:               return visitCTTZ(N);
1123   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1124   case ISD::CTPOP:              return visitCTPOP(N);
1125   case ISD::SELECT:             return visitSELECT(N);
1126   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1127   case ISD::SETCC:              return visitSETCC(N);
1128   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1129   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1130   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1131   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1132   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1133   case ISD::BITCAST:            return visitBITCAST(N);
1134   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1135   case ISD::FADD:               return visitFADD(N);
1136   case ISD::FSUB:               return visitFSUB(N);
1137   case ISD::FMUL:               return visitFMUL(N);
1138   case ISD::FMA:                return visitFMA(N);
1139   case ISD::FDIV:               return visitFDIV(N);
1140   case ISD::FREM:               return visitFREM(N);
1141   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1142   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1143   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1144   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1145   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1146   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1147   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1148   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1149   case ISD::FNEG:               return visitFNEG(N);
1150   case ISD::FABS:               return visitFABS(N);
1151   case ISD::FFLOOR:             return visitFFLOOR(N);
1152   case ISD::FCEIL:              return visitFCEIL(N);
1153   case ISD::FTRUNC:             return visitFTRUNC(N);
1154   case ISD::BRCOND:             return visitBRCOND(N);
1155   case ISD::BR_CC:              return visitBR_CC(N);
1156   case ISD::LOAD:               return visitLOAD(N);
1157   case ISD::STORE:              return visitSTORE(N);
1158   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1159   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1160   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1161   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1162   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1163   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1164   case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
1165   }
1166   return SDValue();
1167 }
1168
1169 SDValue DAGCombiner::combine(SDNode *N) {
1170   SDValue RV = visit(N);
1171
1172   // If nothing happened, try a target-specific DAG combine.
1173   if (RV.getNode() == 0) {
1174     assert(N->getOpcode() != ISD::DELETED_NODE &&
1175            "Node was deleted but visit returned NULL!");
1176
1177     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1178         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1179
1180       // Expose the DAG combiner to the target combiner impls.
1181       TargetLowering::DAGCombinerInfo
1182         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1183
1184       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1185     }
1186   }
1187
1188   // If nothing happened still, try promoting the operation.
1189   if (RV.getNode() == 0) {
1190     switch (N->getOpcode()) {
1191     default: break;
1192     case ISD::ADD:
1193     case ISD::SUB:
1194     case ISD::MUL:
1195     case ISD::AND:
1196     case ISD::OR:
1197     case ISD::XOR:
1198       RV = PromoteIntBinOp(SDValue(N, 0));
1199       break;
1200     case ISD::SHL:
1201     case ISD::SRA:
1202     case ISD::SRL:
1203       RV = PromoteIntShiftOp(SDValue(N, 0));
1204       break;
1205     case ISD::SIGN_EXTEND:
1206     case ISD::ZERO_EXTEND:
1207     case ISD::ANY_EXTEND:
1208       RV = PromoteExtend(SDValue(N, 0));
1209       break;
1210     case ISD::LOAD:
1211       if (PromoteLoad(SDValue(N, 0)))
1212         RV = SDValue(N, 0);
1213       break;
1214     }
1215   }
1216
1217   // If N is a commutative binary node, try commuting it to enable more
1218   // sdisel CSE.
1219   if (RV.getNode() == 0 &&
1220       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1221       N->getNumValues() == 1) {
1222     SDValue N0 = N->getOperand(0);
1223     SDValue N1 = N->getOperand(1);
1224
1225     // Constant operands are canonicalized to RHS.
1226     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1227       SDValue Ops[] = { N1, N0 };
1228       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1229                                             Ops, 2);
1230       if (CSENode)
1231         return SDValue(CSENode, 0);
1232     }
1233   }
1234
1235   return RV;
1236 }
1237
1238 /// getInputChainForNode - Given a node, return its input chain if it has one,
1239 /// otherwise return a null sd operand.
1240 static SDValue getInputChainForNode(SDNode *N) {
1241   if (unsigned NumOps = N->getNumOperands()) {
1242     if (N->getOperand(0).getValueType() == MVT::Other)
1243       return N->getOperand(0);
1244     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1245       return N->getOperand(NumOps-1);
1246     for (unsigned i = 1; i < NumOps-1; ++i)
1247       if (N->getOperand(i).getValueType() == MVT::Other)
1248         return N->getOperand(i);
1249   }
1250   return SDValue();
1251 }
1252
1253 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1254   // If N has two operands, where one has an input chain equal to the other,
1255   // the 'other' chain is redundant.
1256   if (N->getNumOperands() == 2) {
1257     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1258       return N->getOperand(0);
1259     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1260       return N->getOperand(1);
1261   }
1262
1263   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1264   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1265   SmallPtrSet<SDNode*, 16> SeenOps;
1266   bool Changed = false;             // If we should replace this token factor.
1267
1268   // Start out with this token factor.
1269   TFs.push_back(N);
1270
1271   // Iterate through token factors.  The TFs grows when new token factors are
1272   // encountered.
1273   for (unsigned i = 0; i < TFs.size(); ++i) {
1274     SDNode *TF = TFs[i];
1275
1276     // Check each of the operands.
1277     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1278       SDValue Op = TF->getOperand(i);
1279
1280       switch (Op.getOpcode()) {
1281       case ISD::EntryToken:
1282         // Entry tokens don't need to be added to the list. They are
1283         // rededundant.
1284         Changed = true;
1285         break;
1286
1287       case ISD::TokenFactor:
1288         if (Op.hasOneUse() &&
1289             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1290           // Queue up for processing.
1291           TFs.push_back(Op.getNode());
1292           // Clean up in case the token factor is removed.
1293           AddToWorkList(Op.getNode());
1294           Changed = true;
1295           break;
1296         }
1297         // Fall thru
1298
1299       default:
1300         // Only add if it isn't already in the list.
1301         if (SeenOps.insert(Op.getNode()))
1302           Ops.push_back(Op);
1303         else
1304           Changed = true;
1305         break;
1306       }
1307     }
1308   }
1309
1310   SDValue Result;
1311
1312   // If we've change things around then replace token factor.
1313   if (Changed) {
1314     if (Ops.empty()) {
1315       // The entry token is the only possible outcome.
1316       Result = DAG.getEntryNode();
1317     } else {
1318       // New and improved token factor.
1319       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1320                            MVT::Other, &Ops[0], Ops.size());
1321     }
1322
1323     // Don't add users to work list.
1324     return CombineTo(N, Result, false);
1325   }
1326
1327   return Result;
1328 }
1329
1330 /// MERGE_VALUES can always be eliminated.
1331 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1332   WorkListRemover DeadNodes(*this);
1333   // Replacing results may cause a different MERGE_VALUES to suddenly
1334   // be CSE'd with N, and carry its uses with it. Iterate until no
1335   // uses remain, to ensure that the node can be safely deleted.
1336   // First add the users of this node to the work list so that they
1337   // can be tried again once they have new operands.
1338   AddUsersToWorkList(N);
1339   do {
1340     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1341       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1342   } while (!N->use_empty());
1343   removeFromWorkList(N);
1344   DAG.DeleteNode(N);
1345   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1346 }
1347
1348 static
1349 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1350                               SelectionDAG &DAG) {
1351   EVT VT = N0.getValueType();
1352   SDValue N00 = N0.getOperand(0);
1353   SDValue N01 = N0.getOperand(1);
1354   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1355
1356   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1357       isa<ConstantSDNode>(N00.getOperand(1))) {
1358     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1359     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1360                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1361                                  N00.getOperand(0), N01),
1362                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1363                                  N00.getOperand(1), N01));
1364     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1365   }
1366
1367   return SDValue();
1368 }
1369
1370 SDValue DAGCombiner::visitADD(SDNode *N) {
1371   SDValue N0 = N->getOperand(0);
1372   SDValue N1 = N->getOperand(1);
1373   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1374   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1375   EVT VT = N0.getValueType();
1376
1377   // fold vector ops
1378   if (VT.isVector()) {
1379     SDValue FoldedVOp = SimplifyVBinOp(N);
1380     if (FoldedVOp.getNode()) return FoldedVOp;
1381   }
1382
1383   // fold (add x, undef) -> undef
1384   if (N0.getOpcode() == ISD::UNDEF)
1385     return N0;
1386   if (N1.getOpcode() == ISD::UNDEF)
1387     return N1;
1388   // fold (add c1, c2) -> c1+c2
1389   if (N0C && N1C)
1390     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1391   // canonicalize constant to RHS
1392   if (N0C && !N1C)
1393     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1394   // fold (add x, 0) -> x
1395   if (N1C && N1C->isNullValue())
1396     return N0;
1397   // fold (add Sym, c) -> Sym+c
1398   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1399     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1400         GA->getOpcode() == ISD::GlobalAddress)
1401       return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1402                                   GA->getOffset() +
1403                                     (uint64_t)N1C->getSExtValue());
1404   // fold ((c1-A)+c2) -> (c1+c2)-A
1405   if (N1C && N0.getOpcode() == ISD::SUB)
1406     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1407       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1408                          DAG.getConstant(N1C->getAPIntValue()+
1409                                          N0C->getAPIntValue(), VT),
1410                          N0.getOperand(1));
1411   // reassociate add
1412   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1413   if (RADD.getNode() != 0)
1414     return RADD;
1415   // fold ((0-A) + B) -> B-A
1416   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1417       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1418     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1419   // fold (A + (0-B)) -> A-B
1420   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1421       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1422     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1423   // fold (A+(B-A)) -> B
1424   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1425     return N1.getOperand(0);
1426   // fold ((B-A)+A) -> B
1427   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1428     return N0.getOperand(0);
1429   // fold (A+(B-(A+C))) to (B-C)
1430   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1431       N0 == N1.getOperand(1).getOperand(0))
1432     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1433                        N1.getOperand(1).getOperand(1));
1434   // fold (A+(B-(C+A))) to (B-C)
1435   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1436       N0 == N1.getOperand(1).getOperand(1))
1437     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1438                        N1.getOperand(1).getOperand(0));
1439   // fold (A+((B-A)+or-C)) to (B+or-C)
1440   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1441       N1.getOperand(0).getOpcode() == ISD::SUB &&
1442       N0 == N1.getOperand(0).getOperand(1))
1443     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1444                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1445
1446   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1447   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1448     SDValue N00 = N0.getOperand(0);
1449     SDValue N01 = N0.getOperand(1);
1450     SDValue N10 = N1.getOperand(0);
1451     SDValue N11 = N1.getOperand(1);
1452
1453     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1454       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1455                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1456                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1457   }
1458
1459   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1460     return SDValue(N, 0);
1461
1462   // fold (a+b) -> (a|b) iff a and b share no bits.
1463   if (VT.isInteger() && !VT.isVector()) {
1464     APInt LHSZero, LHSOne;
1465     APInt RHSZero, RHSOne;
1466     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1467
1468     if (LHSZero.getBoolValue()) {
1469       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1470
1471       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1472       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1473       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1474         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1475     }
1476   }
1477
1478   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1479   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1480     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1481     if (Result.getNode()) return Result;
1482   }
1483   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1484     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1485     if (Result.getNode()) return Result;
1486   }
1487
1488   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1489   if (N1.getOpcode() == ISD::SHL &&
1490       N1.getOperand(0).getOpcode() == ISD::SUB)
1491     if (ConstantSDNode *C =
1492           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1493       if (C->getAPIntValue() == 0)
1494         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1495                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1496                                        N1.getOperand(0).getOperand(1),
1497                                        N1.getOperand(1)));
1498   if (N0.getOpcode() == ISD::SHL &&
1499       N0.getOperand(0).getOpcode() == ISD::SUB)
1500     if (ConstantSDNode *C =
1501           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1502       if (C->getAPIntValue() == 0)
1503         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1504                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1505                                        N0.getOperand(0).getOperand(1),
1506                                        N0.getOperand(1)));
1507
1508   if (N1.getOpcode() == ISD::AND) {
1509     SDValue AndOp0 = N1.getOperand(0);
1510     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1511     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1512     unsigned DestBits = VT.getScalarType().getSizeInBits();
1513
1514     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1515     // and similar xforms where the inner op is either ~0 or 0.
1516     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1517       DebugLoc DL = N->getDebugLoc();
1518       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1519     }
1520   }
1521
1522   // add (sext i1), X -> sub X, (zext i1)
1523   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1524       N0.getOperand(0).getValueType() == MVT::i1 &&
1525       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1526     DebugLoc DL = N->getDebugLoc();
1527     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1528     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1529   }
1530
1531   return SDValue();
1532 }
1533
1534 SDValue DAGCombiner::visitADDC(SDNode *N) {
1535   SDValue N0 = N->getOperand(0);
1536   SDValue N1 = N->getOperand(1);
1537   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1538   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1539   EVT VT = N0.getValueType();
1540
1541   // If the flag result is dead, turn this into an ADD.
1542   if (!N->hasAnyUseOfValue(1))
1543     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1544                      DAG.getNode(ISD::CARRY_FALSE,
1545                                  N->getDebugLoc(), MVT::Glue));
1546
1547   // canonicalize constant to RHS.
1548   if (N0C && !N1C)
1549     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1550
1551   // fold (addc x, 0) -> x + no carry out
1552   if (N1C && N1C->isNullValue())
1553     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1554                                         N->getDebugLoc(), MVT::Glue));
1555
1556   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1557   APInt LHSZero, LHSOne;
1558   APInt RHSZero, RHSOne;
1559   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1560
1561   if (LHSZero.getBoolValue()) {
1562     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1563
1564     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1565     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1566     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1567       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1568                        DAG.getNode(ISD::CARRY_FALSE,
1569                                    N->getDebugLoc(), MVT::Glue));
1570   }
1571
1572   return SDValue();
1573 }
1574
1575 SDValue DAGCombiner::visitADDE(SDNode *N) {
1576   SDValue N0 = N->getOperand(0);
1577   SDValue N1 = N->getOperand(1);
1578   SDValue CarryIn = N->getOperand(2);
1579   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1580   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1581
1582   // canonicalize constant to RHS
1583   if (N0C && !N1C)
1584     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1585                        N1, N0, CarryIn);
1586
1587   // fold (adde x, y, false) -> (addc x, y)
1588   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1589     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1590
1591   return SDValue();
1592 }
1593
1594 // Since it may not be valid to emit a fold to zero for vector initializers
1595 // check if we can before folding.
1596 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1597                              SelectionDAG &DAG, bool LegalOperations) {
1598   if (!VT.isVector()) {
1599     return DAG.getConstant(0, VT);
1600   }
1601   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1602     // Produce a vector of zeros.
1603     SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1604     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1605     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1606       &Ops[0], Ops.size());
1607   }
1608   return SDValue();
1609 }
1610
1611 SDValue DAGCombiner::visitSUB(SDNode *N) {
1612   SDValue N0 = N->getOperand(0);
1613   SDValue N1 = N->getOperand(1);
1614   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1615   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1616   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1617     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1618   EVT VT = N0.getValueType();
1619
1620   // fold vector ops
1621   if (VT.isVector()) {
1622     SDValue FoldedVOp = SimplifyVBinOp(N);
1623     if (FoldedVOp.getNode()) return FoldedVOp;
1624   }
1625
1626   // fold (sub x, x) -> 0
1627   // FIXME: Refactor this and xor and other similar operations together.
1628   if (N0 == N1)
1629     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1630   // fold (sub c1, c2) -> c1-c2
1631   if (N0C && N1C)
1632     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1633   // fold (sub x, c) -> (add x, -c)
1634   if (N1C)
1635     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1636                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1637   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1638   if (N0C && N0C->isAllOnesValue())
1639     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1640   // fold A-(A-B) -> B
1641   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1642     return N1.getOperand(1);
1643   // fold (A+B)-A -> B
1644   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1645     return N0.getOperand(1);
1646   // fold (A+B)-B -> A
1647   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1648     return N0.getOperand(0);
1649   // fold C2-(A+C1) -> (C2-C1)-A
1650   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1651     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1652                                    VT);
1653     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1654                        N1.getOperand(0));
1655   }
1656   // fold ((A+(B+or-C))-B) -> A+or-C
1657   if (N0.getOpcode() == ISD::ADD &&
1658       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1659        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1660       N0.getOperand(1).getOperand(0) == N1)
1661     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1662                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1663   // fold ((A+(C+B))-B) -> A+C
1664   if (N0.getOpcode() == ISD::ADD &&
1665       N0.getOperand(1).getOpcode() == ISD::ADD &&
1666       N0.getOperand(1).getOperand(1) == N1)
1667     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1668                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1669   // fold ((A-(B-C))-C) -> A-B
1670   if (N0.getOpcode() == ISD::SUB &&
1671       N0.getOperand(1).getOpcode() == ISD::SUB &&
1672       N0.getOperand(1).getOperand(1) == N1)
1673     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1674                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1675
1676   // If either operand of a sub is undef, the result is undef
1677   if (N0.getOpcode() == ISD::UNDEF)
1678     return N0;
1679   if (N1.getOpcode() == ISD::UNDEF)
1680     return N1;
1681
1682   // If the relocation model supports it, consider symbol offsets.
1683   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1684     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1685       // fold (sub Sym, c) -> Sym-c
1686       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1687         return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1688                                     GA->getOffset() -
1689                                       (uint64_t)N1C->getSExtValue());
1690       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1691       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1692         if (GA->getGlobal() == GB->getGlobal())
1693           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1694                                  VT);
1695     }
1696
1697   return SDValue();
1698 }
1699
1700 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1701   SDValue N0 = N->getOperand(0);
1702   SDValue N1 = N->getOperand(1);
1703   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1704   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1705   EVT VT = N0.getValueType();
1706
1707   // If the flag result is dead, turn this into an SUB.
1708   if (!N->hasAnyUseOfValue(1))
1709     return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1710                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1711                                  MVT::Glue));
1712
1713   // fold (subc x, x) -> 0 + no borrow
1714   if (N0 == N1)
1715     return CombineTo(N, DAG.getConstant(0, VT),
1716                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1717                                  MVT::Glue));
1718
1719   // fold (subc x, 0) -> x + no borrow
1720   if (N1C && N1C->isNullValue())
1721     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1722                                         MVT::Glue));
1723
1724   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1725   if (N0C && N0C->isAllOnesValue())
1726     return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1727                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1728                                  MVT::Glue));
1729
1730   return SDValue();
1731 }
1732
1733 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1734   SDValue N0 = N->getOperand(0);
1735   SDValue N1 = N->getOperand(1);
1736   SDValue CarryIn = N->getOperand(2);
1737
1738   // fold (sube x, y, false) -> (subc x, y)
1739   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1740     return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1741
1742   return SDValue();
1743 }
1744
1745 SDValue DAGCombiner::visitMUL(SDNode *N) {
1746   SDValue N0 = N->getOperand(0);
1747   SDValue N1 = N->getOperand(1);
1748   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1749   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1750   EVT VT = N0.getValueType();
1751
1752   // fold vector ops
1753   if (VT.isVector()) {
1754     SDValue FoldedVOp = SimplifyVBinOp(N);
1755     if (FoldedVOp.getNode()) return FoldedVOp;
1756   }
1757
1758   // fold (mul x, undef) -> 0
1759   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1760     return DAG.getConstant(0, VT);
1761   // fold (mul c1, c2) -> c1*c2
1762   if (N0C && N1C)
1763     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1764   // canonicalize constant to RHS
1765   if (N0C && !N1C)
1766     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1767   // fold (mul x, 0) -> 0
1768   if (N1C && N1C->isNullValue())
1769     return N1;
1770   // fold (mul x, -1) -> 0-x
1771   if (N1C && N1C->isAllOnesValue())
1772     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1773                        DAG.getConstant(0, VT), N0);
1774   // fold (mul x, (1 << c)) -> x << c
1775   if (N1C && N1C->getAPIntValue().isPowerOf2())
1776     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1777                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1778                                        getShiftAmountTy(N0.getValueType())));
1779   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1780   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1781     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1782     // FIXME: If the input is something that is easily negated (e.g. a
1783     // single-use add), we should put the negate there.
1784     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1785                        DAG.getConstant(0, VT),
1786                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1787                             DAG.getConstant(Log2Val,
1788                                       getShiftAmountTy(N0.getValueType()))));
1789   }
1790   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1791   if (N1C && N0.getOpcode() == ISD::SHL &&
1792       isa<ConstantSDNode>(N0.getOperand(1))) {
1793     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1794                              N1, N0.getOperand(1));
1795     AddToWorkList(C3.getNode());
1796     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1797                        N0.getOperand(0), C3);
1798   }
1799
1800   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1801   // use.
1802   {
1803     SDValue Sh(0,0), Y(0,0);
1804     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1805     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1806         N0.getNode()->hasOneUse()) {
1807       Sh = N0; Y = N1;
1808     } else if (N1.getOpcode() == ISD::SHL &&
1809                isa<ConstantSDNode>(N1.getOperand(1)) &&
1810                N1.getNode()->hasOneUse()) {
1811       Sh = N1; Y = N0;
1812     }
1813
1814     if (Sh.getNode()) {
1815       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1816                                 Sh.getOperand(0), Y);
1817       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1818                          Mul, Sh.getOperand(1));
1819     }
1820   }
1821
1822   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1823   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1824       isa<ConstantSDNode>(N0.getOperand(1)))
1825     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1826                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1827                                    N0.getOperand(0), N1),
1828                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1829                                    N0.getOperand(1), N1));
1830
1831   // reassociate mul
1832   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1833   if (RMUL.getNode() != 0)
1834     return RMUL;
1835
1836   return SDValue();
1837 }
1838
1839 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1840   SDValue N0 = N->getOperand(0);
1841   SDValue N1 = N->getOperand(1);
1842   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1843   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1844   EVT VT = N->getValueType(0);
1845
1846   // fold vector ops
1847   if (VT.isVector()) {
1848     SDValue FoldedVOp = SimplifyVBinOp(N);
1849     if (FoldedVOp.getNode()) return FoldedVOp;
1850   }
1851
1852   // fold (sdiv c1, c2) -> c1/c2
1853   if (N0C && N1C && !N1C->isNullValue())
1854     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1855   // fold (sdiv X, 1) -> X
1856   if (N1C && N1C->getAPIntValue() == 1LL)
1857     return N0;
1858   // fold (sdiv X, -1) -> 0-X
1859   if (N1C && N1C->isAllOnesValue())
1860     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1861                        DAG.getConstant(0, VT), N0);
1862   // If we know the sign bits of both operands are zero, strength reduce to a
1863   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1864   if (!VT.isVector()) {
1865     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1866       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1867                          N0, N1);
1868   }
1869   // fold (sdiv X, pow2) -> simple ops after legalize
1870   if (N1C && !N1C->isNullValue() &&
1871       (N1C->getAPIntValue().isPowerOf2() ||
1872        (-N1C->getAPIntValue()).isPowerOf2())) {
1873     // If dividing by powers of two is cheap, then don't perform the following
1874     // fold.
1875     if (TLI.isPow2DivCheap())
1876       return SDValue();
1877
1878     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1879
1880     // Splat the sign bit into the register
1881     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1882                               DAG.getConstant(VT.getSizeInBits()-1,
1883                                        getShiftAmountTy(N0.getValueType())));
1884     AddToWorkList(SGN.getNode());
1885
1886     // Add (N0 < 0) ? abs2 - 1 : 0;
1887     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1888                               DAG.getConstant(VT.getSizeInBits() - lg2,
1889                                        getShiftAmountTy(SGN.getValueType())));
1890     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1891     AddToWorkList(SRL.getNode());
1892     AddToWorkList(ADD.getNode());    // Divide by pow2
1893     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1894                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1895
1896     // If we're dividing by a positive value, we're done.  Otherwise, we must
1897     // negate the result.
1898     if (N1C->getAPIntValue().isNonNegative())
1899       return SRA;
1900
1901     AddToWorkList(SRA.getNode());
1902     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1903                        DAG.getConstant(0, VT), SRA);
1904   }
1905
1906   // if integer divide is expensive and we satisfy the requirements, emit an
1907   // alternate sequence.
1908   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1909     SDValue Op = BuildSDIV(N);
1910     if (Op.getNode()) return Op;
1911   }
1912
1913   // undef / X -> 0
1914   if (N0.getOpcode() == ISD::UNDEF)
1915     return DAG.getConstant(0, VT);
1916   // X / undef -> undef
1917   if (N1.getOpcode() == ISD::UNDEF)
1918     return N1;
1919
1920   return SDValue();
1921 }
1922
1923 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1924   SDValue N0 = N->getOperand(0);
1925   SDValue N1 = N->getOperand(1);
1926   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1927   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1928   EVT VT = N->getValueType(0);
1929
1930   // fold vector ops
1931   if (VT.isVector()) {
1932     SDValue FoldedVOp = SimplifyVBinOp(N);
1933     if (FoldedVOp.getNode()) return FoldedVOp;
1934   }
1935
1936   // fold (udiv c1, c2) -> c1/c2
1937   if (N0C && N1C && !N1C->isNullValue())
1938     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1939   // fold (udiv x, (1 << c)) -> x >>u c
1940   if (N1C && N1C->getAPIntValue().isPowerOf2())
1941     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1942                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1943                                        getShiftAmountTy(N0.getValueType())));
1944   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1945   if (N1.getOpcode() == ISD::SHL) {
1946     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1947       if (SHC->getAPIntValue().isPowerOf2()) {
1948         EVT ADDVT = N1.getOperand(1).getValueType();
1949         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1950                                   N1.getOperand(1),
1951                                   DAG.getConstant(SHC->getAPIntValue()
1952                                                                   .logBase2(),
1953                                                   ADDVT));
1954         AddToWorkList(Add.getNode());
1955         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1956       }
1957     }
1958   }
1959   // fold (udiv x, c) -> alternate
1960   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1961     SDValue Op = BuildUDIV(N);
1962     if (Op.getNode()) return Op;
1963   }
1964
1965   // undef / X -> 0
1966   if (N0.getOpcode() == ISD::UNDEF)
1967     return DAG.getConstant(0, VT);
1968   // X / undef -> undef
1969   if (N1.getOpcode() == ISD::UNDEF)
1970     return N1;
1971
1972   return SDValue();
1973 }
1974
1975 SDValue DAGCombiner::visitSREM(SDNode *N) {
1976   SDValue N0 = N->getOperand(0);
1977   SDValue N1 = N->getOperand(1);
1978   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1979   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1980   EVT VT = N->getValueType(0);
1981
1982   // fold (srem c1, c2) -> c1%c2
1983   if (N0C && N1C && !N1C->isNullValue())
1984     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1985   // If we know the sign bits of both operands are zero, strength reduce to a
1986   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1987   if (!VT.isVector()) {
1988     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1989       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1990   }
1991
1992   // If X/C can be simplified by the division-by-constant logic, lower
1993   // X%C to the equivalent of X-X/C*C.
1994   if (N1C && !N1C->isNullValue()) {
1995     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1996     AddToWorkList(Div.getNode());
1997     SDValue OptimizedDiv = combine(Div.getNode());
1998     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1999       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2000                                 OptimizedDiv, N1);
2001       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2002       AddToWorkList(Mul.getNode());
2003       return Sub;
2004     }
2005   }
2006
2007   // undef % X -> 0
2008   if (N0.getOpcode() == ISD::UNDEF)
2009     return DAG.getConstant(0, VT);
2010   // X % undef -> undef
2011   if (N1.getOpcode() == ISD::UNDEF)
2012     return N1;
2013
2014   return SDValue();
2015 }
2016
2017 SDValue DAGCombiner::visitUREM(SDNode *N) {
2018   SDValue N0 = N->getOperand(0);
2019   SDValue N1 = N->getOperand(1);
2020   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2021   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2022   EVT VT = N->getValueType(0);
2023
2024   // fold (urem c1, c2) -> c1%c2
2025   if (N0C && N1C && !N1C->isNullValue())
2026     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2027   // fold (urem x, pow2) -> (and x, pow2-1)
2028   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2029     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2030                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2031   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2032   if (N1.getOpcode() == ISD::SHL) {
2033     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2034       if (SHC->getAPIntValue().isPowerOf2()) {
2035         SDValue Add =
2036           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2037                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2038                                  VT));
2039         AddToWorkList(Add.getNode());
2040         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2041       }
2042     }
2043   }
2044
2045   // If X/C can be simplified by the division-by-constant logic, lower
2046   // X%C to the equivalent of X-X/C*C.
2047   if (N1C && !N1C->isNullValue()) {
2048     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2049     AddToWorkList(Div.getNode());
2050     SDValue OptimizedDiv = combine(Div.getNode());
2051     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2052       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2053                                 OptimizedDiv, N1);
2054       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2055       AddToWorkList(Mul.getNode());
2056       return Sub;
2057     }
2058   }
2059
2060   // undef % X -> 0
2061   if (N0.getOpcode() == ISD::UNDEF)
2062     return DAG.getConstant(0, VT);
2063   // X % undef -> undef
2064   if (N1.getOpcode() == ISD::UNDEF)
2065     return N1;
2066
2067   return SDValue();
2068 }
2069
2070 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2071   SDValue N0 = N->getOperand(0);
2072   SDValue N1 = N->getOperand(1);
2073   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2074   EVT VT = N->getValueType(0);
2075   DebugLoc DL = N->getDebugLoc();
2076
2077   // fold (mulhs x, 0) -> 0
2078   if (N1C && N1C->isNullValue())
2079     return N1;
2080   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2081   if (N1C && N1C->getAPIntValue() == 1)
2082     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2083                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2084                                        getShiftAmountTy(N0.getValueType())));
2085   // fold (mulhs x, undef) -> 0
2086   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2087     return DAG.getConstant(0, VT);
2088
2089   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2090   // plus a shift.
2091   if (VT.isSimple() && !VT.isVector()) {
2092     MVT Simple = VT.getSimpleVT();
2093     unsigned SimpleSize = Simple.getSizeInBits();
2094     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2095     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2096       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2097       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2098       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2099       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2100             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2101       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2102     }
2103   }
2104
2105   return SDValue();
2106 }
2107
2108 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2109   SDValue N0 = N->getOperand(0);
2110   SDValue N1 = N->getOperand(1);
2111   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2112   EVT VT = N->getValueType(0);
2113   DebugLoc DL = N->getDebugLoc();
2114
2115   // fold (mulhu x, 0) -> 0
2116   if (N1C && N1C->isNullValue())
2117     return N1;
2118   // fold (mulhu x, 1) -> 0
2119   if (N1C && N1C->getAPIntValue() == 1)
2120     return DAG.getConstant(0, N0.getValueType());
2121   // fold (mulhu x, undef) -> 0
2122   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2123     return DAG.getConstant(0, VT);
2124
2125   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2126   // plus a shift.
2127   if (VT.isSimple() && !VT.isVector()) {
2128     MVT Simple = VT.getSimpleVT();
2129     unsigned SimpleSize = Simple.getSizeInBits();
2130     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2131     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2132       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2133       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2134       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2135       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2136             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2137       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2138     }
2139   }
2140
2141   return SDValue();
2142 }
2143
2144 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2145 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2146 /// that are being performed. Return true if a simplification was made.
2147 ///
2148 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2149                                                 unsigned HiOp) {
2150   // If the high half is not needed, just compute the low half.
2151   bool HiExists = N->hasAnyUseOfValue(1);
2152   if (!HiExists &&
2153       (!LegalOperations ||
2154        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2155     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2156                               N->op_begin(), N->getNumOperands());
2157     return CombineTo(N, Res, Res);
2158   }
2159
2160   // If the low half is not needed, just compute the high half.
2161   bool LoExists = N->hasAnyUseOfValue(0);
2162   if (!LoExists &&
2163       (!LegalOperations ||
2164        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2165     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2166                               N->op_begin(), N->getNumOperands());
2167     return CombineTo(N, Res, Res);
2168   }
2169
2170   // If both halves are used, return as it is.
2171   if (LoExists && HiExists)
2172     return SDValue();
2173
2174   // If the two computed results can be simplified separately, separate them.
2175   if (LoExists) {
2176     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2177                              N->op_begin(), N->getNumOperands());
2178     AddToWorkList(Lo.getNode());
2179     SDValue LoOpt = combine(Lo.getNode());
2180     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2181         (!LegalOperations ||
2182          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2183       return CombineTo(N, LoOpt, LoOpt);
2184   }
2185
2186   if (HiExists) {
2187     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2188                              N->op_begin(), N->getNumOperands());
2189     AddToWorkList(Hi.getNode());
2190     SDValue HiOpt = combine(Hi.getNode());
2191     if (HiOpt.getNode() && HiOpt != Hi &&
2192         (!LegalOperations ||
2193          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2194       return CombineTo(N, HiOpt, HiOpt);
2195   }
2196
2197   return SDValue();
2198 }
2199
2200 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2201   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2202   if (Res.getNode()) return Res;
2203
2204   EVT VT = N->getValueType(0);
2205   DebugLoc DL = N->getDebugLoc();
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       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2215       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2216       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2217       // Compute the high part as N1.
2218       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2219             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2220       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2221       // Compute the low part as N0.
2222       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2223       return CombineTo(N, Lo, Hi);
2224     }
2225   }
2226
2227   return SDValue();
2228 }
2229
2230 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2231   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2232   if (Res.getNode()) return Res;
2233
2234   EVT VT = N->getValueType(0);
2235   DebugLoc DL = N->getDebugLoc();
2236
2237   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2238   // plus a shift.
2239   if (VT.isSimple() && !VT.isVector()) {
2240     MVT Simple = VT.getSimpleVT();
2241     unsigned SimpleSize = Simple.getSizeInBits();
2242     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2243     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2244       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2245       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2246       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2247       // Compute the high part as N1.
2248       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2249             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2250       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2251       // Compute the low part as N0.
2252       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2253       return CombineTo(N, Lo, Hi);
2254     }
2255   }
2256
2257   return SDValue();
2258 }
2259
2260 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2261   // (smulo x, 2) -> (saddo x, x)
2262   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2263     if (C2->getAPIntValue() == 2)
2264       return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2265                          N->getOperand(0), N->getOperand(0));
2266
2267   return SDValue();
2268 }
2269
2270 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2271   // (umulo x, 2) -> (uaddo x, x)
2272   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2273     if (C2->getAPIntValue() == 2)
2274       return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2275                          N->getOperand(0), N->getOperand(0));
2276
2277   return SDValue();
2278 }
2279
2280 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2281   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2282   if (Res.getNode()) return Res;
2283
2284   return SDValue();
2285 }
2286
2287 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2288   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2289   if (Res.getNode()) return Res;
2290
2291   return SDValue();
2292 }
2293
2294 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2295 /// two operands of the same opcode, try to simplify it.
2296 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2297   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2298   EVT VT = N0.getValueType();
2299   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2300
2301   // Bail early if none of these transforms apply.
2302   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2303
2304   // For each of OP in AND/OR/XOR:
2305   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2306   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2307   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2308   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2309   //
2310   // do not sink logical op inside of a vector extend, since it may combine
2311   // into a vsetcc.
2312   EVT Op0VT = N0.getOperand(0).getValueType();
2313   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2314        N0.getOpcode() == ISD::SIGN_EXTEND ||
2315        // Avoid infinite looping with PromoteIntBinOp.
2316        (N0.getOpcode() == ISD::ANY_EXTEND &&
2317         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2318        (N0.getOpcode() == ISD::TRUNCATE &&
2319         (!TLI.isZExtFree(VT, Op0VT) ||
2320          !TLI.isTruncateFree(Op0VT, VT)) &&
2321         TLI.isTypeLegal(Op0VT))) &&
2322       !VT.isVector() &&
2323       Op0VT == N1.getOperand(0).getValueType() &&
2324       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2325     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2326                                  N0.getOperand(0).getValueType(),
2327                                  N0.getOperand(0), N1.getOperand(0));
2328     AddToWorkList(ORNode.getNode());
2329     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2330   }
2331
2332   // For each of OP in SHL/SRL/SRA/AND...
2333   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2334   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2335   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2336   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2337        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2338       N0.getOperand(1) == N1.getOperand(1)) {
2339     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2340                                  N0.getOperand(0).getValueType(),
2341                                  N0.getOperand(0), N1.getOperand(0));
2342     AddToWorkList(ORNode.getNode());
2343     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2344                        ORNode, N0.getOperand(1));
2345   }
2346
2347   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2348   // Only perform this optimization after type legalization and before
2349   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2350   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2351   // we don't want to undo this promotion.
2352   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2353   // on scalars.
2354   if ((N0.getOpcode() == ISD::BITCAST ||
2355        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2356       Level == AfterLegalizeTypes) {
2357     SDValue In0 = N0.getOperand(0);
2358     SDValue In1 = N1.getOperand(0);
2359     EVT In0Ty = In0.getValueType();
2360     EVT In1Ty = In1.getValueType();
2361     DebugLoc DL = N->getDebugLoc();
2362     // If both incoming values are integers, and the original types are the
2363     // same.
2364     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2365       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2366       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2367       AddToWorkList(Op.getNode());
2368       return BC;
2369     }
2370   }
2371
2372   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2373   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2374   // If both shuffles use the same mask, and both shuffle within a single
2375   // vector, then it is worthwhile to move the swizzle after the operation.
2376   // The type-legalizer generates this pattern when loading illegal
2377   // vector types from memory. In many cases this allows additional shuffle
2378   // optimizations.
2379   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2380       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2381       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2382     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2383     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2384
2385     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2386            "Inputs to shuffles are not the same type");
2387
2388     unsigned NumElts = VT.getVectorNumElements();
2389
2390     // Check that both shuffles use the same mask. The masks are known to be of
2391     // the same length because the result vector type is the same.
2392     bool SameMask = true;
2393     for (unsigned i = 0; i != NumElts; ++i) {
2394       int Idx0 = SVN0->getMaskElt(i);
2395       int Idx1 = SVN1->getMaskElt(i);
2396       if (Idx0 != Idx1) {
2397         SameMask = false;
2398         break;
2399       }
2400     }
2401
2402     if (SameMask) {
2403       SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2404                                N0.getOperand(0), N1.getOperand(0));
2405       AddToWorkList(Op.getNode());
2406       return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2407                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2408     }
2409   }
2410
2411   return SDValue();
2412 }
2413
2414 SDValue DAGCombiner::visitAND(SDNode *N) {
2415   SDValue N0 = N->getOperand(0);
2416   SDValue N1 = N->getOperand(1);
2417   SDValue LL, LR, RL, RR, CC0, CC1;
2418   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2419   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2420   EVT VT = N1.getValueType();
2421   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2422
2423   // fold vector ops
2424   if (VT.isVector()) {
2425     SDValue FoldedVOp = SimplifyVBinOp(N);
2426     if (FoldedVOp.getNode()) return FoldedVOp;
2427   }
2428
2429   // fold (and x, undef) -> 0
2430   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2431     return DAG.getConstant(0, VT);
2432   // fold (and c1, c2) -> c1&c2
2433   if (N0C && N1C)
2434     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2435   // canonicalize constant to RHS
2436   if (N0C && !N1C)
2437     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2438   // fold (and x, -1) -> x
2439   if (N1C && N1C->isAllOnesValue())
2440     return N0;
2441   // if (and x, c) is known to be zero, return 0
2442   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2443                                    APInt::getAllOnesValue(BitWidth)))
2444     return DAG.getConstant(0, VT);
2445   // reassociate and
2446   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2447   if (RAND.getNode() != 0)
2448     return RAND;
2449   // fold (and (or x, C), D) -> D if (C & D) == D
2450   if (N1C && N0.getOpcode() == ISD::OR)
2451     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2452       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2453         return N1;
2454   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2455   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2456     SDValue N0Op0 = N0.getOperand(0);
2457     APInt Mask = ~N1C->getAPIntValue();
2458     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2459     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2460       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2461                                  N0.getValueType(), N0Op0);
2462
2463       // Replace uses of the AND with uses of the Zero extend node.
2464       CombineTo(N, Zext);
2465
2466       // We actually want to replace all uses of the any_extend with the
2467       // zero_extend, to avoid duplicating things.  This will later cause this
2468       // AND to be folded.
2469       CombineTo(N0.getNode(), Zext);
2470       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2471     }
2472   }
2473   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 
2474   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2475   // already be zero by virtue of the width of the base type of the load.
2476   //
2477   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2478   // more cases.
2479   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2480        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2481       N0.getOpcode() == ISD::LOAD) {
2482     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2483                                          N0 : N0.getOperand(0) );
2484
2485     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2486     // This can be a pure constant or a vector splat, in which case we treat the
2487     // vector as a scalar and use the splat value.
2488     APInt Constant = APInt::getNullValue(1);
2489     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2490       Constant = C->getAPIntValue();
2491     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2492       APInt SplatValue, SplatUndef;
2493       unsigned SplatBitSize;
2494       bool HasAnyUndefs;
2495       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2496                                              SplatBitSize, HasAnyUndefs);
2497       if (IsSplat) {
2498         // Undef bits can contribute to a possible optimisation if set, so
2499         // set them.
2500         SplatValue |= SplatUndef;
2501
2502         // The splat value may be something like "0x00FFFFFF", which means 0 for
2503         // the first vector value and FF for the rest, repeating. We need a mask
2504         // that will apply equally to all members of the vector, so AND all the
2505         // lanes of the constant together.
2506         EVT VT = Vector->getValueType(0);
2507         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2508
2509         // If the splat value has been compressed to a bitlength lower
2510         // than the size of the vector lane, we need to re-expand it to
2511         // the lane size.
2512         if (BitWidth > SplatBitSize)
2513           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2514                SplatBitSize < BitWidth;
2515                SplatBitSize = SplatBitSize * 2)
2516             SplatValue |= SplatValue.shl(SplatBitSize);
2517
2518         Constant = APInt::getAllOnesValue(BitWidth);
2519         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2520           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2521       }
2522     }
2523
2524     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2525     // actually legal and isn't going to get expanded, else this is a false
2526     // optimisation.
2527     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2528                                                     Load->getMemoryVT());
2529
2530     // Resize the constant to the same size as the original memory access before
2531     // extension. If it is still the AllOnesValue then this AND is completely
2532     // unneeded.
2533     Constant =
2534       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2535
2536     bool B;
2537     switch (Load->getExtensionType()) {
2538     default: B = false; break;
2539     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2540     case ISD::ZEXTLOAD:
2541     case ISD::NON_EXTLOAD: B = true; break;
2542     }
2543
2544     if (B && Constant.isAllOnesValue()) {
2545       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2546       // preserve semantics once we get rid of the AND.
2547       SDValue NewLoad(Load, 0);
2548       if (Load->getExtensionType() == ISD::EXTLOAD) {
2549         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2550                               Load->getValueType(0), Load->getDebugLoc(),
2551                               Load->getChain(), Load->getBasePtr(),
2552                               Load->getOffset(), Load->getMemoryVT(),
2553                               Load->getMemOperand());
2554         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2555         if (Load->getNumValues() == 3) {
2556           // PRE/POST_INC loads have 3 values.
2557           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2558                            NewLoad.getValue(2) };
2559           CombineTo(Load, To, 3, true);
2560         } else {
2561           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2562         }
2563       }
2564
2565       // Fold the AND away, taking care not to fold to the old load node if we
2566       // replaced it.
2567       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2568
2569       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2570     }
2571   }
2572   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2573   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2574     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2575     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2576
2577     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2578         LL.getValueType().isInteger()) {
2579       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2580       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2581         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2582                                      LR.getValueType(), LL, RL);
2583         AddToWorkList(ORNode.getNode());
2584         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2585       }
2586       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2587       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2588         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2589                                       LR.getValueType(), LL, RL);
2590         AddToWorkList(ANDNode.getNode());
2591         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2592       }
2593       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2594       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2595         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2596                                      LR.getValueType(), LL, RL);
2597         AddToWorkList(ORNode.getNode());
2598         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2599       }
2600     }
2601     // canonicalize equivalent to ll == rl
2602     if (LL == RR && LR == RL) {
2603       Op1 = ISD::getSetCCSwappedOperands(Op1);
2604       std::swap(RL, RR);
2605     }
2606     if (LL == RL && LR == RR) {
2607       bool isInteger = LL.getValueType().isInteger();
2608       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2609       if (Result != ISD::SETCC_INVALID &&
2610           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2611         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2612                             LL, LR, Result);
2613     }
2614   }
2615
2616   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2617   if (N0.getOpcode() == N1.getOpcode()) {
2618     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2619     if (Tmp.getNode()) return Tmp;
2620   }
2621
2622   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2623   // fold (and (sra)) -> (and (srl)) when possible.
2624   if (!VT.isVector() &&
2625       SimplifyDemandedBits(SDValue(N, 0)))
2626     return SDValue(N, 0);
2627
2628   // fold (zext_inreg (extload x)) -> (zextload x)
2629   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2630     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2631     EVT MemVT = LN0->getMemoryVT();
2632     // If we zero all the possible extended bits, then we can turn this into
2633     // a zextload if we are running before legalize or the operation is legal.
2634     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2635     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2636                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2637         ((!LegalOperations && !LN0->isVolatile()) ||
2638          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2639       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2640                                        LN0->getChain(), LN0->getBasePtr(),
2641                                        LN0->getPointerInfo(), MemVT,
2642                                        LN0->isVolatile(), LN0->isNonTemporal(),
2643                                        LN0->getAlignment());
2644       AddToWorkList(N);
2645       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2646       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2647     }
2648   }
2649   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2650   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2651       N0.hasOneUse()) {
2652     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2653     EVT MemVT = LN0->getMemoryVT();
2654     // If we zero all the possible extended bits, then we can turn this into
2655     // a zextload if we are running before legalize or the operation is legal.
2656     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2657     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2658                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2659         ((!LegalOperations && !LN0->isVolatile()) ||
2660          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2661       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2662                                        LN0->getChain(),
2663                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2664                                        MemVT,
2665                                        LN0->isVolatile(), LN0->isNonTemporal(),
2666                                        LN0->getAlignment());
2667       AddToWorkList(N);
2668       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2669       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2670     }
2671   }
2672
2673   // fold (and (load x), 255) -> (zextload x, i8)
2674   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2675   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2676   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2677               (N0.getOpcode() == ISD::ANY_EXTEND &&
2678                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2679     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2680     LoadSDNode *LN0 = HasAnyExt
2681       ? cast<LoadSDNode>(N0.getOperand(0))
2682       : cast<LoadSDNode>(N0);
2683     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2684         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2685       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2686       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2687         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2688         EVT LoadedVT = LN0->getMemoryVT();
2689
2690         if (ExtVT == LoadedVT &&
2691             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2692           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2693
2694           SDValue NewLoad =
2695             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2696                            LN0->getChain(), LN0->getBasePtr(),
2697                            LN0->getPointerInfo(),
2698                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2699                            LN0->getAlignment());
2700           AddToWorkList(N);
2701           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2702           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2703         }
2704
2705         // Do not change the width of a volatile load.
2706         // Do not generate loads of non-round integer types since these can
2707         // be expensive (and would be wrong if the type is not byte sized).
2708         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2709             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2710           EVT PtrType = LN0->getOperand(1).getValueType();
2711
2712           unsigned Alignment = LN0->getAlignment();
2713           SDValue NewPtr = LN0->getBasePtr();
2714
2715           // For big endian targets, we need to add an offset to the pointer
2716           // to load the correct bytes.  For little endian systems, we merely
2717           // need to read fewer bytes from the same pointer.
2718           if (TLI.isBigEndian()) {
2719             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2720             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2721             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2722             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2723                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2724             Alignment = MinAlign(Alignment, PtrOff);
2725           }
2726
2727           AddToWorkList(NewPtr.getNode());
2728
2729           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2730           SDValue Load =
2731             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2732                            LN0->getChain(), NewPtr,
2733                            LN0->getPointerInfo(),
2734                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2735                            Alignment);
2736           AddToWorkList(N);
2737           CombineTo(LN0, Load, Load.getValue(1));
2738           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2739         }
2740       }
2741     }
2742   }
2743
2744   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2745       VT.getSizeInBits() <= 64) {
2746     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2747       APInt ADDC = ADDI->getAPIntValue();
2748       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2749         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2750         // immediate for an add, but it is legal if its top c2 bits are set,
2751         // transform the ADD so the immediate doesn't need to be materialized
2752         // in a register.
2753         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2754           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2755                                              SRLI->getZExtValue());
2756           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2757             ADDC |= Mask;
2758             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2759               SDValue NewAdd =
2760                 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2761                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2762               CombineTo(N0.getNode(), NewAdd);
2763               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2764             }
2765           }
2766         }
2767       }
2768     }
2769   }
2770       
2771
2772   return SDValue();
2773 }
2774
2775 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2776 ///
2777 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2778                                         bool DemandHighBits) {
2779   if (!LegalOperations)
2780     return SDValue();
2781
2782   EVT VT = N->getValueType(0);
2783   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2784     return SDValue();
2785   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2786     return SDValue();
2787
2788   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2789   bool LookPassAnd0 = false;
2790   bool LookPassAnd1 = false;
2791   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2792       std::swap(N0, N1);
2793   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2794       std::swap(N0, N1);
2795   if (N0.getOpcode() == ISD::AND) {
2796     if (!N0.getNode()->hasOneUse())
2797       return SDValue();
2798     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2799     if (!N01C || N01C->getZExtValue() != 0xFF00)
2800       return SDValue();
2801     N0 = N0.getOperand(0);
2802     LookPassAnd0 = true;
2803   }
2804
2805   if (N1.getOpcode() == ISD::AND) {
2806     if (!N1.getNode()->hasOneUse())
2807       return SDValue();
2808     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2809     if (!N11C || N11C->getZExtValue() != 0xFF)
2810       return SDValue();
2811     N1 = N1.getOperand(0);
2812     LookPassAnd1 = true;
2813   }
2814
2815   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2816     std::swap(N0, N1);
2817   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2818     return SDValue();
2819   if (!N0.getNode()->hasOneUse() ||
2820       !N1.getNode()->hasOneUse())
2821     return SDValue();
2822
2823   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2824   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2825   if (!N01C || !N11C)
2826     return SDValue();
2827   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2828     return SDValue();
2829
2830   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2831   SDValue N00 = N0->getOperand(0);
2832   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2833     if (!N00.getNode()->hasOneUse())
2834       return SDValue();
2835     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2836     if (!N001C || N001C->getZExtValue() != 0xFF)
2837       return SDValue();
2838     N00 = N00.getOperand(0);
2839     LookPassAnd0 = true;
2840   }
2841
2842   SDValue N10 = N1->getOperand(0);
2843   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2844     if (!N10.getNode()->hasOneUse())
2845       return SDValue();
2846     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2847     if (!N101C || N101C->getZExtValue() != 0xFF00)
2848       return SDValue();
2849     N10 = N10.getOperand(0);
2850     LookPassAnd1 = true;
2851   }
2852
2853   if (N00 != N10)
2854     return SDValue();
2855
2856   // Make sure everything beyond the low halfword is zero since the SRL 16
2857   // will clear the top bits.
2858   unsigned OpSizeInBits = VT.getSizeInBits();
2859   if (DemandHighBits && OpSizeInBits > 16 &&
2860       (!LookPassAnd0 || !LookPassAnd1) &&
2861       !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2862     return SDValue();
2863
2864   SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2865   if (OpSizeInBits > 16)
2866     Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2867                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2868   return Res;
2869 }
2870
2871 /// isBSwapHWordElement - Return true if the specified node is an element
2872 /// that makes up a 32-bit packed halfword byteswap. i.e.
2873 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2874 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2875   if (!N.getNode()->hasOneUse())
2876     return false;
2877
2878   unsigned Opc = N.getOpcode();
2879   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2880     return false;
2881
2882   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2883   if (!N1C)
2884     return false;
2885
2886   unsigned Num;
2887   switch (N1C->getZExtValue()) {
2888   default:
2889     return false;
2890   case 0xFF:       Num = 0; break;
2891   case 0xFF00:     Num = 1; break;
2892   case 0xFF0000:   Num = 2; break;
2893   case 0xFF000000: Num = 3; break;
2894   }
2895
2896   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2897   SDValue N0 = N.getOperand(0);
2898   if (Opc == ISD::AND) {
2899     if (Num == 0 || Num == 2) {
2900       // (x >> 8) & 0xff
2901       // (x >> 8) & 0xff0000
2902       if (N0.getOpcode() != ISD::SRL)
2903         return false;
2904       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2905       if (!C || C->getZExtValue() != 8)
2906         return false;
2907     } else {
2908       // (x << 8) & 0xff00
2909       // (x << 8) & 0xff000000
2910       if (N0.getOpcode() != ISD::SHL)
2911         return false;
2912       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2913       if (!C || C->getZExtValue() != 8)
2914         return false;
2915     }
2916   } else if (Opc == ISD::SHL) {
2917     // (x & 0xff) << 8
2918     // (x & 0xff0000) << 8
2919     if (Num != 0 && Num != 2)
2920       return false;
2921     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2922     if (!C || C->getZExtValue() != 8)
2923       return false;
2924   } else { // Opc == ISD::SRL
2925     // (x & 0xff00) >> 8
2926     // (x & 0xff000000) >> 8
2927     if (Num != 1 && Num != 3)
2928       return false;
2929     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2930     if (!C || C->getZExtValue() != 8)
2931       return false;
2932   }
2933
2934   if (Parts[Num])
2935     return false;
2936
2937   Parts[Num] = N0.getOperand(0).getNode();
2938   return true;
2939 }
2940
2941 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2942 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2943 /// => (rotl (bswap x), 16)
2944 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2945   if (!LegalOperations)
2946     return SDValue();
2947
2948   EVT VT = N->getValueType(0);
2949   if (VT != MVT::i32)
2950     return SDValue();
2951   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2952     return SDValue();
2953
2954   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2955   // Look for either
2956   // (or (or (and), (and)), (or (and), (and)))
2957   // (or (or (or (and), (and)), (and)), (and))
2958   if (N0.getOpcode() != ISD::OR)
2959     return SDValue();
2960   SDValue N00 = N0.getOperand(0);
2961   SDValue N01 = N0.getOperand(1);
2962
2963   if (N1.getOpcode() == ISD::OR) {
2964     // (or (or (and), (and)), (or (and), (and)))
2965     SDValue N000 = N00.getOperand(0);
2966     if (!isBSwapHWordElement(N000, Parts))
2967       return SDValue();
2968
2969     SDValue N001 = N00.getOperand(1);
2970     if (!isBSwapHWordElement(N001, Parts))
2971       return SDValue();
2972     SDValue N010 = N01.getOperand(0);
2973     if (!isBSwapHWordElement(N010, Parts))
2974       return SDValue();
2975     SDValue N011 = N01.getOperand(1);
2976     if (!isBSwapHWordElement(N011, Parts))
2977       return SDValue();
2978   } else {
2979     // (or (or (or (and), (and)), (and)), (and))
2980     if (!isBSwapHWordElement(N1, Parts))
2981       return SDValue();
2982     if (!isBSwapHWordElement(N01, Parts))
2983       return SDValue();
2984     if (N00.getOpcode() != ISD::OR)
2985       return SDValue();
2986     SDValue N000 = N00.getOperand(0);
2987     if (!isBSwapHWordElement(N000, Parts))
2988       return SDValue();
2989     SDValue N001 = N00.getOperand(1);
2990     if (!isBSwapHWordElement(N001, Parts))
2991       return SDValue();
2992   }
2993
2994   // Make sure the parts are all coming from the same node.
2995   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2996     return SDValue();
2997
2998   SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
2999                               SDValue(Parts[0],0));
3000
3001   // Result of the bswap should be rotated by 16. If it's not legal, than
3002   // do  (x << 16) | (x >> 16).
3003   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3004   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3005     return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
3006   else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3007     return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
3008   return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
3009                      DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
3010                      DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
3011 }
3012
3013 SDValue DAGCombiner::visitOR(SDNode *N) {
3014   SDValue N0 = N->getOperand(0);
3015   SDValue N1 = N->getOperand(1);
3016   SDValue LL, LR, RL, RR, CC0, CC1;
3017   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3018   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3019   EVT VT = N1.getValueType();
3020
3021   // fold vector ops
3022   if (VT.isVector()) {
3023     SDValue FoldedVOp = SimplifyVBinOp(N);
3024     if (FoldedVOp.getNode()) return FoldedVOp;
3025   }
3026
3027   // fold (or x, undef) -> -1
3028   if (!LegalOperations &&
3029       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3030     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3031     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3032   }
3033   // fold (or c1, c2) -> c1|c2
3034   if (N0C && N1C)
3035     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3036   // canonicalize constant to RHS
3037   if (N0C && !N1C)
3038     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3039   // fold (or x, 0) -> x
3040   if (N1C && N1C->isNullValue())
3041     return N0;
3042   // fold (or x, -1) -> -1
3043   if (N1C && N1C->isAllOnesValue())
3044     return N1;
3045   // fold (or x, c) -> c iff (x & ~c) == 0
3046   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3047     return N1;
3048
3049   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3050   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3051   if (BSwap.getNode() != 0)
3052     return BSwap;
3053   BSwap = MatchBSwapHWordLow(N, N0, N1);
3054   if (BSwap.getNode() != 0)
3055     return BSwap;
3056
3057   // reassociate or
3058   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3059   if (ROR.getNode() != 0)
3060     return ROR;
3061   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3062   // iff (c1 & c2) == 0.
3063   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3064              isa<ConstantSDNode>(N0.getOperand(1))) {
3065     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3066     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3067       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3068                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3069                                      N0.getOperand(0), N1),
3070                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3071   }
3072   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3073   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3074     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3075     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3076
3077     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3078         LL.getValueType().isInteger()) {
3079       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3080       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3081       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3082           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3083         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3084                                      LR.getValueType(), LL, RL);
3085         AddToWorkList(ORNode.getNode());
3086         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3087       }
3088       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3089       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3090       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3091           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3092         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3093                                       LR.getValueType(), LL, RL);
3094         AddToWorkList(ANDNode.getNode());
3095         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3096       }
3097     }
3098     // canonicalize equivalent to ll == rl
3099     if (LL == RR && LR == RL) {
3100       Op1 = ISD::getSetCCSwappedOperands(Op1);
3101       std::swap(RL, RR);
3102     }
3103     if (LL == RL && LR == RR) {
3104       bool isInteger = LL.getValueType().isInteger();
3105       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3106       if (Result != ISD::SETCC_INVALID &&
3107           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
3108         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3109                             LL, LR, Result);
3110     }
3111   }
3112
3113   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3114   if (N0.getOpcode() == N1.getOpcode()) {
3115     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3116     if (Tmp.getNode()) return Tmp;
3117   }
3118
3119   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3120   if (N0.getOpcode() == ISD::AND &&
3121       N1.getOpcode() == ISD::AND &&
3122       N0.getOperand(1).getOpcode() == ISD::Constant &&
3123       N1.getOperand(1).getOpcode() == ISD::Constant &&
3124       // Don't increase # computations.
3125       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3126     // We can only do this xform if we know that bits from X that are set in C2
3127     // but not in C1 are already zero.  Likewise for Y.
3128     const APInt &LHSMask =
3129       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3130     const APInt &RHSMask =
3131       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3132
3133     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3134         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3135       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3136                               N0.getOperand(0), N1.getOperand(0));
3137       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3138                          DAG.getConstant(LHSMask | RHSMask, VT));
3139     }
3140   }
3141
3142   // See if this is some rotate idiom.
3143   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3144     return SDValue(Rot, 0);
3145
3146   // Simplify the operands using demanded-bits information.
3147   if (!VT.isVector() &&
3148       SimplifyDemandedBits(SDValue(N, 0)))
3149     return SDValue(N, 0);
3150
3151   return SDValue();
3152 }
3153
3154 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3155 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3156   if (Op.getOpcode() == ISD::AND) {
3157     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3158       Mask = Op.getOperand(1);
3159       Op = Op.getOperand(0);
3160     } else {
3161       return false;
3162     }
3163   }
3164
3165   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3166     Shift = Op;
3167     return true;
3168   }
3169
3170   return false;
3171 }
3172
3173 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3174 // idioms for rotate, and if the target supports rotation instructions, generate
3175 // a rot[lr].
3176 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3177   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3178   EVT VT = LHS.getValueType();
3179   if (!TLI.isTypeLegal(VT)) return 0;
3180
3181   // The target must have at least one rotate flavor.
3182   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3183   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3184   if (!HasROTL && !HasROTR) return 0;
3185
3186   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3187   SDValue LHSShift;   // The shift.
3188   SDValue LHSMask;    // AND value if any.
3189   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3190     return 0; // Not part of a rotate.
3191
3192   SDValue RHSShift;   // The shift.
3193   SDValue RHSMask;    // AND value if any.
3194   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3195     return 0; // Not part of a rotate.
3196
3197   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3198     return 0;   // Not shifting the same value.
3199
3200   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3201     return 0;   // Shifts must disagree.
3202
3203   // Canonicalize shl to left side in a shl/srl pair.
3204   if (RHSShift.getOpcode() == ISD::SHL) {
3205     std::swap(LHS, RHS);
3206     std::swap(LHSShift, RHSShift);
3207     std::swap(LHSMask , RHSMask );
3208   }
3209
3210   unsigned OpSizeInBits = VT.getSizeInBits();
3211   SDValue LHSShiftArg = LHSShift.getOperand(0);
3212   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3213   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3214
3215   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3216   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3217   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3218       RHSShiftAmt.getOpcode() == ISD::Constant) {
3219     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3220     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3221     if ((LShVal + RShVal) != OpSizeInBits)
3222       return 0;
3223
3224     SDValue Rot;
3225     if (HasROTL)
3226       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
3227     else
3228       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
3229
3230     // If there is an AND of either shifted operand, apply it to the result.
3231     if (LHSMask.getNode() || RHSMask.getNode()) {
3232       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3233
3234       if (LHSMask.getNode()) {
3235         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3236         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3237       }
3238       if (RHSMask.getNode()) {
3239         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3240         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3241       }
3242
3243       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3244     }
3245
3246     return Rot.getNode();
3247   }
3248
3249   // If there is a mask here, and we have a variable shift, we can't be sure
3250   // that we're masking out the right stuff.
3251   if (LHSMask.getNode() || RHSMask.getNode())
3252     return 0;
3253
3254   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3255   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3256   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3257       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3258     if (ConstantSDNode *SUBC =
3259           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3260       if (SUBC->getAPIntValue() == OpSizeInBits) {
3261         if (HasROTL)
3262           return DAG.getNode(ISD::ROTL, DL, VT,
3263                              LHSShiftArg, LHSShiftAmt).getNode();
3264         else
3265           return DAG.getNode(ISD::ROTR, DL, VT,
3266                              LHSShiftArg, RHSShiftAmt).getNode();
3267       }
3268     }
3269   }
3270
3271   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3272   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3273   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3274       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3275     if (ConstantSDNode *SUBC =
3276           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3277       if (SUBC->getAPIntValue() == OpSizeInBits) {
3278         if (HasROTR)
3279           return DAG.getNode(ISD::ROTR, DL, VT,
3280                              LHSShiftArg, RHSShiftAmt).getNode();
3281         else
3282           return DAG.getNode(ISD::ROTL, DL, VT,
3283                              LHSShiftArg, LHSShiftAmt).getNode();
3284       }
3285     }
3286   }
3287
3288   // Look for sign/zext/any-extended or truncate cases:
3289   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3290        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3291        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3292        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3293       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3294        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3295        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3296        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3297     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3298     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3299     if (RExtOp0.getOpcode() == ISD::SUB &&
3300         RExtOp0.getOperand(1) == LExtOp0) {
3301       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3302       //   (rotl x, y)
3303       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3304       //   (rotr x, (sub 32, y))
3305       if (ConstantSDNode *SUBC =
3306             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3307         if (SUBC->getAPIntValue() == OpSizeInBits) {
3308           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3309                              LHSShiftArg,
3310                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3311         }
3312       }
3313     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3314                RExtOp0 == LExtOp0.getOperand(1)) {
3315       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3316       //   (rotr x, y)
3317       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3318       //   (rotl x, (sub 32, y))
3319       if (ConstantSDNode *SUBC =
3320             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3321         if (SUBC->getAPIntValue() == OpSizeInBits) {
3322           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3323                              LHSShiftArg,
3324                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3325         }
3326       }
3327     }
3328   }
3329
3330   return 0;
3331 }
3332
3333 SDValue DAGCombiner::visitXOR(SDNode *N) {
3334   SDValue N0 = N->getOperand(0);
3335   SDValue N1 = N->getOperand(1);
3336   SDValue LHS, RHS, CC;
3337   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3338   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3339   EVT VT = N0.getValueType();
3340
3341   // fold vector ops
3342   if (VT.isVector()) {
3343     SDValue FoldedVOp = SimplifyVBinOp(N);
3344     if (FoldedVOp.getNode()) return FoldedVOp;
3345   }
3346
3347   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3348   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3349     return DAG.getConstant(0, VT);
3350   // fold (xor x, undef) -> undef
3351   if (N0.getOpcode() == ISD::UNDEF)
3352     return N0;
3353   if (N1.getOpcode() == ISD::UNDEF)
3354     return N1;
3355   // fold (xor c1, c2) -> c1^c2
3356   if (N0C && N1C)
3357     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3358   // canonicalize constant to RHS
3359   if (N0C && !N1C)
3360     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3361   // fold (xor x, 0) -> x
3362   if (N1C && N1C->isNullValue())
3363     return N0;
3364   // reassociate xor
3365   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3366   if (RXOR.getNode() != 0)
3367     return RXOR;
3368
3369   // fold !(x cc y) -> (x !cc y)
3370   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3371     bool isInt = LHS.getValueType().isInteger();
3372     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3373                                                isInt);
3374
3375     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3376       switch (N0.getOpcode()) {
3377       default:
3378         llvm_unreachable("Unhandled SetCC Equivalent!");
3379       case ISD::SETCC:
3380         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3381       case ISD::SELECT_CC:
3382         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3383                                N0.getOperand(3), NotCC);
3384       }
3385     }
3386   }
3387
3388   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3389   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3390       N0.getNode()->hasOneUse() &&
3391       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3392     SDValue V = N0.getOperand(0);
3393     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3394                     DAG.getConstant(1, V.getValueType()));
3395     AddToWorkList(V.getNode());
3396     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3397   }
3398
3399   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3400   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3401       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3402     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3403     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3404       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3405       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3406       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3407       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3408       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3409     }
3410   }
3411   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3412   if (N1C && N1C->isAllOnesValue() &&
3413       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3414     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3415     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3416       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3417       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3418       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3419       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3420       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3421     }
3422   }
3423   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3424   if (N1C && N0.getOpcode() == ISD::XOR) {
3425     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3426     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3427     if (N00C)
3428       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3429                          DAG.getConstant(N1C->getAPIntValue() ^
3430                                          N00C->getAPIntValue(), VT));
3431     if (N01C)
3432       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3433                          DAG.getConstant(N1C->getAPIntValue() ^
3434                                          N01C->getAPIntValue(), VT));
3435   }
3436   // fold (xor x, x) -> 0
3437   if (N0 == N1)
3438     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3439
3440   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3441   if (N0.getOpcode() == N1.getOpcode()) {
3442     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3443     if (Tmp.getNode()) return Tmp;
3444   }
3445
3446   // Simplify the expression using non-local knowledge.
3447   if (!VT.isVector() &&
3448       SimplifyDemandedBits(SDValue(N, 0)))
3449     return SDValue(N, 0);
3450
3451   return SDValue();
3452 }
3453
3454 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3455 /// the shift amount is a constant.
3456 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3457   SDNode *LHS = N->getOperand(0).getNode();
3458   if (!LHS->hasOneUse()) return SDValue();
3459
3460   // We want to pull some binops through shifts, so that we have (and (shift))
3461   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3462   // thing happens with address calculations, so it's important to canonicalize
3463   // it.
3464   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3465
3466   switch (LHS->getOpcode()) {
3467   default: return SDValue();
3468   case ISD::OR:
3469   case ISD::XOR:
3470     HighBitSet = false; // We can only transform sra if the high bit is clear.
3471     break;
3472   case ISD::AND:
3473     HighBitSet = true;  // We can only transform sra if the high bit is set.
3474     break;
3475   case ISD::ADD:
3476     if (N->getOpcode() != ISD::SHL)
3477       return SDValue(); // only shl(add) not sr[al](add).
3478     HighBitSet = false; // We can only transform sra if the high bit is clear.
3479     break;
3480   }
3481
3482   // We require the RHS of the binop to be a constant as well.
3483   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3484   if (!BinOpCst) return SDValue();
3485
3486   // FIXME: disable this unless the input to the binop is a shift by a constant.
3487   // If it is not a shift, it pessimizes some common cases like:
3488   //
3489   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3490   //    int bar(int *X, int i) { return X[i & 255]; }
3491   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3492   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3493        BinOpLHSVal->getOpcode() != ISD::SRA &&
3494        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3495       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3496     return SDValue();
3497
3498   EVT VT = N->getValueType(0);
3499
3500   // If this is a signed shift right, and the high bit is modified by the
3501   // logical operation, do not perform the transformation. The highBitSet
3502   // boolean indicates the value of the high bit of the constant which would
3503   // cause it to be modified for this operation.
3504   if (N->getOpcode() == ISD::SRA) {
3505     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3506     if (BinOpRHSSignSet != HighBitSet)
3507       return SDValue();
3508   }
3509
3510   // Fold the constants, shifting the binop RHS by the shift amount.
3511   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3512                                N->getValueType(0),
3513                                LHS->getOperand(1), N->getOperand(1));
3514
3515   // Create the new shift.
3516   SDValue NewShift = DAG.getNode(N->getOpcode(),
3517                                  LHS->getOperand(0).getDebugLoc(),
3518                                  VT, LHS->getOperand(0), N->getOperand(1));
3519
3520   // Create the new binop.
3521   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3522 }
3523
3524 SDValue DAGCombiner::visitSHL(SDNode *N) {
3525   SDValue N0 = N->getOperand(0);
3526   SDValue N1 = N->getOperand(1);
3527   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3528   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3529   EVT VT = N0.getValueType();
3530   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3531
3532   // fold (shl c1, c2) -> c1<<c2
3533   if (N0C && N1C)
3534     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3535   // fold (shl 0, x) -> 0
3536   if (N0C && N0C->isNullValue())
3537     return N0;
3538   // fold (shl x, c >= size(x)) -> undef
3539   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3540     return DAG.getUNDEF(VT);
3541   // fold (shl x, 0) -> x
3542   if (N1C && N1C->isNullValue())
3543     return N0;
3544   // fold (shl undef, x) -> 0
3545   if (N0.getOpcode() == ISD::UNDEF)
3546     return DAG.getConstant(0, VT);
3547   // if (shl x, c) is known to be zero, return 0
3548   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3549                             APInt::getAllOnesValue(OpSizeInBits)))
3550     return DAG.getConstant(0, VT);
3551   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3552   if (N1.getOpcode() == ISD::TRUNCATE &&
3553       N1.getOperand(0).getOpcode() == ISD::AND &&
3554       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3555     SDValue N101 = N1.getOperand(0).getOperand(1);
3556     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3557       EVT TruncVT = N1.getValueType();
3558       SDValue N100 = N1.getOperand(0).getOperand(0);
3559       APInt TruncC = N101C->getAPIntValue();
3560       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3561       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3562                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3563                                      DAG.getNode(ISD::TRUNCATE,
3564                                                  N->getDebugLoc(),
3565                                                  TruncVT, N100),
3566                                      DAG.getConstant(TruncC, TruncVT)));
3567     }
3568   }
3569
3570   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3571     return SDValue(N, 0);
3572
3573   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3574   if (N1C && N0.getOpcode() == ISD::SHL &&
3575       N0.getOperand(1).getOpcode() == ISD::Constant) {
3576     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3577     uint64_t c2 = N1C->getZExtValue();
3578     if (c1 + c2 >= OpSizeInBits)
3579       return DAG.getConstant(0, VT);
3580     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3581                        DAG.getConstant(c1 + c2, N1.getValueType()));
3582   }
3583
3584   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3585   // For this to be valid, the second form must not preserve any of the bits
3586   // that are shifted out by the inner shift in the first form.  This means
3587   // the outer shift size must be >= the number of bits added by the ext.
3588   // As a corollary, we don't care what kind of ext it is.
3589   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3590               N0.getOpcode() == ISD::ANY_EXTEND ||
3591               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3592       N0.getOperand(0).getOpcode() == ISD::SHL &&
3593       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3594     uint64_t c1 =
3595       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3596     uint64_t c2 = N1C->getZExtValue();
3597     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3598     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3599     if (c2 >= OpSizeInBits - InnerShiftSize) {
3600       if (c1 + c2 >= OpSizeInBits)
3601         return DAG.getConstant(0, VT);
3602       return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3603                          DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3604                                      N0.getOperand(0)->getOperand(0)),
3605                          DAG.getConstant(c1 + c2, N1.getValueType()));
3606     }
3607   }
3608
3609   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3610   //                               (and (srl x, (sub c1, c2), MASK)
3611   // Only fold this if the inner shift has no other uses -- if it does, folding
3612   // this will increase the total number of instructions.
3613   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3614       N0.getOperand(1).getOpcode() == ISD::Constant) {
3615     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3616     if (c1 < VT.getSizeInBits()) {
3617       uint64_t c2 = N1C->getZExtValue();
3618       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3619                                          VT.getSizeInBits() - c1);
3620       SDValue Shift;
3621       if (c2 > c1) {
3622         Mask = Mask.shl(c2-c1);
3623         Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3624                             DAG.getConstant(c2-c1, N1.getValueType()));
3625       } else {
3626         Mask = Mask.lshr(c1-c2);
3627         Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3628                             DAG.getConstant(c1-c2, N1.getValueType()));
3629       }
3630       return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3631                          DAG.getConstant(Mask, VT));
3632     }
3633   }
3634   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3635   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3636     SDValue HiBitsMask =
3637       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3638                                             VT.getSizeInBits() -
3639                                               N1C->getZExtValue()),
3640                       VT);
3641     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3642                        HiBitsMask);
3643   }
3644
3645   if (N1C) {
3646     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3647     if (NewSHL.getNode())
3648       return NewSHL;
3649   }
3650
3651   return SDValue();
3652 }
3653
3654 SDValue DAGCombiner::visitSRA(SDNode *N) {
3655   SDValue N0 = N->getOperand(0);
3656   SDValue N1 = N->getOperand(1);
3657   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3658   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3659   EVT VT = N0.getValueType();
3660   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3661
3662   // fold (sra c1, c2) -> (sra c1, c2)
3663   if (N0C && N1C)
3664     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3665   // fold (sra 0, x) -> 0
3666   if (N0C && N0C->isNullValue())
3667     return N0;
3668   // fold (sra -1, x) -> -1
3669   if (N0C && N0C->isAllOnesValue())
3670     return N0;
3671   // fold (sra x, (setge c, size(x))) -> undef
3672   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3673     return DAG.getUNDEF(VT);
3674   // fold (sra x, 0) -> x
3675   if (N1C && N1C->isNullValue())
3676     return N0;
3677   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3678   // sext_inreg.
3679   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3680     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3681     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3682     if (VT.isVector())
3683       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3684                                ExtVT, VT.getVectorNumElements());
3685     if ((!LegalOperations ||
3686          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3687       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3688                          N0.getOperand(0), DAG.getValueType(ExtVT));
3689   }
3690
3691   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3692   if (N1C && N0.getOpcode() == ISD::SRA) {
3693     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3694       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3695       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3696       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3697                          DAG.getConstant(Sum, N1C->getValueType(0)));
3698     }
3699   }
3700
3701   // fold (sra (shl X, m), (sub result_size, n))
3702   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3703   // result_size - n != m.
3704   // If truncate is free for the target sext(shl) is likely to result in better
3705   // code.
3706   if (N0.getOpcode() == ISD::SHL) {
3707     // Get the two constanst of the shifts, CN0 = m, CN = n.
3708     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3709     if (N01C && N1C) {
3710       // Determine what the truncate's result bitsize and type would be.
3711       EVT TruncVT =
3712         EVT::getIntegerVT(*DAG.getContext(),
3713                           OpSizeInBits - N1C->getZExtValue());
3714       // Determine the residual right-shift amount.
3715       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3716
3717       // If the shift is not a no-op (in which case this should be just a sign
3718       // extend already), the truncated to type is legal, sign_extend is legal
3719       // on that type, and the truncate to that type is both legal and free,
3720       // perform the transform.
3721       if ((ShiftAmt > 0) &&
3722           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3723           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3724           TLI.isTruncateFree(VT, TruncVT)) {
3725
3726           SDValue Amt = DAG.getConstant(ShiftAmt,
3727               getShiftAmountTy(N0.getOperand(0).getValueType()));
3728           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3729                                       N0.getOperand(0), Amt);
3730           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3731                                       Shift);
3732           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3733                              N->getValueType(0), Trunc);
3734       }
3735     }
3736   }
3737
3738   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3739   if (N1.getOpcode() == ISD::TRUNCATE &&
3740       N1.getOperand(0).getOpcode() == ISD::AND &&
3741       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3742     SDValue N101 = N1.getOperand(0).getOperand(1);
3743     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3744       EVT TruncVT = N1.getValueType();
3745       SDValue N100 = N1.getOperand(0).getOperand(0);
3746       APInt TruncC = N101C->getAPIntValue();
3747       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3748       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3749                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3750                                      TruncVT,
3751                                      DAG.getNode(ISD::TRUNCATE,
3752                                                  N->getDebugLoc(),
3753                                                  TruncVT, N100),
3754                                      DAG.getConstant(TruncC, TruncVT)));
3755     }
3756   }
3757
3758   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3759   //      if c1 is equal to the number of bits the trunc removes
3760   if (N0.getOpcode() == ISD::TRUNCATE &&
3761       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3762        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3763       N0.getOperand(0).hasOneUse() &&
3764       N0.getOperand(0).getOperand(1).hasOneUse() &&
3765       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3766     EVT LargeVT = N0.getOperand(0).getValueType();
3767     ConstantSDNode *LargeShiftAmt =
3768       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3769
3770     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3771         LargeShiftAmt->getZExtValue()) {
3772       SDValue Amt =
3773         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3774               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3775       SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3776                                 N0.getOperand(0).getOperand(0), Amt);
3777       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3778     }
3779   }
3780
3781   // Simplify, based on bits shifted out of the LHS.
3782   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3783     return SDValue(N, 0);
3784
3785
3786   // If the sign bit is known to be zero, switch this to a SRL.
3787   if (DAG.SignBitIsZero(N0))
3788     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3789
3790   if (N1C) {
3791     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3792     if (NewSRA.getNode())
3793       return NewSRA;
3794   }
3795
3796   return SDValue();
3797 }
3798
3799 SDValue DAGCombiner::visitSRL(SDNode *N) {
3800   SDValue N0 = N->getOperand(0);
3801   SDValue N1 = N->getOperand(1);
3802   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3803   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3804   EVT VT = N0.getValueType();
3805   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3806
3807   // fold (srl c1, c2) -> c1 >>u c2
3808   if (N0C && N1C)
3809     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3810   // fold (srl 0, x) -> 0
3811   if (N0C && N0C->isNullValue())
3812     return N0;
3813   // fold (srl x, c >= size(x)) -> undef
3814   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3815     return DAG.getUNDEF(VT);
3816   // fold (srl x, 0) -> x
3817   if (N1C && N1C->isNullValue())
3818     return N0;
3819   // if (srl x, c) is known to be zero, return 0
3820   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3821                                    APInt::getAllOnesValue(OpSizeInBits)))
3822     return DAG.getConstant(0, VT);
3823
3824   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3825   if (N1C && N0.getOpcode() == ISD::SRL &&
3826       N0.getOperand(1).getOpcode() == ISD::Constant) {
3827     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3828     uint64_t c2 = N1C->getZExtValue();
3829     if (c1 + c2 >= OpSizeInBits)
3830       return DAG.getConstant(0, VT);
3831     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3832                        DAG.getConstant(c1 + c2, N1.getValueType()));
3833   }
3834
3835   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3836   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3837       N0.getOperand(0).getOpcode() == ISD::SRL &&
3838       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3839     uint64_t c1 =
3840       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3841     uint64_t c2 = N1C->getZExtValue();
3842     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3843     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3844     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3845     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3846     if (c1 + OpSizeInBits == InnerShiftSize) {
3847       if (c1 + c2 >= InnerShiftSize)
3848         return DAG.getConstant(0, VT);
3849       return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3850                          DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3851                                      N0.getOperand(0)->getOperand(0),
3852                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3853     }
3854   }
3855
3856   // fold (srl (shl x, c), c) -> (and x, cst2)
3857   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3858       N0.getValueSizeInBits() <= 64) {
3859     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3860     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3861                        DAG.getConstant(~0ULL >> ShAmt, VT));
3862   }
3863
3864
3865   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3866   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3867     // Shifting in all undef bits?
3868     EVT SmallVT = N0.getOperand(0).getValueType();
3869     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3870       return DAG.getUNDEF(VT);
3871
3872     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3873       uint64_t ShiftAmt = N1C->getZExtValue();
3874       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3875                                        N0.getOperand(0),
3876                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3877       AddToWorkList(SmallShift.getNode());
3878       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3879     }
3880   }
3881
3882   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3883   // bit, which is unmodified by sra.
3884   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3885     if (N0.getOpcode() == ISD::SRA)
3886       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3887   }
3888
3889   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3890   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3891       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3892     APInt KnownZero, KnownOne;
3893     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3894
3895     // If any of the input bits are KnownOne, then the input couldn't be all
3896     // zeros, thus the result of the srl will always be zero.
3897     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3898
3899     // If all of the bits input the to ctlz node are known to be zero, then
3900     // the result of the ctlz is "32" and the result of the shift is one.
3901     APInt UnknownBits = ~KnownZero;
3902     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3903
3904     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3905     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3906       // Okay, we know that only that the single bit specified by UnknownBits
3907       // could be set on input to the CTLZ node. If this bit is set, the SRL
3908       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3909       // to an SRL/XOR pair, which is likely to simplify more.
3910       unsigned ShAmt = UnknownBits.countTrailingZeros();
3911       SDValue Op = N0.getOperand(0);
3912
3913       if (ShAmt) {
3914         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3915                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3916         AddToWorkList(Op.getNode());
3917       }
3918
3919       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3920                          Op, DAG.getConstant(1, VT));
3921     }
3922   }
3923
3924   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3925   if (N1.getOpcode() == ISD::TRUNCATE &&
3926       N1.getOperand(0).getOpcode() == ISD::AND &&
3927       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3928     SDValue N101 = N1.getOperand(0).getOperand(1);
3929     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3930       EVT TruncVT = N1.getValueType();
3931       SDValue N100 = N1.getOperand(0).getOperand(0);
3932       APInt TruncC = N101C->getAPIntValue();
3933       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3934       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3935                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3936                                      TruncVT,
3937                                      DAG.getNode(ISD::TRUNCATE,
3938                                                  N->getDebugLoc(),
3939                                                  TruncVT, N100),
3940                                      DAG.getConstant(TruncC, TruncVT)));
3941     }
3942   }
3943
3944   // fold operands of srl based on knowledge that the low bits are not
3945   // demanded.
3946   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3947     return SDValue(N, 0);
3948
3949   if (N1C) {
3950     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3951     if (NewSRL.getNode())
3952       return NewSRL;
3953   }
3954
3955   // Attempt to convert a srl of a load into a narrower zero-extending load.
3956   SDValue NarrowLoad = ReduceLoadWidth(N);
3957   if (NarrowLoad.getNode())
3958     return NarrowLoad;
3959
3960   // Here is a common situation. We want to optimize:
3961   //
3962   //   %a = ...
3963   //   %b = and i32 %a, 2
3964   //   %c = srl i32 %b, 1
3965   //   brcond i32 %c ...
3966   //
3967   // into
3968   //
3969   //   %a = ...
3970   //   %b = and %a, 2
3971   //   %c = setcc eq %b, 0
3972   //   brcond %c ...
3973   //
3974   // However when after the source operand of SRL is optimized into AND, the SRL
3975   // itself may not be optimized further. Look for it and add the BRCOND into
3976   // the worklist.
3977   if (N->hasOneUse()) {
3978     SDNode *Use = *N->use_begin();
3979     if (Use->getOpcode() == ISD::BRCOND)
3980       AddToWorkList(Use);
3981     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3982       // Also look pass the truncate.
3983       Use = *Use->use_begin();
3984       if (Use->getOpcode() == ISD::BRCOND)
3985         AddToWorkList(Use);
3986     }
3987   }
3988
3989   return SDValue();
3990 }
3991
3992 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3993   SDValue N0 = N->getOperand(0);
3994   EVT VT = N->getValueType(0);
3995
3996   // fold (ctlz c1) -> c2
3997   if (isa<ConstantSDNode>(N0))
3998     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3999   return SDValue();
4000 }
4001
4002 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4003   SDValue N0 = N->getOperand(0);
4004   EVT VT = N->getValueType(0);
4005
4006   // fold (ctlz_zero_undef c1) -> c2
4007   if (isa<ConstantSDNode>(N0))
4008     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4009   return SDValue();
4010 }
4011
4012 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4013   SDValue N0 = N->getOperand(0);
4014   EVT VT = N->getValueType(0);
4015
4016   // fold (cttz c1) -> c2
4017   if (isa<ConstantSDNode>(N0))
4018     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
4019   return SDValue();
4020 }
4021
4022 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4023   SDValue N0 = N->getOperand(0);
4024   EVT VT = N->getValueType(0);
4025
4026   // fold (cttz_zero_undef c1) -> c2
4027   if (isa<ConstantSDNode>(N0))
4028     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4029   return SDValue();
4030 }
4031
4032 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4033   SDValue N0 = N->getOperand(0);
4034   EVT VT = N->getValueType(0);
4035
4036   // fold (ctpop c1) -> c2
4037   if (isa<ConstantSDNode>(N0))
4038     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4039   return SDValue();
4040 }
4041
4042 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4043   SDValue N0 = N->getOperand(0);
4044   SDValue N1 = N->getOperand(1);
4045   SDValue N2 = N->getOperand(2);
4046   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4047   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4048   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4049   EVT VT = N->getValueType(0);
4050   EVT VT0 = N0.getValueType();
4051
4052   // fold (select C, X, X) -> X
4053   if (N1 == N2)
4054     return N1;
4055   // fold (select true, X, Y) -> X
4056   if (N0C && !N0C->isNullValue())
4057     return N1;
4058   // fold (select false, X, Y) -> Y
4059   if (N0C && N0C->isNullValue())
4060     return N2;
4061   // fold (select C, 1, X) -> (or C, X)
4062   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4063     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4064   // fold (select C, 0, 1) -> (xor C, 1)
4065   if (VT.isInteger() &&
4066       (VT0 == MVT::i1 ||
4067        (VT0.isInteger() &&
4068         TLI.getBooleanContents(false) ==
4069         TargetLowering::ZeroOrOneBooleanContent)) &&
4070       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4071     SDValue XORNode;
4072     if (VT == VT0)
4073       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4074                          N0, DAG.getConstant(1, VT0));
4075     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4076                           N0, DAG.getConstant(1, VT0));
4077     AddToWorkList(XORNode.getNode());
4078     if (VT.bitsGT(VT0))
4079       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4080     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4081   }
4082   // fold (select C, 0, X) -> (and (not C), X)
4083   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4084     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4085     AddToWorkList(NOTNode.getNode());
4086     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4087   }
4088   // fold (select C, X, 1) -> (or (not C), X)
4089   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4090     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4091     AddToWorkList(NOTNode.getNode());
4092     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4093   }
4094   // fold (select C, X, 0) -> (and C, X)
4095   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4096     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4097   // fold (select X, X, Y) -> (or X, Y)
4098   // fold (select X, 1, Y) -> (or X, Y)
4099   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4100     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4101   // fold (select X, Y, X) -> (and X, Y)
4102   // fold (select X, Y, 0) -> (and X, Y)
4103   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4104     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4105
4106   // If we can fold this based on the true/false value, do so.
4107   if (SimplifySelectOps(N, N1, N2))
4108     return SDValue(N, 0);  // Don't revisit N.
4109
4110   // fold selects based on a setcc into other things, such as min/max/abs
4111   if (N0.getOpcode() == ISD::SETCC) {
4112     // FIXME:
4113     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4114     // having to say they don't support SELECT_CC on every type the DAG knows
4115     // about, since there is no way to mark an opcode illegal at all value types
4116     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4117         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4118       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4119                          N0.getOperand(0), N0.getOperand(1),
4120                          N1, N2, N0.getOperand(2));
4121     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4122   }
4123
4124   return SDValue();
4125 }
4126
4127 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4128   SDValue N0 = N->getOperand(0);
4129   SDValue N1 = N->getOperand(1);
4130   SDValue N2 = N->getOperand(2);
4131   SDValue N3 = N->getOperand(3);
4132   SDValue N4 = N->getOperand(4);
4133   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4134
4135   // fold select_cc lhs, rhs, x, x, cc -> x
4136   if (N2 == N3)
4137     return N2;
4138
4139   // Determine if the condition we're dealing with is constant
4140   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4141                               N0, N1, CC, N->getDebugLoc(), false);
4142   if (SCC.getNode()) AddToWorkList(SCC.getNode());
4143
4144   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4145     if (!SCCC->isNullValue())
4146       return N2;    // cond always true -> true val
4147     else
4148       return N3;    // cond always false -> false val
4149   }
4150
4151   // Fold to a simpler select_cc
4152   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4153     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4154                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4155                        SCC.getOperand(2));
4156
4157   // If we can fold this based on the true/false value, do so.
4158   if (SimplifySelectOps(N, N2, N3))
4159     return SDValue(N, 0);  // Don't revisit N.
4160
4161   // fold select_cc into other things, such as min/max/abs
4162   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4163 }
4164
4165 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4166   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4167                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4168                        N->getDebugLoc());
4169 }
4170
4171 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4172 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4173 // transformation. Returns true if extension are possible and the above
4174 // mentioned transformation is profitable.
4175 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4176                                     unsigned ExtOpc,
4177                                     SmallVector<SDNode*, 4> &ExtendNodes,
4178                                     const TargetLowering &TLI) {
4179   bool HasCopyToRegUses = false;
4180   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4181   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4182                             UE = N0.getNode()->use_end();
4183        UI != UE; ++UI) {
4184     SDNode *User = *UI;
4185     if (User == N)
4186       continue;
4187     if (UI.getUse().getResNo() != N0.getResNo())
4188       continue;
4189     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4190     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4191       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4192       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4193         // Sign bits will be lost after a zext.
4194         return false;
4195       bool Add = false;
4196       for (unsigned i = 0; i != 2; ++i) {
4197         SDValue UseOp = User->getOperand(i);
4198         if (UseOp == N0)
4199           continue;
4200         if (!isa<ConstantSDNode>(UseOp))
4201           return false;
4202         Add = true;
4203       }
4204       if (Add)
4205         ExtendNodes.push_back(User);
4206       continue;
4207     }
4208     // If truncates aren't free and there are users we can't
4209     // extend, it isn't worthwhile.
4210     if (!isTruncFree)
4211       return false;
4212     // Remember if this value is live-out.
4213     if (User->getOpcode() == ISD::CopyToReg)
4214       HasCopyToRegUses = true;
4215   }
4216
4217   if (HasCopyToRegUses) {
4218     bool BothLiveOut = false;
4219     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4220          UI != UE; ++UI) {
4221       SDUse &Use = UI.getUse();
4222       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4223         BothLiveOut = true;
4224         break;
4225       }
4226     }
4227     if (BothLiveOut)
4228       // Both unextended and extended values are live out. There had better be
4229       // a good reason for the transformation.
4230       return ExtendNodes.size();
4231   }
4232   return true;
4233 }
4234
4235 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4236                                   SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4237                                   ISD::NodeType ExtType) {
4238   // Extend SetCC uses if necessary.
4239   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4240     SDNode *SetCC = SetCCs[i];
4241     SmallVector<SDValue, 4> Ops;
4242
4243     for (unsigned j = 0; j != 2; ++j) {
4244       SDValue SOp = SetCC->getOperand(j);
4245       if (SOp == Trunc)
4246         Ops.push_back(ExtLoad);
4247       else
4248         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4249     }
4250
4251     Ops.push_back(SetCC->getOperand(2));
4252     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4253                                  &Ops[0], Ops.size()));
4254   }
4255 }
4256
4257 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4258   SDValue N0 = N->getOperand(0);
4259   EVT VT = N->getValueType(0);
4260
4261   // fold (sext c1) -> c1
4262   if (isa<ConstantSDNode>(N0))
4263     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4264
4265   // fold (sext (sext x)) -> (sext x)
4266   // fold (sext (aext x)) -> (sext x)
4267   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4268     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4269                        N0.getOperand(0));
4270
4271   if (N0.getOpcode() == ISD::TRUNCATE) {
4272     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4273     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4274     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4275     if (NarrowLoad.getNode()) {
4276       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4277       if (NarrowLoad.getNode() != N0.getNode()) {
4278         CombineTo(N0.getNode(), NarrowLoad);
4279         // CombineTo deleted the truncate, if needed, but not what's under it.
4280         AddToWorkList(oye);
4281       }
4282       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4283     }
4284
4285     // See if the value being truncated is already sign extended.  If so, just
4286     // eliminate the trunc/sext pair.
4287     SDValue Op = N0.getOperand(0);
4288     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4289     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4290     unsigned DestBits = VT.getScalarType().getSizeInBits();
4291     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4292
4293     if (OpBits == DestBits) {
4294       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4295       // bits, it is already ready.
4296       if (NumSignBits > DestBits-MidBits)
4297         return Op;
4298     } else if (OpBits < DestBits) {
4299       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4300       // bits, just sext from i32.
4301       if (NumSignBits > OpBits-MidBits)
4302         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4303     } else {
4304       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4305       // bits, just truncate to i32.
4306       if (NumSignBits > OpBits-MidBits)
4307         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4308     }
4309
4310     // fold (sext (truncate x)) -> (sextinreg x).
4311     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4312                                                  N0.getValueType())) {
4313       if (OpBits < DestBits)
4314         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4315       else if (OpBits > DestBits)
4316         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4317       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4318                          DAG.getValueType(N0.getValueType()));
4319     }
4320   }
4321
4322   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4323   // None of the supported targets knows how to perform load and sign extend
4324   // on vectors in one instruction.  We only perform this transformation on
4325   // scalars.
4326   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4327       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4328        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4329     bool DoXform = true;
4330     SmallVector<SDNode*, 4> SetCCs;
4331     if (!N0.hasOneUse())
4332       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4333     if (DoXform) {
4334       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4335       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4336                                        LN0->getChain(),
4337                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4338                                        N0.getValueType(),
4339                                        LN0->isVolatile(), LN0->isNonTemporal(),
4340                                        LN0->getAlignment());
4341       CombineTo(N, ExtLoad);
4342       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4343                                   N0.getValueType(), ExtLoad);
4344       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4345       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4346                       ISD::SIGN_EXTEND);
4347       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4348     }
4349   }
4350
4351   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4352   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4353   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4354       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4355     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4356     EVT MemVT = LN0->getMemoryVT();
4357     if ((!LegalOperations && !LN0->isVolatile()) ||
4358         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4359       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4360                                        LN0->getChain(),
4361                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4362                                        MemVT,
4363                                        LN0->isVolatile(), LN0->isNonTemporal(),
4364                                        LN0->getAlignment());
4365       CombineTo(N, ExtLoad);
4366       CombineTo(N0.getNode(),
4367                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4368                             N0.getValueType(), ExtLoad),
4369                 ExtLoad.getValue(1));
4370       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4371     }
4372   }
4373
4374   // fold (sext (and/or/xor (load x), cst)) ->
4375   //      (and/or/xor (sextload x), (sext cst))
4376   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4377        N0.getOpcode() == ISD::XOR) &&
4378       isa<LoadSDNode>(N0.getOperand(0)) &&
4379       N0.getOperand(1).getOpcode() == ISD::Constant &&
4380       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4381       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4382     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4383     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4384       bool DoXform = true;
4385       SmallVector<SDNode*, 4> SetCCs;
4386       if (!N0.hasOneUse())
4387         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4388                                           SetCCs, TLI);
4389       if (DoXform) {
4390         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4391                                          LN0->getChain(), LN0->getBasePtr(),
4392                                          LN0->getPointerInfo(),
4393                                          LN0->getMemoryVT(),
4394                                          LN0->isVolatile(),
4395                                          LN0->isNonTemporal(),
4396                                          LN0->getAlignment());
4397         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4398         Mask = Mask.sext(VT.getSizeInBits());
4399         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4400                                   ExtLoad, DAG.getConstant(Mask, VT));
4401         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4402                                     N0.getOperand(0).getDebugLoc(),
4403                                     N0.getOperand(0).getValueType(), ExtLoad);
4404         CombineTo(N, And);
4405         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4406         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4407                         ISD::SIGN_EXTEND);
4408         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4409       }
4410     }
4411   }
4412
4413   if (N0.getOpcode() == ISD::SETCC) {
4414     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4415     // Only do this before legalize for now.
4416     if (VT.isVector() && !LegalOperations) {
4417       EVT N0VT = N0.getOperand(0).getValueType();
4418       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4419       // of the same size as the compared operands. Only optimize sext(setcc())
4420       // if this is the case.
4421       EVT SVT = TLI.getSetCCResultType(N0VT);
4422
4423       // We know that the # elements of the results is the same as the
4424       // # elements of the compare (and the # elements of the compare result
4425       // for that matter).  Check to see that they are the same size.  If so,
4426       // we know that the element size of the sext'd result matches the
4427       // element size of the compare operands.
4428       if (VT.getSizeInBits() == SVT.getSizeInBits())
4429         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4430                              N0.getOperand(1),
4431                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4432       // If the desired elements are smaller or larger than the source
4433       // elements we can use a matching integer vector type and then
4434       // truncate/sign extend
4435       else {
4436         EVT MatchingElementType =
4437           EVT::getIntegerVT(*DAG.getContext(),
4438                             N0VT.getScalarType().getSizeInBits());
4439         EVT MatchingVectorType =
4440           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4441                            N0VT.getVectorNumElements());
4442
4443         if (SVT == MatchingVectorType) {
4444           SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4445                                  N0.getOperand(0), N0.getOperand(1),
4446                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
4447           return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4448         }
4449       }
4450     }
4451
4452     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4453     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4454     SDValue NegOne =
4455       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4456     SDValue SCC =
4457       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4458                        NegOne, DAG.getConstant(0, VT),
4459                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4460     if (SCC.getNode()) return SCC;
4461     if (!LegalOperations ||
4462         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4463       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4464                          DAG.getSetCC(N->getDebugLoc(),
4465                                       TLI.getSetCCResultType(VT),
4466                                       N0.getOperand(0), N0.getOperand(1),
4467                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4468                          NegOne, DAG.getConstant(0, VT));
4469   }
4470
4471   // fold (sext x) -> (zext x) if the sign bit is known zero.
4472   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4473       DAG.SignBitIsZero(N0))
4474     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4475
4476   return SDValue();
4477 }
4478
4479 // isTruncateOf - If N is a truncate of some other value, return true, record
4480 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4481 // This function computes KnownZero to avoid a duplicated call to
4482 // ComputeMaskedBits in the caller.
4483 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4484                          APInt &KnownZero) {
4485   APInt KnownOne;
4486   if (N->getOpcode() == ISD::TRUNCATE) {
4487     Op = N->getOperand(0);
4488     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4489     return true;
4490   }
4491
4492   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4493       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4494     return false;
4495
4496   SDValue Op0 = N->getOperand(0);
4497   SDValue Op1 = N->getOperand(1);
4498   assert(Op0.getValueType() == Op1.getValueType());
4499
4500   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4501   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4502   if (COp0 && COp0->isNullValue())
4503     Op = Op1;
4504   else if (COp1 && COp1->isNullValue())
4505     Op = Op0;
4506   else
4507     return false;
4508
4509   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4510
4511   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4512     return false;
4513
4514   return true;
4515 }
4516
4517 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4518   SDValue N0 = N->getOperand(0);
4519   EVT VT = N->getValueType(0);
4520
4521   // fold (zext c1) -> c1
4522   if (isa<ConstantSDNode>(N0))
4523     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4524   // fold (zext (zext x)) -> (zext x)
4525   // fold (zext (aext x)) -> (zext x)
4526   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4527     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4528                        N0.getOperand(0));
4529
4530   // fold (zext (truncate x)) -> (zext x) or
4531   //      (zext (truncate x)) -> (truncate x)
4532   // This is valid when the truncated bits of x are already zero.
4533   // FIXME: We should extend this to work for vectors too.
4534   SDValue Op;
4535   APInt KnownZero;
4536   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4537     APInt TruncatedBits =
4538       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4539       APInt(Op.getValueSizeInBits(), 0) :
4540       APInt::getBitsSet(Op.getValueSizeInBits(),
4541                         N0.getValueSizeInBits(),
4542                         std::min(Op.getValueSizeInBits(),
4543                                  VT.getSizeInBits()));
4544     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4545       if (VT.bitsGT(Op.getValueType()))
4546         return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4547       if (VT.bitsLT(Op.getValueType()))
4548         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4549
4550       return Op;
4551     }
4552   }
4553
4554   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4555   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4556   if (N0.getOpcode() == ISD::TRUNCATE) {
4557     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4558     if (NarrowLoad.getNode()) {
4559       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4560       if (NarrowLoad.getNode() != N0.getNode()) {
4561         CombineTo(N0.getNode(), NarrowLoad);
4562         // CombineTo deleted the truncate, if needed, but not what's under it.
4563         AddToWorkList(oye);
4564       }
4565       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4566     }
4567   }
4568
4569   // fold (zext (truncate x)) -> (and x, mask)
4570   if (N0.getOpcode() == ISD::TRUNCATE &&
4571       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4572
4573     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4574     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4575     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4576     if (NarrowLoad.getNode()) {
4577       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4578       if (NarrowLoad.getNode() != N0.getNode()) {
4579         CombineTo(N0.getNode(), NarrowLoad);
4580         // CombineTo deleted the truncate, if needed, but not what's under it.
4581         AddToWorkList(oye);
4582       }
4583       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4584     }
4585
4586     SDValue Op = N0.getOperand(0);
4587     if (Op.getValueType().bitsLT(VT)) {
4588       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4589       AddToWorkList(Op.getNode());
4590     } else if (Op.getValueType().bitsGT(VT)) {
4591       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4592       AddToWorkList(Op.getNode());
4593     }
4594     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4595                                   N0.getValueType().getScalarType());
4596   }
4597
4598   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4599   // if either of the casts is not free.
4600   if (N0.getOpcode() == ISD::AND &&
4601       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4602       N0.getOperand(1).getOpcode() == ISD::Constant &&
4603       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4604                            N0.getValueType()) ||
4605        !TLI.isZExtFree(N0.getValueType(), VT))) {
4606     SDValue X = N0.getOperand(0).getOperand(0);
4607     if (X.getValueType().bitsLT(VT)) {
4608       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4609     } else if (X.getValueType().bitsGT(VT)) {
4610       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4611     }
4612     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4613     Mask = Mask.zext(VT.getSizeInBits());
4614     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4615                        X, DAG.getConstant(Mask, VT));
4616   }
4617
4618   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4619   // None of the supported targets knows how to perform load and vector_zext
4620   // on vectors in one instruction.  We only perform this transformation on
4621   // scalars.
4622   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4623       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4624        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4625     bool DoXform = true;
4626     SmallVector<SDNode*, 4> SetCCs;
4627     if (!N0.hasOneUse())
4628       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4629     if (DoXform) {
4630       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4631       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4632                                        LN0->getChain(),
4633                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4634                                        N0.getValueType(),
4635                                        LN0->isVolatile(), LN0->isNonTemporal(),
4636                                        LN0->getAlignment());
4637       CombineTo(N, ExtLoad);
4638       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4639                                   N0.getValueType(), ExtLoad);
4640       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4641
4642       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4643                       ISD::ZERO_EXTEND);
4644       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4645     }
4646   }
4647
4648   // fold (zext (and/or/xor (load x), cst)) ->
4649   //      (and/or/xor (zextload x), (zext cst))
4650   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4651        N0.getOpcode() == ISD::XOR) &&
4652       isa<LoadSDNode>(N0.getOperand(0)) &&
4653       N0.getOperand(1).getOpcode() == ISD::Constant &&
4654       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4655       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4656     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4657     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4658       bool DoXform = true;
4659       SmallVector<SDNode*, 4> SetCCs;
4660       if (!N0.hasOneUse())
4661         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4662                                           SetCCs, TLI);
4663       if (DoXform) {
4664         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4665                                          LN0->getChain(), LN0->getBasePtr(),
4666                                          LN0->getPointerInfo(),
4667                                          LN0->getMemoryVT(),
4668                                          LN0->isVolatile(),
4669                                          LN0->isNonTemporal(),
4670                                          LN0->getAlignment());
4671         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4672         Mask = Mask.zext(VT.getSizeInBits());
4673         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4674                                   ExtLoad, DAG.getConstant(Mask, VT));
4675         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4676                                     N0.getOperand(0).getDebugLoc(),
4677                                     N0.getOperand(0).getValueType(), ExtLoad);
4678         CombineTo(N, And);
4679         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4680         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4681                         ISD::ZERO_EXTEND);
4682         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4683       }
4684     }
4685   }
4686
4687   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4688   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4689   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4690       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4691     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4692     EVT MemVT = LN0->getMemoryVT();
4693     if ((!LegalOperations && !LN0->isVolatile()) ||
4694         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4695       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4696                                        LN0->getChain(),
4697                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4698                                        MemVT,
4699                                        LN0->isVolatile(), LN0->isNonTemporal(),
4700                                        LN0->getAlignment());
4701       CombineTo(N, ExtLoad);
4702       CombineTo(N0.getNode(),
4703                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4704                             ExtLoad),
4705                 ExtLoad.getValue(1));
4706       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4707     }
4708   }
4709
4710   if (N0.getOpcode() == ISD::SETCC) {
4711     if (!LegalOperations && VT.isVector()) {
4712       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4713       // Only do this before legalize for now.
4714       EVT N0VT = N0.getOperand(0).getValueType();
4715       EVT EltVT = VT.getVectorElementType();
4716       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4717                                     DAG.getConstant(1, EltVT));
4718       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4719         // We know that the # elements of the results is the same as the
4720         // # elements of the compare (and the # elements of the compare result
4721         // for that matter).  Check to see that they are the same size.  If so,
4722         // we know that the element size of the sext'd result matches the
4723         // element size of the compare operands.
4724         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4725                            DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4726                                          N0.getOperand(1),
4727                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4728                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4729                                        &OneOps[0], OneOps.size()));
4730
4731       // If the desired elements are smaller or larger than the source
4732       // elements we can use a matching integer vector type and then
4733       // truncate/sign extend
4734       EVT MatchingElementType =
4735         EVT::getIntegerVT(*DAG.getContext(),
4736                           N0VT.getScalarType().getSizeInBits());
4737       EVT MatchingVectorType =
4738         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4739                          N0VT.getVectorNumElements());
4740       SDValue VsetCC =
4741         DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4742                       N0.getOperand(1),
4743                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4744       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4745                          DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4746                          DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4747                                      &OneOps[0], OneOps.size()));
4748     }
4749
4750     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4751     SDValue SCC =
4752       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4753                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4754                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4755     if (SCC.getNode()) return SCC;
4756   }
4757
4758   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4759   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4760       isa<ConstantSDNode>(N0.getOperand(1)) &&
4761       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4762       N0.hasOneUse()) {
4763     SDValue ShAmt = N0.getOperand(1);
4764     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4765     if (N0.getOpcode() == ISD::SHL) {
4766       SDValue InnerZExt = N0.getOperand(0);
4767       // If the original shl may be shifting out bits, do not perform this
4768       // transformation.
4769       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4770         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4771       if (ShAmtVal > KnownZeroBits)
4772         return SDValue();
4773     }
4774
4775     DebugLoc DL = N->getDebugLoc();
4776
4777     // Ensure that the shift amount is wide enough for the shifted value.
4778     if (VT.getSizeInBits() >= 256)
4779       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4780
4781     return DAG.getNode(N0.getOpcode(), DL, VT,
4782                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4783                        ShAmt);
4784   }
4785
4786   return SDValue();
4787 }
4788
4789 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4790   SDValue N0 = N->getOperand(0);
4791   EVT VT = N->getValueType(0);
4792
4793   // fold (aext c1) -> c1
4794   if (isa<ConstantSDNode>(N0))
4795     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4796   // fold (aext (aext x)) -> (aext x)
4797   // fold (aext (zext x)) -> (zext x)
4798   // fold (aext (sext x)) -> (sext x)
4799   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4800       N0.getOpcode() == ISD::ZERO_EXTEND ||
4801       N0.getOpcode() == ISD::SIGN_EXTEND)
4802     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4803
4804   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4805   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4806   if (N0.getOpcode() == ISD::TRUNCATE) {
4807     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4808     if (NarrowLoad.getNode()) {
4809       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4810       if (NarrowLoad.getNode() != N0.getNode()) {
4811         CombineTo(N0.getNode(), NarrowLoad);
4812         // CombineTo deleted the truncate, if needed, but not what's under it.
4813         AddToWorkList(oye);
4814       }
4815       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4816     }
4817   }
4818
4819   // fold (aext (truncate x))
4820   if (N0.getOpcode() == ISD::TRUNCATE) {
4821     SDValue TruncOp = N0.getOperand(0);
4822     if (TruncOp.getValueType() == VT)
4823       return TruncOp; // x iff x size == zext size.
4824     if (TruncOp.getValueType().bitsGT(VT))
4825       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4826     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4827   }
4828
4829   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4830   // if the trunc is not free.
4831   if (N0.getOpcode() == ISD::AND &&
4832       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4833       N0.getOperand(1).getOpcode() == ISD::Constant &&
4834       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4835                           N0.getValueType())) {
4836     SDValue X = N0.getOperand(0).getOperand(0);
4837     if (X.getValueType().bitsLT(VT)) {
4838       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4839     } else if (X.getValueType().bitsGT(VT)) {
4840       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4841     }
4842     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4843     Mask = Mask.zext(VT.getSizeInBits());
4844     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4845                        X, DAG.getConstant(Mask, VT));
4846   }
4847
4848   // fold (aext (load x)) -> (aext (truncate (extload x)))
4849   // None of the supported targets knows how to perform load and any_ext
4850   // on vectors in one instruction.  We only perform this transformation on
4851   // scalars.
4852   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4853       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4854        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4855     bool DoXform = true;
4856     SmallVector<SDNode*, 4> SetCCs;
4857     if (!N0.hasOneUse())
4858       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4859     if (DoXform) {
4860       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4861       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4862                                        LN0->getChain(),
4863                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4864                                        N0.getValueType(),
4865                                        LN0->isVolatile(), LN0->isNonTemporal(),
4866                                        LN0->getAlignment());
4867       CombineTo(N, ExtLoad);
4868       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4869                                   N0.getValueType(), ExtLoad);
4870       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4871       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4872                       ISD::ANY_EXTEND);
4873       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4874     }
4875   }
4876
4877   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4878   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4879   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4880   if (N0.getOpcode() == ISD::LOAD &&
4881       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4882       N0.hasOneUse()) {
4883     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4884     EVT MemVT = LN0->getMemoryVT();
4885     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4886                                      VT, LN0->getChain(), LN0->getBasePtr(),
4887                                      LN0->getPointerInfo(), MemVT,
4888                                      LN0->isVolatile(), LN0->isNonTemporal(),
4889                                      LN0->getAlignment());
4890     CombineTo(N, ExtLoad);
4891     CombineTo(N0.getNode(),
4892               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4893                           N0.getValueType(), ExtLoad),
4894               ExtLoad.getValue(1));
4895     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4896   }
4897
4898   if (N0.getOpcode() == ISD::SETCC) {
4899     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4900     // Only do this before legalize for now.
4901     if (VT.isVector() && !LegalOperations) {
4902       EVT N0VT = N0.getOperand(0).getValueType();
4903         // We know that the # elements of the results is the same as the
4904         // # elements of the compare (and the # elements of the compare result
4905         // for that matter).  Check to see that they are the same size.  If so,
4906         // we know that the element size of the sext'd result matches the
4907         // element size of the compare operands.
4908       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4909         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4910                              N0.getOperand(1),
4911                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4912       // If the desired elements are smaller or larger than the source
4913       // elements we can use a matching integer vector type and then
4914       // truncate/sign extend
4915       else {
4916         EVT MatchingElementType =
4917           EVT::getIntegerVT(*DAG.getContext(),
4918                             N0VT.getScalarType().getSizeInBits());
4919         EVT MatchingVectorType =
4920           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4921                            N0VT.getVectorNumElements());
4922         SDValue VsetCC =
4923           DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4924                         N0.getOperand(1),
4925                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
4926         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4927       }
4928     }
4929
4930     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4931     SDValue SCC =
4932       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4933                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4934                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4935     if (SCC.getNode())
4936       return SCC;
4937   }
4938
4939   return SDValue();
4940 }
4941
4942 /// GetDemandedBits - See if the specified operand can be simplified with the
4943 /// knowledge that only the bits specified by Mask are used.  If so, return the
4944 /// simpler operand, otherwise return a null SDValue.
4945 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4946   switch (V.getOpcode()) {
4947   default: break;
4948   case ISD::Constant: {
4949     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4950     assert(CV != 0 && "Const value should be ConstSDNode.");
4951     const APInt &CVal = CV->getAPIntValue();
4952     APInt NewVal = CVal & Mask;
4953     if (NewVal != CVal) {
4954       return DAG.getConstant(NewVal, V.getValueType());
4955     }
4956     break;
4957   }
4958   case ISD::OR:
4959   case ISD::XOR:
4960     // If the LHS or RHS don't contribute bits to the or, drop them.
4961     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4962       return V.getOperand(1);
4963     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4964       return V.getOperand(0);
4965     break;
4966   case ISD::SRL:
4967     // Only look at single-use SRLs.
4968     if (!V.getNode()->hasOneUse())
4969       break;
4970     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4971       // See if we can recursively simplify the LHS.
4972       unsigned Amt = RHSC->getZExtValue();
4973
4974       // Watch out for shift count overflow though.
4975       if (Amt >= Mask.getBitWidth()) break;
4976       APInt NewMask = Mask << Amt;
4977       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4978       if (SimplifyLHS.getNode())
4979         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4980                            SimplifyLHS, V.getOperand(1));
4981     }
4982   }
4983   return SDValue();
4984 }
4985
4986 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4987 /// bits and then truncated to a narrower type and where N is a multiple
4988 /// of number of bits of the narrower type, transform it to a narrower load
4989 /// from address + N / num of bits of new type. If the result is to be
4990 /// extended, also fold the extension to form a extending load.
4991 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4992   unsigned Opc = N->getOpcode();
4993
4994   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4995   SDValue N0 = N->getOperand(0);
4996   EVT VT = N->getValueType(0);
4997   EVT ExtVT = VT;
4998
4999   // This transformation isn't valid for vector loads.
5000   if (VT.isVector())
5001     return SDValue();
5002
5003   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5004   // extended to VT.
5005   if (Opc == ISD::SIGN_EXTEND_INREG) {
5006     ExtType = ISD::SEXTLOAD;
5007     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5008   } else if (Opc == ISD::SRL) {
5009     // Another special-case: SRL is basically zero-extending a narrower value.
5010     ExtType = ISD::ZEXTLOAD;
5011     N0 = SDValue(N, 0);
5012     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5013     if (!N01) return SDValue();
5014     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5015                               VT.getSizeInBits() - N01->getZExtValue());
5016   }
5017   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5018     return SDValue();
5019
5020   unsigned EVTBits = ExtVT.getSizeInBits();
5021
5022   // Do not generate loads of non-round integer types since these can
5023   // be expensive (and would be wrong if the type is not byte sized).
5024   if (!ExtVT.isRound())
5025     return SDValue();
5026
5027   unsigned ShAmt = 0;
5028   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5029     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5030       ShAmt = N01->getZExtValue();
5031       // Is the shift amount a multiple of size of VT?
5032       if ((ShAmt & (EVTBits-1)) == 0) {
5033         N0 = N0.getOperand(0);
5034         // Is the load width a multiple of size of VT?
5035         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5036           return SDValue();
5037       }
5038
5039       // At this point, we must have a load or else we can't do the transform.
5040       if (!isa<LoadSDNode>(N0)) return SDValue();
5041
5042       // If the shift amount is larger than the input type then we're not
5043       // accessing any of the loaded bytes.  If the load was a zextload/extload
5044       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5045       // If the load was a sextload then the result is a splat of the sign bit
5046       // of the extended byte.  This is not worth optimizing for.
5047       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5048         return SDValue();
5049     }
5050   }
5051
5052   // If the load is shifted left (and the result isn't shifted back right),
5053   // we can fold the truncate through the shift.
5054   unsigned ShLeftAmt = 0;
5055   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5056       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5057     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5058       ShLeftAmt = N01->getZExtValue();
5059       N0 = N0.getOperand(0);
5060     }
5061   }
5062
5063   // If we haven't found a load, we can't narrow it.  Don't transform one with
5064   // multiple uses, this would require adding a new load.
5065   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
5066       // Don't change the width of a volatile load.
5067       cast<LoadSDNode>(N0)->isVolatile())
5068     return SDValue();
5069
5070   // Verify that we are actually reducing a load width here.
5071   if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
5072     return SDValue();
5073
5074   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5075   EVT PtrType = N0.getOperand(1).getValueType();
5076
5077   if (PtrType == MVT::Untyped || PtrType.isExtended())
5078     // It's not possible to generate a constant of extended or untyped type.
5079     return SDValue();
5080
5081   // For big endian targets, we need to adjust the offset to the pointer to
5082   // load the correct bytes.
5083   if (TLI.isBigEndian()) {
5084     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5085     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5086     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5087   }
5088
5089   uint64_t PtrOff = ShAmt / 8;
5090   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5091   SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5092                                PtrType, LN0->getBasePtr(),
5093                                DAG.getConstant(PtrOff, PtrType));
5094   AddToWorkList(NewPtr.getNode());
5095
5096   SDValue Load;
5097   if (ExtType == ISD::NON_EXTLOAD)
5098     Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5099                         LN0->getPointerInfo().getWithOffset(PtrOff),
5100                         LN0->isVolatile(), LN0->isNonTemporal(),
5101                         LN0->isInvariant(), NewAlign);
5102   else
5103     Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5104                           LN0->getPointerInfo().getWithOffset(PtrOff),
5105                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5106                           NewAlign);
5107
5108   // Replace the old load's chain with the new load's chain.
5109   WorkListRemover DeadNodes(*this);
5110   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5111
5112   // Shift the result left, if we've swallowed a left shift.
5113   SDValue Result = Load;
5114   if (ShLeftAmt != 0) {
5115     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5116     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5117       ShImmTy = VT;
5118     Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5119                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5120   }
5121
5122   // Return the new loaded value.
5123   return Result;
5124 }
5125
5126 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5127   SDValue N0 = N->getOperand(0);
5128   SDValue N1 = N->getOperand(1);
5129   EVT VT = N->getValueType(0);
5130   EVT EVT = cast<VTSDNode>(N1)->getVT();
5131   unsigned VTBits = VT.getScalarType().getSizeInBits();
5132   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5133
5134   // fold (sext_in_reg c1) -> c1
5135   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5136     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5137
5138   // If the input is already sign extended, just drop the extension.
5139   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5140     return N0;
5141
5142   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5143   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5144       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5145     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5146                        N0.getOperand(0), N1);
5147   }
5148
5149   // fold (sext_in_reg (sext x)) -> (sext x)
5150   // fold (sext_in_reg (aext x)) -> (sext x)
5151   // if x is small enough.
5152   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5153     SDValue N00 = N0.getOperand(0);
5154     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5155         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5156       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5157   }
5158
5159   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5160   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5161     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5162
5163   // fold operands of sext_in_reg based on knowledge that the top bits are not
5164   // demanded.
5165   if (SimplifyDemandedBits(SDValue(N, 0)))
5166     return SDValue(N, 0);
5167
5168   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5169   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5170   SDValue NarrowLoad = ReduceLoadWidth(N);
5171   if (NarrowLoad.getNode())
5172     return NarrowLoad;
5173
5174   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5175   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5176   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5177   if (N0.getOpcode() == ISD::SRL) {
5178     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5179       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5180         // We can turn this into an SRA iff the input to the SRL is already sign
5181         // extended enough.
5182         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5183         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5184           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5185                              N0.getOperand(0), N0.getOperand(1));
5186       }
5187   }
5188
5189   // fold (sext_inreg (extload x)) -> (sextload x)
5190   if (ISD::isEXTLoad(N0.getNode()) &&
5191       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5192       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5193       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5194        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5195     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5196     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5197                                      LN0->getChain(),
5198                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5199                                      EVT,
5200                                      LN0->isVolatile(), LN0->isNonTemporal(),
5201                                      LN0->getAlignment());
5202     CombineTo(N, ExtLoad);
5203     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5204     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5205   }
5206   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5207   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5208       N0.hasOneUse() &&
5209       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5210       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5211        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5212     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5213     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5214                                      LN0->getChain(),
5215                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5216                                      EVT,
5217                                      LN0->isVolatile(), LN0->isNonTemporal(),
5218                                      LN0->getAlignment());
5219     CombineTo(N, ExtLoad);
5220     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5221     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5222   }
5223
5224   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5225   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5226     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5227                                        N0.getOperand(1), false);
5228     if (BSwap.getNode() != 0)
5229       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5230                          BSwap, N1);
5231   }
5232
5233   return SDValue();
5234 }
5235
5236 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5237   SDValue N0 = N->getOperand(0);
5238   EVT VT = N->getValueType(0);
5239   bool isLE = TLI.isLittleEndian();
5240
5241   // noop truncate
5242   if (N0.getValueType() == N->getValueType(0))
5243     return N0;
5244   // fold (truncate c1) -> c1
5245   if (isa<ConstantSDNode>(N0))
5246     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5247   // fold (truncate (truncate x)) -> (truncate x)
5248   if (N0.getOpcode() == ISD::TRUNCATE)
5249     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5250   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5251   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5252       N0.getOpcode() == ISD::SIGN_EXTEND ||
5253       N0.getOpcode() == ISD::ANY_EXTEND) {
5254     if (N0.getOperand(0).getValueType().bitsLT(VT))
5255       // if the source is smaller than the dest, we still need an extend
5256       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5257                          N0.getOperand(0));
5258     else if (N0.getOperand(0).getValueType().bitsGT(VT))
5259       // if the source is larger than the dest, than we just need the truncate
5260       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5261     else
5262       // if the source and dest are the same type, we can drop both the extend
5263       // and the truncate.
5264       return N0.getOperand(0);
5265   }
5266
5267   // Fold extract-and-trunc into a narrow extract. For example:
5268   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5269   //   i32 y = TRUNCATE(i64 x)
5270   //        -- becomes --
5271   //   v16i8 b = BITCAST (v2i64 val)
5272   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5273   //
5274   // Note: We only run this optimization after type legalization (which often
5275   // creates this pattern) and before operation legalization after which
5276   // we need to be more careful about the vector instructions that we generate.
5277   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5278       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5279
5280     EVT VecTy = N0.getOperand(0).getValueType();
5281     EVT ExTy = N0.getValueType();
5282     EVT TrTy = N->getValueType(0);
5283
5284     unsigned NumElem = VecTy.getVectorNumElements();
5285     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5286
5287     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5288     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5289
5290     SDValue EltNo = N0->getOperand(1);
5291     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5292       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5293       EVT IndexTy = N0->getOperand(1).getValueType();
5294       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5295
5296       SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5297                               NVT, N0.getOperand(0));
5298
5299       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5300                          N->getDebugLoc(), TrTy, V,
5301                          DAG.getConstant(Index, IndexTy));
5302     }
5303   }
5304
5305   // See if we can simplify the input to this truncate through knowledge that
5306   // only the low bits are being used.
5307   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5308   // Currently we only perform this optimization on scalars because vectors
5309   // may have different active low bits.
5310   if (!VT.isVector()) {
5311     SDValue Shorter =
5312       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5313                                                VT.getSizeInBits()));
5314     if (Shorter.getNode())
5315       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5316   }
5317   // fold (truncate (load x)) -> (smaller load x)
5318   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5319   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5320     SDValue Reduced = ReduceLoadWidth(N);
5321     if (Reduced.getNode())
5322       return Reduced;
5323   }
5324
5325   // Simplify the operands using demanded-bits information.
5326   if (!VT.isVector() &&
5327       SimplifyDemandedBits(SDValue(N, 0)))
5328     return SDValue(N, 0);
5329
5330   return SDValue();
5331 }
5332
5333 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5334   SDValue Elt = N->getOperand(i);
5335   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5336     return Elt.getNode();
5337   return Elt.getOperand(Elt.getResNo()).getNode();
5338 }
5339
5340 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5341 /// if load locations are consecutive.
5342 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5343   assert(N->getOpcode() == ISD::BUILD_PAIR);
5344
5345   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5346   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5347   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5348       LD1->getPointerInfo().getAddrSpace() !=
5349          LD2->getPointerInfo().getAddrSpace())
5350     return SDValue();
5351   EVT LD1VT = LD1->getValueType(0);
5352
5353   if (ISD::isNON_EXTLoad(LD2) &&
5354       LD2->hasOneUse() &&
5355       // If both are volatile this would reduce the number of volatile loads.
5356       // If one is volatile it might be ok, but play conservative and bail out.
5357       !LD1->isVolatile() &&
5358       !LD2->isVolatile() &&
5359       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5360     unsigned Align = LD1->getAlignment();
5361     unsigned NewAlign = TLI.getTargetData()->
5362       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5363
5364     if (NewAlign <= Align &&
5365         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5366       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5367                          LD1->getBasePtr(), LD1->getPointerInfo(),
5368                          false, false, false, Align);
5369   }
5370
5371   return SDValue();
5372 }
5373
5374 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5375   SDValue N0 = N->getOperand(0);
5376   EVT VT = N->getValueType(0);
5377
5378   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5379   // Only do this before legalize, since afterward the target may be depending
5380   // on the bitconvert.
5381   // First check to see if this is all constant.
5382   if (!LegalTypes &&
5383       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5384       VT.isVector()) {
5385     bool isSimple = true;
5386     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5387       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5388           N0.getOperand(i).getOpcode() != ISD::Constant &&
5389           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5390         isSimple = false;
5391         break;
5392       }
5393
5394     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5395     assert(!DestEltVT.isVector() &&
5396            "Element type of vector ValueType must not be vector!");
5397     if (isSimple)
5398       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5399   }
5400
5401   // If the input is a constant, let getNode fold it.
5402   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5403     SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5404     if (Res.getNode() != N) {
5405       if (!LegalOperations ||
5406           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5407         return Res;
5408
5409       // Folding it resulted in an illegal node, and it's too late to
5410       // do that. Clean up the old node and forego the transformation.
5411       // Ideally this won't happen very often, because instcombine
5412       // and the earlier dagcombine runs (where illegal nodes are
5413       // permitted) should have folded most of them already.
5414       DAG.DeleteNode(Res.getNode());
5415     }
5416   }
5417
5418   // (conv (conv x, t1), t2) -> (conv x, t2)
5419   if (N0.getOpcode() == ISD::BITCAST)
5420     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5421                        N0.getOperand(0));
5422
5423   // fold (conv (load x)) -> (load (conv*)x)
5424   // If the resultant load doesn't need a higher alignment than the original!
5425   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5426       // Do not change the width of a volatile load.
5427       !cast<LoadSDNode>(N0)->isVolatile() &&
5428       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5429     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5430     unsigned Align = TLI.getTargetData()->
5431       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5432     unsigned OrigAlign = LN0->getAlignment();
5433
5434     if (Align <= OrigAlign) {
5435       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5436                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5437                                  LN0->isVolatile(), LN0->isNonTemporal(),
5438                                  LN0->isInvariant(), OrigAlign);
5439       AddToWorkList(N);
5440       CombineTo(N0.getNode(),
5441                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5442                             N0.getValueType(), Load),
5443                 Load.getValue(1));
5444       return Load;
5445     }
5446   }
5447
5448   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5449   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5450   // This often reduces constant pool loads.
5451   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5452        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5453       N0.getNode()->hasOneUse() && VT.isInteger() &&
5454       !VT.isVector() && !N0.getValueType().isVector()) {
5455     SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5456                                   N0.getOperand(0));
5457     AddToWorkList(NewConv.getNode());
5458
5459     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5460     if (N0.getOpcode() == ISD::FNEG)
5461       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5462                          NewConv, DAG.getConstant(SignBit, VT));
5463     assert(N0.getOpcode() == ISD::FABS);
5464     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5465                        NewConv, DAG.getConstant(~SignBit, VT));
5466   }
5467
5468   // fold (bitconvert (fcopysign cst, x)) ->
5469   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5470   // Note that we don't handle (copysign x, cst) because this can always be
5471   // folded to an fneg or fabs.
5472   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5473       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5474       VT.isInteger() && !VT.isVector()) {
5475     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5476     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5477     if (isTypeLegal(IntXVT)) {
5478       SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5479                               IntXVT, N0.getOperand(1));
5480       AddToWorkList(X.getNode());
5481
5482       // If X has a different width than the result/lhs, sext it or truncate it.
5483       unsigned VTWidth = VT.getSizeInBits();
5484       if (OrigXWidth < VTWidth) {
5485         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5486         AddToWorkList(X.getNode());
5487       } else if (OrigXWidth > VTWidth) {
5488         // To get the sign bit in the right place, we have to shift it right
5489         // before truncating.
5490         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5491                         X.getValueType(), X,
5492                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5493         AddToWorkList(X.getNode());
5494         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5495         AddToWorkList(X.getNode());
5496       }
5497
5498       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5499       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5500                       X, DAG.getConstant(SignBit, VT));
5501       AddToWorkList(X.getNode());
5502
5503       SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5504                                 VT, N0.getOperand(0));
5505       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5506                         Cst, DAG.getConstant(~SignBit, VT));
5507       AddToWorkList(Cst.getNode());
5508
5509       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5510     }
5511   }
5512
5513   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5514   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5515     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5516     if (CombineLD.getNode())
5517       return CombineLD;
5518   }
5519
5520   return SDValue();
5521 }
5522
5523 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5524   EVT VT = N->getValueType(0);
5525   return CombineConsecutiveLoads(N, VT);
5526 }
5527
5528 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5529 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5530 /// destination element value type.
5531 SDValue DAGCombiner::
5532 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5533   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5534
5535   // If this is already the right type, we're done.
5536   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5537
5538   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5539   unsigned DstBitSize = DstEltVT.getSizeInBits();
5540
5541   // If this is a conversion of N elements of one type to N elements of another
5542   // type, convert each element.  This handles FP<->INT cases.
5543   if (SrcBitSize == DstBitSize) {
5544     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5545                               BV->getValueType(0).getVectorNumElements());
5546
5547     // Due to the FP element handling below calling this routine recursively,
5548     // we can end up with a scalar-to-vector node here.
5549     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5550       return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5551                          DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5552                                      DstEltVT, BV->getOperand(0)));
5553
5554     SmallVector<SDValue, 8> Ops;
5555     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5556       SDValue Op = BV->getOperand(i);
5557       // If the vector element type is not legal, the BUILD_VECTOR operands
5558       // are promoted and implicitly truncated.  Make that explicit here.
5559       if (Op.getValueType() != SrcEltVT)
5560         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5561       Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5562                                 DstEltVT, Op));
5563       AddToWorkList(Ops.back().getNode());
5564     }
5565     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5566                        &Ops[0], Ops.size());
5567   }
5568
5569   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5570   // handle annoying details of growing/shrinking FP values, we convert them to
5571   // int first.
5572   if (SrcEltVT.isFloatingPoint()) {
5573     // Convert the input float vector to a int vector where the elements are the
5574     // same sizes.
5575     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5576     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5577     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5578     SrcEltVT = IntVT;
5579   }
5580
5581   // Now we know the input is an integer vector.  If the output is a FP type,
5582   // convert to integer first, then to FP of the right size.
5583   if (DstEltVT.isFloatingPoint()) {
5584     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5585     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5586     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5587
5588     // Next, convert to FP elements of the same size.
5589     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5590   }
5591
5592   // Okay, we know the src/dst types are both integers of differing types.
5593   // Handling growing first.
5594   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5595   if (SrcBitSize < DstBitSize) {
5596     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5597
5598     SmallVector<SDValue, 8> Ops;
5599     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5600          i += NumInputsPerOutput) {
5601       bool isLE = TLI.isLittleEndian();
5602       APInt NewBits = APInt(DstBitSize, 0);
5603       bool EltIsUndef = true;
5604       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5605         // Shift the previously computed bits over.
5606         NewBits <<= SrcBitSize;
5607         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5608         if (Op.getOpcode() == ISD::UNDEF) continue;
5609         EltIsUndef = false;
5610
5611         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5612                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5613       }
5614
5615       if (EltIsUndef)
5616         Ops.push_back(DAG.getUNDEF(DstEltVT));
5617       else
5618         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5619     }
5620
5621     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5622     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5623                        &Ops[0], Ops.size());
5624   }
5625
5626   // Finally, this must be the case where we are shrinking elements: each input
5627   // turns into multiple outputs.
5628   bool isS2V = ISD::isScalarToVector(BV);
5629   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5630   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5631                             NumOutputsPerInput*BV->getNumOperands());
5632   SmallVector<SDValue, 8> Ops;
5633
5634   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5635     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5636       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5637         Ops.push_back(DAG.getUNDEF(DstEltVT));
5638       continue;
5639     }
5640
5641     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5642                   getAPIntValue().zextOrTrunc(SrcBitSize);
5643
5644     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5645       APInt ThisVal = OpVal.trunc(DstBitSize);
5646       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5647       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5648         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5649         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5650                            Ops[0]);
5651       OpVal = OpVal.lshr(DstBitSize);
5652     }
5653
5654     // For big endian targets, swap the order of the pieces of each element.
5655     if (TLI.isBigEndian())
5656       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5657   }
5658
5659   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5660                      &Ops[0], Ops.size());
5661 }
5662
5663 SDValue DAGCombiner::visitFADD(SDNode *N) {
5664   SDValue N0 = N->getOperand(0);
5665   SDValue N1 = N->getOperand(1);
5666   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5667   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5668   EVT VT = N->getValueType(0);
5669
5670   // fold vector ops
5671   if (VT.isVector()) {
5672     SDValue FoldedVOp = SimplifyVBinOp(N);
5673     if (FoldedVOp.getNode()) return FoldedVOp;
5674   }
5675
5676   // fold (fadd c1, c2) -> c1 + c2
5677   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5678     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5679   // canonicalize constant to RHS
5680   if (N0CFP && !N1CFP)
5681     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5682   // fold (fadd A, 0) -> A
5683   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5684       N1CFP->getValueAPF().isZero())
5685     return N0;
5686   // fold (fadd A, (fneg B)) -> (fsub A, B)
5687   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5688     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5689     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5690                        GetNegatedExpression(N1, DAG, LegalOperations));
5691   // fold (fadd (fneg A), B) -> (fsub B, A)
5692   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5693     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5694     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5695                        GetNegatedExpression(N0, DAG, LegalOperations));
5696
5697   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5698   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5699       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5700       isa<ConstantFPSDNode>(N0.getOperand(1)))
5701     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5702                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5703                                    N0.getOperand(1), N1));
5704
5705   // In unsafe math mode, we can fold chains of FADD's of the same value
5706   // into multiplications.  This transform is not safe in general because
5707   // we are reducing the number of rounding steps.
5708   if (DAG.getTarget().Options.UnsafeFPMath &&
5709       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5710       !N0CFP && !N1CFP) {
5711     if (N0.getOpcode() == ISD::FMUL) {
5712       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5713       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5714
5715       // (fadd (fmul c, x), x) -> (fmul c+1, x)
5716       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5717         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5718                                      SDValue(CFP00, 0),
5719                                      DAG.getConstantFP(1.0, VT));
5720         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5721                            N1, NewCFP);
5722       }
5723
5724       // (fadd (fmul x, c), x) -> (fmul c+1, x)
5725       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5726         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5727                                      SDValue(CFP01, 0),
5728                                      DAG.getConstantFP(1.0, VT));
5729         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5730                            N1, NewCFP);
5731       }
5732
5733       // (fadd (fadd x, x), x) -> (fmul 3.0, x)
5734       if (!CFP00 && !CFP01 && N0.getOperand(0) == N0.getOperand(1) &&
5735           N0.getOperand(0) == N1) {
5736         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5737                            N1, DAG.getConstantFP(3.0, VT));
5738       }
5739
5740       // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x)
5741       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5742           N1.getOperand(0) == N1.getOperand(1) &&
5743           N0.getOperand(1) == N1.getOperand(0)) {
5744         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5745                                      SDValue(CFP00, 0),
5746                                      DAG.getConstantFP(2.0, VT));
5747         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5748                            N0.getOperand(1), NewCFP);
5749       }
5750
5751       // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x)
5752       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5753           N1.getOperand(0) == N1.getOperand(1) &&
5754           N0.getOperand(0) == N1.getOperand(0)) {
5755         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5756                                      SDValue(CFP01, 0),
5757                                      DAG.getConstantFP(2.0, VT));
5758         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5759                            N0.getOperand(0), NewCFP);
5760       }
5761     }
5762
5763     if (N1.getOpcode() == ISD::FMUL) {
5764       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5765       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
5766
5767       // (fadd x, (fmul c, x)) -> (fmul c+1, x)
5768       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
5769         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5770                                      SDValue(CFP10, 0),
5771                                      DAG.getConstantFP(1.0, VT));
5772         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5773                            N0, NewCFP);
5774       }
5775
5776       // (fadd x, (fmul x, c)) -> (fmul c+1, x)
5777       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
5778         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5779                                      SDValue(CFP11, 0),
5780                                      DAG.getConstantFP(1.0, VT));
5781         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5782                            N0, NewCFP);
5783       }
5784
5785       // (fadd x, (fadd x, x)) -> (fmul 3.0, x)
5786       if (!CFP10 && !CFP11 && N1.getOperand(0) == N1.getOperand(1) &&
5787           N1.getOperand(0) == N0) {
5788         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5789                            N0, DAG.getConstantFP(3.0, VT));
5790       }
5791
5792       // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x)
5793       if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD &&
5794           N1.getOperand(0) == N1.getOperand(1) &&
5795           N0.getOperand(1) == N1.getOperand(0)) {
5796         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5797                                      SDValue(CFP10, 0),
5798                                      DAG.getConstantFP(2.0, VT));
5799         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5800                            N0.getOperand(1), NewCFP);
5801       }
5802
5803       // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x)
5804       if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD &&
5805           N1.getOperand(0) == N1.getOperand(1) &&
5806           N0.getOperand(0) == N1.getOperand(0)) {
5807         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5808                                      SDValue(CFP11, 0),
5809                                      DAG.getConstantFP(2.0, VT));
5810         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5811                            N0.getOperand(0), NewCFP);
5812       }
5813     }
5814
5815     // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x)
5816     if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
5817         N0.getOperand(0) == N0.getOperand(1) &&
5818         N1.getOperand(0) == N1.getOperand(1) &&
5819         N0.getOperand(0) == N1.getOperand(0)) {
5820       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5821                          N0.getOperand(0),
5822                          DAG.getConstantFP(4.0, VT));
5823     }
5824   }
5825
5826   // FADD -> FMA combines:
5827   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5828        DAG.getTarget().Options.UnsafeFPMath) &&
5829       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5830       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5831
5832     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5833     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5834       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5835                          N0.getOperand(0), N0.getOperand(1), N1);
5836     }
5837
5838     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
5839     // Note: Commutes FADD operands.
5840     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5841       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5842                          N1.getOperand(0), N1.getOperand(1), N0);
5843     }
5844   }
5845
5846   return SDValue();
5847 }
5848
5849 SDValue DAGCombiner::visitFSUB(SDNode *N) {
5850   SDValue N0 = N->getOperand(0);
5851   SDValue N1 = N->getOperand(1);
5852   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5853   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5854   EVT VT = N->getValueType(0);
5855   DebugLoc dl = N->getDebugLoc();
5856
5857   // fold vector ops
5858   if (VT.isVector()) {
5859     SDValue FoldedVOp = SimplifyVBinOp(N);
5860     if (FoldedVOp.getNode()) return FoldedVOp;
5861   }
5862
5863   // fold (fsub c1, c2) -> c1-c2
5864   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5865     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5866   // fold (fsub A, 0) -> A
5867   if (DAG.getTarget().Options.UnsafeFPMath &&
5868       N1CFP && N1CFP->getValueAPF().isZero())
5869     return N0;
5870   // fold (fsub 0, B) -> -B
5871   if (DAG.getTarget().Options.UnsafeFPMath &&
5872       N0CFP && N0CFP->getValueAPF().isZero()) {
5873     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5874       return GetNegatedExpression(N1, DAG, LegalOperations);
5875     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5876       return DAG.getNode(ISD::FNEG, dl, VT, N1);
5877   }
5878   // fold (fsub A, (fneg B)) -> (fadd A, B)
5879   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5880     return DAG.getNode(ISD::FADD, dl, VT, N0,
5881                        GetNegatedExpression(N1, DAG, LegalOperations));
5882
5883   // If 'unsafe math' is enabled, fold
5884   //    (fsub x, x) -> 0.0 &
5885   //    (fsub x, (fadd x, y)) -> (fneg y) &
5886   //    (fsub x, (fadd y, x)) -> (fneg y)
5887   if (DAG.getTarget().Options.UnsafeFPMath) {
5888     if (N0 == N1)
5889       return DAG.getConstantFP(0.0f, VT);
5890
5891     if (N1.getOpcode() == ISD::FADD) {
5892       SDValue N10 = N1->getOperand(0);
5893       SDValue N11 = N1->getOperand(1);
5894
5895       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
5896                                           &DAG.getTarget().Options))
5897         return GetNegatedExpression(N11, DAG, LegalOperations);
5898       else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
5899                                                &DAG.getTarget().Options))
5900         return GetNegatedExpression(N10, DAG, LegalOperations);
5901     }
5902   }
5903
5904   // FSUB -> FMA combines:
5905   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5906        DAG.getTarget().Options.UnsafeFPMath) &&
5907       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5908       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5909
5910     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
5911     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5912       return DAG.getNode(ISD::FMA, dl, VT,
5913                          N0.getOperand(0), N0.getOperand(1),
5914                          DAG.getNode(ISD::FNEG, dl, VT, N1));
5915     }
5916
5917     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
5918     // Note: Commutes FSUB operands.
5919     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5920       return DAG.getNode(ISD::FMA, dl, VT,
5921                          DAG.getNode(ISD::FNEG, dl, VT,
5922                          N1.getOperand(0)),
5923                          N1.getOperand(1), N0);
5924     }
5925
5926     // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
5927     if (N0.getOpcode() == ISD::FNEG && 
5928         N0.getOperand(0).getOpcode() == ISD::FMUL &&
5929         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
5930       SDValue N00 = N0.getOperand(0).getOperand(0);
5931       SDValue N01 = N0.getOperand(0).getOperand(1);
5932       return DAG.getNode(ISD::FMA, dl, VT,
5933                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
5934                          DAG.getNode(ISD::FNEG, dl, VT, N1));
5935     }
5936   }
5937
5938   return SDValue();
5939 }
5940
5941 SDValue DAGCombiner::visitFMUL(SDNode *N) {
5942   SDValue N0 = N->getOperand(0);
5943   SDValue N1 = N->getOperand(1);
5944   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5945   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5946   EVT VT = N->getValueType(0);
5947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5948
5949   // fold vector ops
5950   if (VT.isVector()) {
5951     SDValue FoldedVOp = SimplifyVBinOp(N);
5952     if (FoldedVOp.getNode()) return FoldedVOp;
5953   }
5954
5955   // fold (fmul c1, c2) -> c1*c2
5956   if (N0CFP && N1CFP && VT != MVT::ppcf128)
5957     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5958   // canonicalize constant to RHS
5959   if (N0CFP && !N1CFP)
5960     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5961   // fold (fmul A, 0) -> 0
5962   if (DAG.getTarget().Options.UnsafeFPMath &&
5963       N1CFP && N1CFP->getValueAPF().isZero())
5964     return N1;
5965   // fold (fmul A, 0) -> 0, vector edition.
5966   if (DAG.getTarget().Options.UnsafeFPMath &&
5967       ISD::isBuildVectorAllZeros(N1.getNode()))
5968     return N1;
5969   // fold (fmul A, 1.0) -> A
5970   if (N1CFP && N1CFP->isExactlyValue(1.0))
5971     return N0;
5972   // fold (fmul X, 2.0) -> (fadd X, X)
5973   if (N1CFP && N1CFP->isExactlyValue(+2.0))
5974     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5975   // fold (fmul X, -1.0) -> (fneg X)
5976   if (N1CFP && N1CFP->isExactlyValue(-1.0))
5977     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5978       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5979
5980   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5981   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5982                                        &DAG.getTarget().Options)) {
5983     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 
5984                                          &DAG.getTarget().Options)) {
5985       // Both can be negated for free, check to see if at least one is cheaper
5986       // negated.
5987       if (LHSNeg == 2 || RHSNeg == 2)
5988         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5989                            GetNegatedExpression(N0, DAG, LegalOperations),
5990                            GetNegatedExpression(N1, DAG, LegalOperations));
5991     }
5992   }
5993
5994   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5995   if (DAG.getTarget().Options.UnsafeFPMath &&
5996       N1CFP && N0.getOpcode() == ISD::FMUL &&
5997       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5998     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5999                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6000                                    N0.getOperand(1), N1));
6001
6002   return SDValue();
6003 }
6004
6005 SDValue DAGCombiner::visitFMA(SDNode *N) {
6006   SDValue N0 = N->getOperand(0);
6007   SDValue N1 = N->getOperand(1);
6008   SDValue N2 = N->getOperand(2);
6009   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6010   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6011   EVT VT = N->getValueType(0);
6012   DebugLoc dl = N->getDebugLoc();
6013
6014   if (N0CFP && N0CFP->isExactlyValue(1.0))
6015     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
6016   if (N1CFP && N1CFP->isExactlyValue(1.0))
6017     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
6018
6019   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6020   if (N0CFP && !N1CFP)
6021     return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
6022
6023   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6024   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6025       N2.getOpcode() == ISD::FMUL &&
6026       N0 == N2.getOperand(0) &&
6027       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6028     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6029                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6030   }
6031
6032
6033   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6034   if (DAG.getTarget().Options.UnsafeFPMath &&
6035       N0.getOpcode() == ISD::FMUL && N1CFP &&
6036       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6037     return DAG.getNode(ISD::FMA, dl, VT,
6038                        N0.getOperand(0),
6039                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6040                        N2);
6041   }
6042
6043   // (fma x, 1, y) -> (fadd x, y)
6044   // (fma x, -1, y) -> (fadd (fneg x), y)
6045   if (N1CFP) {
6046     if (N1CFP->isExactlyValue(1.0))
6047       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6048
6049     if (N1CFP->isExactlyValue(-1.0) &&
6050         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6051       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6052       AddToWorkList(RHSNeg.getNode());
6053       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6054     }
6055   }
6056
6057   // (fma x, c, x) -> (fmul x, (c+1))
6058   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6059     return DAG.getNode(ISD::FMUL, dl, VT,
6060                        N0,
6061                        DAG.getNode(ISD::FADD, dl, VT,
6062                                    N1, DAG.getConstantFP(1.0, VT)));
6063   }
6064
6065   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6066   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6067       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6068     return DAG.getNode(ISD::FMUL, dl, VT,
6069                        N0,
6070                        DAG.getNode(ISD::FADD, dl, VT,
6071                                    N1, DAG.getConstantFP(-1.0, VT)));
6072   }
6073
6074
6075   return SDValue();
6076 }
6077
6078 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6079   SDValue N0 = N->getOperand(0);
6080   SDValue N1 = N->getOperand(1);
6081   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6082   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6083   EVT VT = N->getValueType(0);
6084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6085
6086   // fold vector ops
6087   if (VT.isVector()) {
6088     SDValue FoldedVOp = SimplifyVBinOp(N);
6089     if (FoldedVOp.getNode()) return FoldedVOp;
6090   }
6091
6092   // fold (fdiv c1, c2) -> c1/c2
6093   if (N0CFP && N1CFP && VT != MVT::ppcf128)
6094     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
6095
6096   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6097   if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) {
6098     // Compute the reciprocal 1.0 / c2.
6099     APFloat N1APF = N1CFP->getValueAPF();
6100     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6101     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6102     // Only do the transform if the reciprocal is a legal fp immediate that
6103     // isn't too nasty (eg NaN, denormal, ...).
6104     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6105         (!LegalOperations ||
6106          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6107          // backend)... we should handle this gracefully after Legalize.
6108          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6109          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6110          TLI.isFPImmLegal(Recip, VT)))
6111       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
6112                          DAG.getConstantFP(Recip, VT));
6113   }
6114
6115   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6116   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6117                                        &DAG.getTarget().Options)) {
6118     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6119                                          &DAG.getTarget().Options)) {
6120       // Both can be negated for free, check to see if at least one is cheaper
6121       // negated.
6122       if (LHSNeg == 2 || RHSNeg == 2)
6123         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
6124                            GetNegatedExpression(N0, DAG, LegalOperations),
6125                            GetNegatedExpression(N1, DAG, LegalOperations));
6126     }
6127   }
6128
6129   return SDValue();
6130 }
6131
6132 SDValue DAGCombiner::visitFREM(SDNode *N) {
6133   SDValue N0 = N->getOperand(0);
6134   SDValue N1 = N->getOperand(1);
6135   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6136   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6137   EVT VT = N->getValueType(0);
6138
6139   // fold (frem c1, c2) -> fmod(c1,c2)
6140   if (N0CFP && N1CFP && VT != MVT::ppcf128)
6141     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
6142
6143   return SDValue();
6144 }
6145
6146 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6147   SDValue N0 = N->getOperand(0);
6148   SDValue N1 = N->getOperand(1);
6149   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6150   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6151   EVT VT = N->getValueType(0);
6152
6153   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
6154     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
6155
6156   if (N1CFP) {
6157     const APFloat& V = N1CFP->getValueAPF();
6158     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6159     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6160     if (!V.isNegative()) {
6161       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6162         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6163     } else {
6164       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6165         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6166                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
6167     }
6168   }
6169
6170   // copysign(fabs(x), y) -> copysign(x, y)
6171   // copysign(fneg(x), y) -> copysign(x, y)
6172   // copysign(copysign(x,z), y) -> copysign(x, y)
6173   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6174       N0.getOpcode() == ISD::FCOPYSIGN)
6175     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6176                        N0.getOperand(0), N1);
6177
6178   // copysign(x, abs(y)) -> abs(x)
6179   if (N1.getOpcode() == ISD::FABS)
6180     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6181
6182   // copysign(x, copysign(y,z)) -> copysign(x, z)
6183   if (N1.getOpcode() == ISD::FCOPYSIGN)
6184     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6185                        N0, N1.getOperand(1));
6186
6187   // copysign(x, fp_extend(y)) -> copysign(x, y)
6188   // copysign(x, fp_round(y)) -> copysign(x, y)
6189   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6190     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6191                        N0, N1.getOperand(0));
6192
6193   return SDValue();
6194 }
6195
6196 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6197   SDValue N0 = N->getOperand(0);
6198   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6199   EVT VT = N->getValueType(0);
6200   EVT OpVT = N0.getValueType();
6201
6202   // fold (sint_to_fp c1) -> c1fp
6203   if (N0C && OpVT != MVT::ppcf128 &&
6204       // ...but only if the target supports immediate floating-point values
6205       (!LegalOperations ||
6206        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6207     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6208
6209   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6210   // but UINT_TO_FP is legal on this target, try to convert.
6211   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6212       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6213     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6214     if (DAG.SignBitIsZero(N0))
6215       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6216   }
6217
6218   // The next optimizations are desireable only if SELECT_CC can be lowered.
6219   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6220   // having to say they don't support SELECT_CC on every type the DAG knows
6221   // about, since there is no way to mark an opcode illegal at all value types
6222   // (See also visitSELECT)
6223   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6224     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6225     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6226         !VT.isVector() &&
6227         (!LegalOperations ||
6228          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6229       SDValue Ops[] =
6230         { N0.getOperand(0), N0.getOperand(1),
6231           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6232           N0.getOperand(2) };
6233       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6234     }
6235
6236     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6237     //      (select_cc x, y, 1.0, 0.0,, cc)
6238     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6239         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6240         (!LegalOperations ||
6241          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6242       SDValue Ops[] =
6243         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6244           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6245           N0.getOperand(0).getOperand(2) };
6246       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6247     }
6248   }
6249
6250   return SDValue();
6251 }
6252
6253 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6254   SDValue N0 = N->getOperand(0);
6255   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6256   EVT VT = N->getValueType(0);
6257   EVT OpVT = N0.getValueType();
6258
6259   // fold (uint_to_fp c1) -> c1fp
6260   if (N0C && OpVT != MVT::ppcf128 &&
6261       // ...but only if the target supports immediate floating-point values
6262       (!LegalOperations ||
6263        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6264     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6265
6266   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6267   // but SINT_TO_FP is legal on this target, try to convert.
6268   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6269       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6270     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6271     if (DAG.SignBitIsZero(N0))
6272       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6273   }
6274
6275   // The next optimizations are desireable only if SELECT_CC can be lowered.
6276   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6277   // having to say they don't support SELECT_CC on every type the DAG knows
6278   // about, since there is no way to mark an opcode illegal at all value types
6279   // (See also visitSELECT)
6280   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6281     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6282
6283     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6284         (!LegalOperations ||
6285          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6286       SDValue Ops[] =
6287         { N0.getOperand(0), N0.getOperand(1),
6288           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6289           N0.getOperand(2) };
6290       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6291     }
6292   }
6293
6294   return SDValue();
6295 }
6296
6297 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6298   SDValue N0 = N->getOperand(0);
6299   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6300   EVT VT = N->getValueType(0);
6301
6302   // fold (fp_to_sint c1fp) -> c1
6303   if (N0CFP)
6304     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6305
6306   return SDValue();
6307 }
6308
6309 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6310   SDValue N0 = N->getOperand(0);
6311   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6312   EVT VT = N->getValueType(0);
6313
6314   // fold (fp_to_uint c1fp) -> c1
6315   if (N0CFP && VT != MVT::ppcf128)
6316     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6317
6318   return SDValue();
6319 }
6320
6321 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6322   SDValue N0 = N->getOperand(0);
6323   SDValue N1 = N->getOperand(1);
6324   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6325   EVT VT = N->getValueType(0);
6326
6327   // fold (fp_round c1fp) -> c1fp
6328   if (N0CFP && N0.getValueType() != MVT::ppcf128)
6329     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6330
6331   // fold (fp_round (fp_extend x)) -> x
6332   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6333     return N0.getOperand(0);
6334
6335   // fold (fp_round (fp_round x)) -> (fp_round x)
6336   if (N0.getOpcode() == ISD::FP_ROUND) {
6337     // This is a value preserving truncation if both round's are.
6338     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6339                    N0.getNode()->getConstantOperandVal(1) == 1;
6340     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6341                        DAG.getIntPtrConstant(IsTrunc));
6342   }
6343
6344   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6345   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6346     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6347                               N0.getOperand(0), N1);
6348     AddToWorkList(Tmp.getNode());
6349     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6350                        Tmp, N0.getOperand(1));
6351   }
6352
6353   return SDValue();
6354 }
6355
6356 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6357   SDValue N0 = N->getOperand(0);
6358   EVT VT = N->getValueType(0);
6359   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6360   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6361
6362   // fold (fp_round_inreg c1fp) -> c1fp
6363   if (N0CFP && isTypeLegal(EVT)) {
6364     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6365     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6366   }
6367
6368   return SDValue();
6369 }
6370
6371 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6372   SDValue N0 = N->getOperand(0);
6373   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6374   EVT VT = N->getValueType(0);
6375
6376   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6377   if (N->hasOneUse() &&
6378       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6379     return SDValue();
6380
6381   // fold (fp_extend c1fp) -> c1fp
6382   if (N0CFP && VT != MVT::ppcf128)
6383     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6384
6385   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6386   // value of X.
6387   if (N0.getOpcode() == ISD::FP_ROUND
6388       && N0.getNode()->getConstantOperandVal(1) == 1) {
6389     SDValue In = N0.getOperand(0);
6390     if (In.getValueType() == VT) return In;
6391     if (VT.bitsLT(In.getValueType()))
6392       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6393                          In, N0.getOperand(1));
6394     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6395   }
6396
6397   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6398   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6399       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6400        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6401     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6402     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6403                                      LN0->getChain(),
6404                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6405                                      N0.getValueType(),
6406                                      LN0->isVolatile(), LN0->isNonTemporal(),
6407                                      LN0->getAlignment());
6408     CombineTo(N, ExtLoad);
6409     CombineTo(N0.getNode(),
6410               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6411                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6412               ExtLoad.getValue(1));
6413     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6414   }
6415
6416   return SDValue();
6417 }
6418
6419 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6420   SDValue N0 = N->getOperand(0);
6421   EVT VT = N->getValueType(0);
6422
6423   if (VT.isVector()) {
6424     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6425     if (FoldedVOp.getNode()) return FoldedVOp;
6426   }
6427
6428   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6429                          &DAG.getTarget().Options))
6430     return GetNegatedExpression(N0, DAG, LegalOperations);
6431
6432   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6433   // constant pool values.
6434   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6435       !VT.isVector() &&
6436       N0.getNode()->hasOneUse() &&
6437       N0.getOperand(0).getValueType().isInteger()) {
6438     SDValue Int = N0.getOperand(0);
6439     EVT IntVT = Int.getValueType();
6440     if (IntVT.isInteger() && !IntVT.isVector()) {
6441       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6442               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6443       AddToWorkList(Int.getNode());
6444       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6445                          VT, Int);
6446     }
6447   }
6448
6449   // (fneg (fmul c, x)) -> (fmul -c, x)
6450   if (N0.getOpcode() == ISD::FMUL) {
6451     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6452     if (CFP1) {
6453       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6454                          N0.getOperand(0),
6455                          DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6456                                      N0.getOperand(1)));
6457     }
6458   }
6459
6460   return SDValue();
6461 }
6462
6463 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6464   SDValue N0 = N->getOperand(0);
6465   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6466   EVT VT = N->getValueType(0);
6467
6468   // fold (fceil c1) -> fceil(c1)
6469   if (N0CFP && VT != MVT::ppcf128)
6470     return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
6471
6472   return SDValue();
6473 }
6474
6475 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6476   SDValue N0 = N->getOperand(0);
6477   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6478   EVT VT = N->getValueType(0);
6479
6480   // fold (ftrunc c1) -> ftrunc(c1)
6481   if (N0CFP && VT != MVT::ppcf128)
6482     return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
6483
6484   return SDValue();
6485 }
6486
6487 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6488   SDValue N0 = N->getOperand(0);
6489   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6490   EVT VT = N->getValueType(0);
6491
6492   // fold (ffloor c1) -> ffloor(c1)
6493   if (N0CFP && VT != MVT::ppcf128)
6494     return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
6495
6496   return SDValue();
6497 }
6498
6499 SDValue DAGCombiner::visitFABS(SDNode *N) {
6500   SDValue N0 = N->getOperand(0);
6501   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6502   EVT VT = N->getValueType(0);
6503
6504   if (VT.isVector()) {
6505     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6506     if (FoldedVOp.getNode()) return FoldedVOp;
6507   }
6508
6509   // fold (fabs c1) -> fabs(c1)
6510   if (N0CFP && VT != MVT::ppcf128)
6511     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6512   // fold (fabs (fabs x)) -> (fabs x)
6513   if (N0.getOpcode() == ISD::FABS)
6514     return N->getOperand(0);
6515   // fold (fabs (fneg x)) -> (fabs x)
6516   // fold (fabs (fcopysign x, y)) -> (fabs x)
6517   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6518     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6519
6520   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6521   // constant pool values.
6522   if (!TLI.isFAbsFree(VT) && 
6523       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6524       N0.getOperand(0).getValueType().isInteger() &&
6525       !N0.getOperand(0).getValueType().isVector()) {
6526     SDValue Int = N0.getOperand(0);
6527     EVT IntVT = Int.getValueType();
6528     if (IntVT.isInteger() && !IntVT.isVector()) {
6529       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6530              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6531       AddToWorkList(Int.getNode());
6532       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6533                          N->getValueType(0), Int);
6534     }
6535   }
6536
6537   return SDValue();
6538 }
6539
6540 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6541   SDValue Chain = N->getOperand(0);
6542   SDValue N1 = N->getOperand(1);
6543   SDValue N2 = N->getOperand(2);
6544
6545   // If N is a constant we could fold this into a fallthrough or unconditional
6546   // branch. However that doesn't happen very often in normal code, because
6547   // Instcombine/SimplifyCFG should have handled the available opportunities.
6548   // If we did this folding here, it would be necessary to update the
6549   // MachineBasicBlock CFG, which is awkward.
6550
6551   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6552   // on the target.
6553   if (N1.getOpcode() == ISD::SETCC &&
6554       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
6555     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6556                        Chain, N1.getOperand(2),
6557                        N1.getOperand(0), N1.getOperand(1), N2);
6558   }
6559
6560   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6561       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6562        (N1.getOperand(0).hasOneUse() &&
6563         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6564     SDNode *Trunc = 0;
6565     if (N1.getOpcode() == ISD::TRUNCATE) {
6566       // Look pass the truncate.
6567       Trunc = N1.getNode();
6568       N1 = N1.getOperand(0);
6569     }
6570
6571     // Match this pattern so that we can generate simpler code:
6572     //
6573     //   %a = ...
6574     //   %b = and i32 %a, 2
6575     //   %c = srl i32 %b, 1
6576     //   brcond i32 %c ...
6577     //
6578     // into
6579     //
6580     //   %a = ...
6581     //   %b = and i32 %a, 2
6582     //   %c = setcc eq %b, 0
6583     //   brcond %c ...
6584     //
6585     // This applies only when the AND constant value has one bit set and the
6586     // SRL constant is equal to the log2 of the AND constant. The back-end is
6587     // smart enough to convert the result into a TEST/JMP sequence.
6588     SDValue Op0 = N1.getOperand(0);
6589     SDValue Op1 = N1.getOperand(1);
6590
6591     if (Op0.getOpcode() == ISD::AND &&
6592         Op1.getOpcode() == ISD::Constant) {
6593       SDValue AndOp1 = Op0.getOperand(1);
6594
6595       if (AndOp1.getOpcode() == ISD::Constant) {
6596         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6597
6598         if (AndConst.isPowerOf2() &&
6599             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6600           SDValue SetCC =
6601             DAG.getSetCC(N->getDebugLoc(),
6602                          TLI.getSetCCResultType(Op0.getValueType()),
6603                          Op0, DAG.getConstant(0, Op0.getValueType()),
6604                          ISD::SETNE);
6605
6606           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6607                                           MVT::Other, Chain, SetCC, N2);
6608           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6609           // will convert it back to (X & C1) >> C2.
6610           CombineTo(N, NewBRCond, false);
6611           // Truncate is dead.
6612           if (Trunc) {
6613             removeFromWorkList(Trunc);
6614             DAG.DeleteNode(Trunc);
6615           }
6616           // Replace the uses of SRL with SETCC
6617           WorkListRemover DeadNodes(*this);
6618           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6619           removeFromWorkList(N1.getNode());
6620           DAG.DeleteNode(N1.getNode());
6621           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6622         }
6623       }
6624     }
6625
6626     if (Trunc)
6627       // Restore N1 if the above transformation doesn't match.
6628       N1 = N->getOperand(1);
6629   }
6630
6631   // Transform br(xor(x, y)) -> br(x != y)
6632   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6633   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6634     SDNode *TheXor = N1.getNode();
6635     SDValue Op0 = TheXor->getOperand(0);
6636     SDValue Op1 = TheXor->getOperand(1);
6637     if (Op0.getOpcode() == Op1.getOpcode()) {
6638       // Avoid missing important xor optimizations.
6639       SDValue Tmp = visitXOR(TheXor);
6640       if (Tmp.getNode() && Tmp.getNode() != TheXor) {
6641         DEBUG(dbgs() << "\nReplacing.8 ";
6642               TheXor->dump(&DAG);
6643               dbgs() << "\nWith: ";
6644               Tmp.getNode()->dump(&DAG);
6645               dbgs() << '\n');
6646         WorkListRemover DeadNodes(*this);
6647         DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6648         removeFromWorkList(TheXor);
6649         DAG.DeleteNode(TheXor);
6650         return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6651                            MVT::Other, Chain, Tmp, N2);
6652       }
6653     }
6654
6655     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6656       bool Equal = false;
6657       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6658         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6659             Op0.getOpcode() == ISD::XOR) {
6660           TheXor = Op0.getNode();
6661           Equal = true;
6662         }
6663
6664       EVT SetCCVT = N1.getValueType();
6665       if (LegalTypes)
6666         SetCCVT = TLI.getSetCCResultType(SetCCVT);
6667       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6668                                    SetCCVT,
6669                                    Op0, Op1,
6670                                    Equal ? ISD::SETEQ : ISD::SETNE);
6671       // Replace the uses of XOR with SETCC
6672       WorkListRemover DeadNodes(*this);
6673       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6674       removeFromWorkList(N1.getNode());
6675       DAG.DeleteNode(N1.getNode());
6676       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6677                          MVT::Other, Chain, SetCC, N2);
6678     }
6679   }
6680
6681   return SDValue();
6682 }
6683
6684 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6685 //
6686 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6687   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6688   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6689
6690   // If N is a constant we could fold this into a fallthrough or unconditional
6691   // branch. However that doesn't happen very often in normal code, because
6692   // Instcombine/SimplifyCFG should have handled the available opportunities.
6693   // If we did this folding here, it would be necessary to update the
6694   // MachineBasicBlock CFG, which is awkward.
6695
6696   // Use SimplifySetCC to simplify SETCC's.
6697   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6698                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6699                                false);
6700   if (Simp.getNode()) AddToWorkList(Simp.getNode());
6701
6702   // fold to a simpler setcc
6703   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6704     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6705                        N->getOperand(0), Simp.getOperand(2),
6706                        Simp.getOperand(0), Simp.getOperand(1),
6707                        N->getOperand(4));
6708
6709   return SDValue();
6710 }
6711
6712 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6713 /// uses N as its base pointer and that N may be folded in the load / store
6714 /// addressing mode.
6715 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6716                                     SelectionDAG &DAG,
6717                                     const TargetLowering &TLI) {
6718   EVT VT;
6719   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6720     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6721       return false;
6722     VT = Use->getValueType(0);
6723   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6724     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6725       return false;
6726     VT = ST->getValue().getValueType();
6727   } else
6728     return false;
6729
6730   TargetLowering::AddrMode AM;
6731   if (N->getOpcode() == ISD::ADD) {
6732     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6733     if (Offset)
6734       // [reg +/- imm]
6735       AM.BaseOffs = Offset->getSExtValue();
6736     else
6737       // [reg +/- reg]
6738       AM.Scale = 1;
6739   } else if (N->getOpcode() == ISD::SUB) {
6740     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6741     if (Offset)
6742       // [reg +/- imm]
6743       AM.BaseOffs = -Offset->getSExtValue();
6744     else
6745       // [reg +/- reg]
6746       AM.Scale = 1;
6747   } else
6748     return false;
6749
6750   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6751 }
6752
6753 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6754 /// pre-indexed load / store when the base pointer is an add or subtract
6755 /// and it has other uses besides the load / store. After the
6756 /// transformation, the new indexed load / store has effectively folded
6757 /// the add / subtract in and all of its other uses are redirected to the
6758 /// new load / store.
6759 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6760   if (Level < AfterLegalizeDAG)
6761     return false;
6762
6763   bool isLoad = true;
6764   SDValue Ptr;
6765   EVT VT;
6766   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6767     if (LD->isIndexed())
6768       return false;
6769     VT = LD->getMemoryVT();
6770     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6771         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6772       return false;
6773     Ptr = LD->getBasePtr();
6774   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6775     if (ST->isIndexed())
6776       return false;
6777     VT = ST->getMemoryVT();
6778     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6779         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6780       return false;
6781     Ptr = ST->getBasePtr();
6782     isLoad = false;
6783   } else {
6784     return false;
6785   }
6786
6787   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6788   // out.  There is no reason to make this a preinc/predec.
6789   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6790       Ptr.getNode()->hasOneUse())
6791     return false;
6792
6793   // Ask the target to do addressing mode selection.
6794   SDValue BasePtr;
6795   SDValue Offset;
6796   ISD::MemIndexedMode AM = ISD::UNINDEXED;
6797   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6798     return false;
6799   // Don't create a indexed load / store with zero offset.
6800   if (isa<ConstantSDNode>(Offset) &&
6801       cast<ConstantSDNode>(Offset)->isNullValue())
6802     return false;
6803
6804   // Try turning it into a pre-indexed load / store except when:
6805   // 1) The new base ptr is a frame index.
6806   // 2) If N is a store and the new base ptr is either the same as or is a
6807   //    predecessor of the value being stored.
6808   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6809   //    that would create a cycle.
6810   // 4) All uses are load / store ops that use it as old base ptr.
6811
6812   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
6813   // (plus the implicit offset) to a register to preinc anyway.
6814   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6815     return false;
6816
6817   // Check #2.
6818   if (!isLoad) {
6819     SDValue Val = cast<StoreSDNode>(N)->getValue();
6820     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
6821       return false;
6822   }
6823
6824   // Now check for #3 and #4.
6825   bool RealUse = false;
6826
6827   // Caches for hasPredecessorHelper
6828   SmallPtrSet<const SDNode *, 32> Visited;
6829   SmallVector<const SDNode *, 16> Worklist;
6830
6831   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6832          E = Ptr.getNode()->use_end(); I != E; ++I) {
6833     SDNode *Use = *I;
6834     if (Use == N)
6835       continue;
6836     if (N->hasPredecessorHelper(Use, Visited, Worklist))
6837       return false;
6838
6839     // If Ptr may be folded in addressing mode of other use, then it's
6840     // not profitable to do this transformation.
6841     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
6842       RealUse = true;
6843   }
6844
6845   if (!RealUse)
6846     return false;
6847
6848   SDValue Result;
6849   if (isLoad)
6850     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6851                                 BasePtr, Offset, AM);
6852   else
6853     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6854                                  BasePtr, Offset, AM);
6855   ++PreIndexedNodes;
6856   ++NodesCombined;
6857   DEBUG(dbgs() << "\nReplacing.4 ";
6858         N->dump(&DAG);
6859         dbgs() << "\nWith: ";
6860         Result.getNode()->dump(&DAG);
6861         dbgs() << '\n');
6862   WorkListRemover DeadNodes(*this);
6863   if (isLoad) {
6864     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6865     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6866   } else {
6867     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6868   }
6869
6870   // Finally, since the node is now dead, remove it from the graph.
6871   DAG.DeleteNode(N);
6872
6873   // Replace the uses of Ptr with uses of the updated base value.
6874   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
6875   removeFromWorkList(Ptr.getNode());
6876   DAG.DeleteNode(Ptr.getNode());
6877
6878   return true;
6879 }
6880
6881 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6882 /// add / sub of the base pointer node into a post-indexed load / store.
6883 /// The transformation folded the add / subtract into the new indexed
6884 /// load / store effectively and all of its uses are redirected to the
6885 /// new load / store.
6886 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6887   if (Level < AfterLegalizeDAG)
6888     return false;
6889
6890   bool isLoad = true;
6891   SDValue Ptr;
6892   EVT VT;
6893   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6894     if (LD->isIndexed())
6895       return false;
6896     VT = LD->getMemoryVT();
6897     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6898         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6899       return false;
6900     Ptr = LD->getBasePtr();
6901   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6902     if (ST->isIndexed())
6903       return false;
6904     VT = ST->getMemoryVT();
6905     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6906         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6907       return false;
6908     Ptr = ST->getBasePtr();
6909     isLoad = false;
6910   } else {
6911     return false;
6912   }
6913
6914   if (Ptr.getNode()->hasOneUse())
6915     return false;
6916
6917   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6918          E = Ptr.getNode()->use_end(); I != E; ++I) {
6919     SDNode *Op = *I;
6920     if (Op == N ||
6921         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6922       continue;
6923
6924     SDValue BasePtr;
6925     SDValue Offset;
6926     ISD::MemIndexedMode AM = ISD::UNINDEXED;
6927     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6928       // Don't create a indexed load / store with zero offset.
6929       if (isa<ConstantSDNode>(Offset) &&
6930           cast<ConstantSDNode>(Offset)->isNullValue())
6931         continue;
6932
6933       // Try turning it into a post-indexed load / store except when
6934       // 1) All uses are load / store ops that use it as base ptr (and
6935       //    it may be folded as addressing mmode).
6936       // 2) Op must be independent of N, i.e. Op is neither a predecessor
6937       //    nor a successor of N. Otherwise, if Op is folded that would
6938       //    create a cycle.
6939
6940       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6941         continue;
6942
6943       // Check for #1.
6944       bool TryNext = false;
6945       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6946              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6947         SDNode *Use = *II;
6948         if (Use == Ptr.getNode())
6949           continue;
6950
6951         // If all the uses are load / store addresses, then don't do the
6952         // transformation.
6953         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6954           bool RealUse = false;
6955           for (SDNode::use_iterator III = Use->use_begin(),
6956                  EEE = Use->use_end(); III != EEE; ++III) {
6957             SDNode *UseUse = *III;
6958             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 
6959               RealUse = true;
6960           }
6961
6962           if (!RealUse) {
6963             TryNext = true;
6964             break;
6965           }
6966         }
6967       }
6968
6969       if (TryNext)
6970         continue;
6971
6972       // Check for #2
6973       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
6974         SDValue Result = isLoad
6975           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6976                                BasePtr, Offset, AM)
6977           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6978                                 BasePtr, Offset, AM);
6979         ++PostIndexedNodes;
6980         ++NodesCombined;
6981         DEBUG(dbgs() << "\nReplacing.5 ";
6982               N->dump(&DAG);
6983               dbgs() << "\nWith: ";
6984               Result.getNode()->dump(&DAG);
6985               dbgs() << '\n');
6986         WorkListRemover DeadNodes(*this);
6987         if (isLoad) {
6988           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6989           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6990         } else {
6991           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6992         }
6993
6994         // Finally, since the node is now dead, remove it from the graph.
6995         DAG.DeleteNode(N);
6996
6997         // Replace the uses of Use with uses of the updated base value.
6998         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
6999                                       Result.getValue(isLoad ? 1 : 0));
7000         removeFromWorkList(Op);
7001         DAG.DeleteNode(Op);
7002         return true;
7003       }
7004     }
7005   }
7006
7007   return false;
7008 }
7009
7010 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7011   LoadSDNode *LD  = cast<LoadSDNode>(N);
7012   SDValue Chain = LD->getChain();
7013   SDValue Ptr   = LD->getBasePtr();
7014
7015   // If load is not volatile and there are no uses of the loaded value (and
7016   // the updated indexed value in case of indexed loads), change uses of the
7017   // chain value into uses of the chain input (i.e. delete the dead load).
7018   if (!LD->isVolatile()) {
7019     if (N->getValueType(1) == MVT::Other) {
7020       // Unindexed loads.
7021       if (!N->hasAnyUseOfValue(0)) {
7022         // It's not safe to use the two value CombineTo variant here. e.g.
7023         // v1, chain2 = load chain1, loc
7024         // v2, chain3 = load chain2, loc
7025         // v3         = add v2, c
7026         // Now we replace use of chain2 with chain1.  This makes the second load
7027         // isomorphic to the one we are deleting, and thus makes this load live.
7028         DEBUG(dbgs() << "\nReplacing.6 ";
7029               N->dump(&DAG);
7030               dbgs() << "\nWith chain: ";
7031               Chain.getNode()->dump(&DAG);
7032               dbgs() << "\n");
7033         WorkListRemover DeadNodes(*this);
7034         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7035
7036         if (N->use_empty()) {
7037           removeFromWorkList(N);
7038           DAG.DeleteNode(N);
7039         }
7040
7041         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7042       }
7043     } else {
7044       // Indexed loads.
7045       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7046       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7047         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7048         DEBUG(dbgs() << "\nReplacing.7 ";
7049               N->dump(&DAG);
7050               dbgs() << "\nWith: ";
7051               Undef.getNode()->dump(&DAG);
7052               dbgs() << " and 2 other values\n");
7053         WorkListRemover DeadNodes(*this);
7054         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7055         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7056                                       DAG.getUNDEF(N->getValueType(1)));
7057         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7058         removeFromWorkList(N);
7059         DAG.DeleteNode(N);
7060         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7061       }
7062     }
7063   }
7064
7065   // If this load is directly stored, replace the load value with the stored
7066   // value.
7067   // TODO: Handle store large -> read small portion.
7068   // TODO: Handle TRUNCSTORE/LOADEXT
7069   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7070     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7071       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7072       if (PrevST->getBasePtr() == Ptr &&
7073           PrevST->getValue().getValueType() == N->getValueType(0))
7074       return CombineTo(N, Chain.getOperand(1), Chain);
7075     }
7076   }
7077
7078   // Try to infer better alignment information than the load already has.
7079   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7080     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7081       if (Align > LD->getAlignment())
7082         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
7083                               LD->getValueType(0),
7084                               Chain, Ptr, LD->getPointerInfo(),
7085                               LD->getMemoryVT(),
7086                               LD->isVolatile(), LD->isNonTemporal(), Align);
7087     }
7088   }
7089
7090   if (CombinerAA) {
7091     // Walk up chain skipping non-aliasing memory nodes.
7092     SDValue BetterChain = FindBetterChain(N, Chain);
7093
7094     // If there is a better chain.
7095     if (Chain != BetterChain) {
7096       SDValue ReplLoad;
7097
7098       // Replace the chain to void dependency.
7099       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7100         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
7101                                BetterChain, Ptr, LD->getPointerInfo(),
7102                                LD->isVolatile(), LD->isNonTemporal(),
7103                                LD->isInvariant(), LD->getAlignment());
7104       } else {
7105         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
7106                                   LD->getValueType(0),
7107                                   BetterChain, Ptr, LD->getPointerInfo(),
7108                                   LD->getMemoryVT(),
7109                                   LD->isVolatile(),
7110                                   LD->isNonTemporal(),
7111                                   LD->getAlignment());
7112       }
7113
7114       // Create token factor to keep old chain connected.
7115       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7116                                   MVT::Other, Chain, ReplLoad.getValue(1));
7117
7118       // Make sure the new and old chains are cleaned up.
7119       AddToWorkList(Token.getNode());
7120
7121       // Replace uses with load result and token factor. Don't add users
7122       // to work list.
7123       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7124     }
7125   }
7126
7127   // Try transforming N to an indexed load.
7128   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7129     return SDValue(N, 0);
7130
7131   return SDValue();
7132 }
7133
7134 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7135 /// load is having specific bytes cleared out.  If so, return the byte size
7136 /// being masked out and the shift amount.
7137 static std::pair<unsigned, unsigned>
7138 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7139   std::pair<unsigned, unsigned> Result(0, 0);
7140
7141   // Check for the structure we're looking for.
7142   if (V->getOpcode() != ISD::AND ||
7143       !isa<ConstantSDNode>(V->getOperand(1)) ||
7144       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7145     return Result;
7146
7147   // Check the chain and pointer.
7148   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7149   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7150
7151   // The store should be chained directly to the load or be an operand of a
7152   // tokenfactor.
7153   if (LD == Chain.getNode())
7154     ; // ok.
7155   else if (Chain->getOpcode() != ISD::TokenFactor)
7156     return Result; // Fail.
7157   else {
7158     bool isOk = false;
7159     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7160       if (Chain->getOperand(i).getNode() == LD) {
7161         isOk = true;
7162         break;
7163       }
7164     if (!isOk) return Result;
7165   }
7166
7167   // This only handles simple types.
7168   if (V.getValueType() != MVT::i16 &&
7169       V.getValueType() != MVT::i32 &&
7170       V.getValueType() != MVT::i64)
7171     return Result;
7172
7173   // Check the constant mask.  Invert it so that the bits being masked out are
7174   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7175   // follow the sign bit for uniformity.
7176   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7177   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
7178   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7179   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
7180   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7181   if (NotMaskLZ == 64) return Result;  // All zero mask.
7182
7183   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7184   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7185     return Result;
7186
7187   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7188   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7189     NotMaskLZ -= 64-V.getValueSizeInBits();
7190
7191   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7192   switch (MaskedBytes) {
7193   case 1:
7194   case 2:
7195   case 4: break;
7196   default: return Result; // All one mask, or 5-byte mask.
7197   }
7198
7199   // Verify that the first bit starts at a multiple of mask so that the access
7200   // is aligned the same as the access width.
7201   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7202
7203   Result.first = MaskedBytes;
7204   Result.second = NotMaskTZ/8;
7205   return Result;
7206 }
7207
7208
7209 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7210 /// provides a value as specified by MaskInfo.  If so, replace the specified
7211 /// store with a narrower store of truncated IVal.
7212 static SDNode *
7213 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7214                                 SDValue IVal, StoreSDNode *St,
7215                                 DAGCombiner *DC) {
7216   unsigned NumBytes = MaskInfo.first;
7217   unsigned ByteShift = MaskInfo.second;
7218   SelectionDAG &DAG = DC->getDAG();
7219
7220   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7221   // that uses this.  If not, this is not a replacement.
7222   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7223                                   ByteShift*8, (ByteShift+NumBytes)*8);
7224   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7225
7226   // Check that it is legal on the target to do this.  It is legal if the new
7227   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7228   // legalization.
7229   MVT VT = MVT::getIntegerVT(NumBytes*8);
7230   if (!DC->isTypeLegal(VT))
7231     return 0;
7232
7233   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7234   // shifted by ByteShift and truncated down to NumBytes.
7235   if (ByteShift)
7236     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
7237                        DAG.getConstant(ByteShift*8,
7238                                     DC->getShiftAmountTy(IVal.getValueType())));
7239
7240   // Figure out the offset for the store and the alignment of the access.
7241   unsigned StOffset;
7242   unsigned NewAlign = St->getAlignment();
7243
7244   if (DAG.getTargetLoweringInfo().isLittleEndian())
7245     StOffset = ByteShift;
7246   else
7247     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7248
7249   SDValue Ptr = St->getBasePtr();
7250   if (StOffset) {
7251     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
7252                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7253     NewAlign = MinAlign(NewAlign, StOffset);
7254   }
7255
7256   // Truncate down to the new size.
7257   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7258
7259   ++OpsNarrowed;
7260   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7261                       St->getPointerInfo().getWithOffset(StOffset),
7262                       false, false, NewAlign).getNode();
7263 }
7264
7265
7266 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7267 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7268 /// of the loaded bits, try narrowing the load and store if it would end up
7269 /// being a win for performance or code size.
7270 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7271   StoreSDNode *ST  = cast<StoreSDNode>(N);
7272   if (ST->isVolatile())
7273     return SDValue();
7274
7275   SDValue Chain = ST->getChain();
7276   SDValue Value = ST->getValue();
7277   SDValue Ptr   = ST->getBasePtr();
7278   EVT VT = Value.getValueType();
7279
7280   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7281     return SDValue();
7282
7283   unsigned Opc = Value.getOpcode();
7284
7285   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7286   // is a byte mask indicating a consecutive number of bytes, check to see if
7287   // Y is known to provide just those bytes.  If so, we try to replace the
7288   // load + replace + store sequence with a single (narrower) store, which makes
7289   // the load dead.
7290   if (Opc == ISD::OR) {
7291     std::pair<unsigned, unsigned> MaskedLoad;
7292     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7293     if (MaskedLoad.first)
7294       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7295                                                   Value.getOperand(1), ST,this))
7296         return SDValue(NewST, 0);
7297
7298     // Or is commutative, so try swapping X and Y.
7299     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7300     if (MaskedLoad.first)
7301       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7302                                                   Value.getOperand(0), ST,this))
7303         return SDValue(NewST, 0);
7304   }
7305
7306   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7307       Value.getOperand(1).getOpcode() != ISD::Constant)
7308     return SDValue();
7309
7310   SDValue N0 = Value.getOperand(0);
7311   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7312       Chain == SDValue(N0.getNode(), 1)) {
7313     LoadSDNode *LD = cast<LoadSDNode>(N0);
7314     if (LD->getBasePtr() != Ptr ||
7315         LD->getPointerInfo().getAddrSpace() !=
7316         ST->getPointerInfo().getAddrSpace())
7317       return SDValue();
7318
7319     // Find the type to narrow it the load / op / store to.
7320     SDValue N1 = Value.getOperand(1);
7321     unsigned BitWidth = N1.getValueSizeInBits();
7322     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7323     if (Opc == ISD::AND)
7324       Imm ^= APInt::getAllOnesValue(BitWidth);
7325     if (Imm == 0 || Imm.isAllOnesValue())
7326       return SDValue();
7327     unsigned ShAmt = Imm.countTrailingZeros();
7328     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7329     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7330     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7331     while (NewBW < BitWidth &&
7332            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7333              TLI.isNarrowingProfitable(VT, NewVT))) {
7334       NewBW = NextPowerOf2(NewBW);
7335       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7336     }
7337     if (NewBW >= BitWidth)
7338       return SDValue();
7339
7340     // If the lsb changed does not start at the type bitwidth boundary,
7341     // start at the previous one.
7342     if (ShAmt % NewBW)
7343       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7344     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
7345     if ((Imm & Mask) == Imm) {
7346       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7347       if (Opc == ISD::AND)
7348         NewImm ^= APInt::getAllOnesValue(NewBW);
7349       uint64_t PtrOff = ShAmt / 8;
7350       // For big endian targets, we need to adjust the offset to the pointer to
7351       // load the correct bytes.
7352       if (TLI.isBigEndian())
7353         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7354
7355       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7356       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7357       if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
7358         return SDValue();
7359
7360       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7361                                    Ptr.getValueType(), Ptr,
7362                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7363       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7364                                   LD->getChain(), NewPtr,
7365                                   LD->getPointerInfo().getWithOffset(PtrOff),
7366                                   LD->isVolatile(), LD->isNonTemporal(),
7367                                   LD->isInvariant(), NewAlign);
7368       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7369                                    DAG.getConstant(NewImm, NewVT));
7370       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7371                                    NewVal, NewPtr,
7372                                    ST->getPointerInfo().getWithOffset(PtrOff),
7373                                    false, false, NewAlign);
7374
7375       AddToWorkList(NewPtr.getNode());
7376       AddToWorkList(NewLD.getNode());
7377       AddToWorkList(NewVal.getNode());
7378       WorkListRemover DeadNodes(*this);
7379       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7380       ++OpsNarrowed;
7381       return NewST;
7382     }
7383   }
7384
7385   return SDValue();
7386 }
7387
7388 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7389 /// if the load value isn't used by any other operations, then consider
7390 /// transforming the pair to integer load / store operations if the target
7391 /// deems the transformation profitable.
7392 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7393   StoreSDNode *ST  = cast<StoreSDNode>(N);
7394   SDValue Chain = ST->getChain();
7395   SDValue Value = ST->getValue();
7396   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7397       Value.hasOneUse() &&
7398       Chain == SDValue(Value.getNode(), 1)) {
7399     LoadSDNode *LD = cast<LoadSDNode>(Value);
7400     EVT VT = LD->getMemoryVT();
7401     if (!VT.isFloatingPoint() ||
7402         VT != ST->getMemoryVT() ||
7403         LD->isNonTemporal() ||
7404         ST->isNonTemporal() ||
7405         LD->getPointerInfo().getAddrSpace() != 0 ||
7406         ST->getPointerInfo().getAddrSpace() != 0)
7407       return SDValue();
7408
7409     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7410     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7411         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7412         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7413         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7414       return SDValue();
7415
7416     unsigned LDAlign = LD->getAlignment();
7417     unsigned STAlign = ST->getAlignment();
7418     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7419     unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
7420     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7421       return SDValue();
7422
7423     SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7424                                 LD->getChain(), LD->getBasePtr(),
7425                                 LD->getPointerInfo(),
7426                                 false, false, false, LDAlign);
7427
7428     SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7429                                  NewLD, ST->getBasePtr(),
7430                                  ST->getPointerInfo(),
7431                                  false, false, STAlign);
7432
7433     AddToWorkList(NewLD.getNode());
7434     AddToWorkList(NewST.getNode());
7435     WorkListRemover DeadNodes(*this);
7436     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7437     ++LdStFP2Int;
7438     return NewST;
7439   }
7440
7441   return SDValue();
7442 }
7443
7444 /// Returns the base pointer and an integer offset from that object.
7445 static std::pair<SDValue, int64_t> GetPointerBaseAndOffset(SDValue Ptr) {
7446   if (Ptr->getOpcode() == ISD::ADD && isa<ConstantSDNode>(Ptr->getOperand(1))) {
7447     int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7448     SDValue Base = Ptr->getOperand(0);
7449     return std::make_pair(Base, Offset);
7450   }
7451
7452   return std::make_pair(Ptr, 0);
7453 }
7454
7455 struct ConsecutiveMemoryChainSorter {
7456   typedef std::pair<LSBaseSDNode*, int64_t> MemLink;
7457   bool operator()(MemLink LHS, MemLink RHS) {
7458     return LHS.second < RHS.second;
7459   }
7460 };
7461
7462 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7463   EVT MemVT = St->getMemoryVT();
7464   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7465
7466   // Don't handle vectors.
7467   if (MemVT.isVector() || !MemVT.isSimple())
7468     return false;
7469
7470   // Perform an early exit check. Do not bother looking at stored values that
7471   // are not constants or loads.
7472   SDValue StoredVal = St->getValue();
7473   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7474       !isa<LoadSDNode>(StoredVal))
7475     return false;
7476
7477   // Is this a load-to-store or a const-store.
7478   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7479
7480   // Only look at ends of store chains.
7481   SDValue Chain = SDValue(St, 1);
7482   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7483     return false;
7484
7485   // This holds the base pointer and the offset in bytes from the base pointer.
7486   std::pair<SDValue, int64_t> BasePtr =
7487       GetPointerBaseAndOffset(St->getBasePtr());
7488
7489   // We must have a base and an offset.
7490   if (!BasePtr.first.getNode())
7491     return false;
7492
7493   // Do not handle stores to undef base pointers.
7494   if (BasePtr.first.getOpcode() == ISD::UNDEF)
7495     return false;
7496
7497   SmallVector<std::pair<StoreSDNode*, int64_t>, 8> StoreNodes;
7498   // Walk up the chain and look for nodes with offsets from the same
7499   // base pointer. Stop when reaching an instruction with a different kind
7500   // or instruction which has a different base pointer.
7501   StoreSDNode *Index = St;
7502   while (Index) {
7503     // If the chain has more than one use, then we can't reorder the mem ops.
7504     if (Index != St && !SDValue(Index, 1)->hasOneUse())
7505       break;
7506
7507     // Find the base pointer and offset for this memory node.
7508     std::pair<SDValue, int64_t> Ptr =
7509       GetPointerBaseAndOffset(Index->getBasePtr());
7510
7511     // Check that the base pointer is the same as the original one.
7512     if (Ptr.first.getNode() != BasePtr.first.getNode())
7513       break;
7514
7515     // Check that the alignment is the same.
7516     if (Index->getAlignment() != St->getAlignment())
7517       break;
7518
7519     // The memory operands must not be volatile.
7520     if (Index->isVolatile() || Index->isIndexed())
7521       break;
7522
7523     // No truncation.
7524     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7525       if (St->isTruncatingStore())
7526         break;
7527
7528     // The stored memory type must be the same.
7529     if (Index->getMemoryVT() != MemVT)
7530       break;
7531
7532     // We found a potential memory operand to merge.
7533     StoreNodes.push_back(std::make_pair(Index,Ptr.second));
7534
7535    // Move up the chain to the next memory operation.
7536     Index = dyn_cast<StoreSDNode>(Index->getChain().getNode());
7537   }
7538
7539   // Check if there is anything to merge.
7540   if (StoreNodes.size() < 2)
7541     return false;
7542
7543   // Remember which node is the earliest node in the chain.
7544   LSBaseSDNode *EarliestOp = StoreNodes.back().first;
7545
7546   // Sort the memory operands according to their distance from the base pointer.
7547   std::sort(StoreNodes.begin(), StoreNodes.end(),
7548             ConsecutiveMemoryChainSorter());
7549
7550   // Scan the memory operations on the chain and find the first non-consecutive
7551   // store memory address.
7552   unsigned LastConsecutiveStore = 0;
7553   int64_t StartAddress = StoreNodes[0].second;
7554   for (unsigned i=1; i<StoreNodes.size(); ++i) {
7555     int64_t CurrAddress = StoreNodes[i].second;
7556     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7557       break;
7558     LastConsecutiveStore = i;
7559   }
7560
7561   // Store the constants into memory as one consecutive store.
7562   if (!IsLoadSrc) {
7563     unsigned LastConst = 0;
7564     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
7565       SDValue StoredVal = StoreNodes[i].first->getValue();
7566       bool IsConst = (isa<ConstantSDNode>(StoredVal) || isa<ConstantFPSDNode>(StoredVal));
7567       if (!IsConst)
7568         break;
7569       LastConst = i;
7570     }
7571     unsigned NumElem = std::min(LastConsecutiveStore + 1, LastConst + 1);
7572     if (NumElem < 2)
7573       return false;
7574
7575     EVT JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
7576     DebugLoc DL = StoreNodes[0].first->getDebugLoc();
7577     SmallVector<SDValue, 8> Ops;
7578
7579     for (unsigned i = 0; i < NumElem ; ++i) {
7580       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].first);
7581       Ops.push_back(St->getValue());
7582     }
7583
7584     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL,
7585                              JointMemOpVT, &Ops[0], Ops.size());
7586
7587     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, BV,
7588                                     EarliestOp->getBasePtr(),
7589                                     EarliestOp->getPointerInfo(), false, false,
7590                                     EarliestOp->getAlignment());
7591
7592     for (unsigned i = 0; i < NumElem ; ++i) {
7593       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].first);
7594       CombineTo(St, NewStore);
7595     }
7596     return true;
7597   }
7598
7599   // Look for load nodes wich are used by the stored values.
7600   SmallVector<std::pair<LoadSDNode*, int64_t>, 8> LoadNodes;
7601
7602   // Find acceptible loads. Loads need to have the same chain (token factor),
7603   // must not be zext, volatile, indexed, and they must be consecutive.
7604   SDValue LdBasePtr;
7605   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
7606     LoadSDNode *Ld = dyn_cast<LoadSDNode>(StoreNodes[i].first->getValue());
7607     if (!Ld) break;
7608
7609     // Loads must only have one use.
7610     if (!Ld->hasNUsesOfValue(1, 0))
7611       break;
7612
7613     // Check that the alignment is the same as the stores.
7614     if (Ld->getAlignment() != St->getAlignment())
7615       break;
7616
7617     // The memory operands must not be volatile.
7618     if (Ld->isVolatile() || Ld->isIndexed())
7619       break;
7620
7621     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
7622       break;
7623
7624     // The stored memory type must be the same.
7625     if (Ld->getMemoryVT() != MemVT)
7626       break;
7627
7628     std::pair<SDValue, int64_t> LdPtr =
7629     GetPointerBaseAndOffset(Ld->getBasePtr());
7630
7631     // If this is not the first ptr that we check.
7632     if (LdBasePtr.getNode()) {
7633       // The base ptr must be the same,
7634       if (LdPtr.first != LdBasePtr)
7635         break;
7636     } else {
7637       LdBasePtr = LdPtr.first;
7638     }
7639
7640     // We found a potential memory operand to merge.
7641     LoadNodes.push_back(std::make_pair(Ld, LdPtr.second));
7642   }
7643
7644   if (LoadNodes.size() < 2)
7645     return false;
7646
7647   // Scan the memory operations on the chain and find the first non-consecutive
7648   // load memory address.
7649   unsigned LastConsecutiveLoad = 0;
7650   StartAddress = LoadNodes[0].second;
7651   for (unsigned i=1; i<LoadNodes.size(); ++i) {
7652     int64_t CurrAddress = LoadNodes[i].second;
7653     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7654       break;
7655     LastConsecutiveLoad = i;
7656   }
7657
7658   unsigned NumElem =
7659     std::min(LastConsecutiveStore + 1, LastConsecutiveLoad + 1);
7660
7661   EVT JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
7662   DebugLoc LoadDL = LoadNodes[0].first->getDebugLoc();
7663   DebugLoc StoreDL = StoreNodes[0].first->getDebugLoc();
7664
7665   LoadSDNode *FirstLoad = LoadNodes[0].first;
7666   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
7667                                 FirstLoad->getChain(),
7668                                 FirstLoad->getBasePtr(),
7669                                 FirstLoad->getPointerInfo(),
7670                                 false, false, false,
7671                                 FirstLoad->getAlignment());
7672
7673   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
7674                                   EarliestOp->getBasePtr(),
7675                                   EarliestOp->getPointerInfo(), false, false,
7676                                   EarliestOp->getAlignment());
7677
7678   for (unsigned i = 0; i < NumElem ; ++i) {
7679     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].first);
7680     CombineTo(St, NewStore);
7681   }
7682
7683   return true;
7684 }
7685
7686 SDValue DAGCombiner::visitSTORE(SDNode *N) {
7687   StoreSDNode *ST  = cast<StoreSDNode>(N);
7688   SDValue Chain = ST->getChain();
7689   SDValue Value = ST->getValue();
7690   SDValue Ptr   = ST->getBasePtr();
7691
7692   // If this is a store of a bit convert, store the input value if the
7693   // resultant store does not need a higher alignment than the original.
7694   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
7695       ST->isUnindexed()) {
7696     unsigned OrigAlign = ST->getAlignment();
7697     EVT SVT = Value.getOperand(0).getValueType();
7698     unsigned Align = TLI.getTargetData()->
7699       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
7700     if (Align <= OrigAlign &&
7701         ((!LegalOperations && !ST->isVolatile()) ||
7702          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
7703       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7704                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
7705                           ST->isNonTemporal(), OrigAlign);
7706   }
7707
7708   // Turn 'store undef, Ptr' -> nothing.
7709   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
7710     return Chain;
7711
7712   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
7713   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
7714     // NOTE: If the original store is volatile, this transform must not increase
7715     // the number of stores.  For example, on x86-32 an f64 can be stored in one
7716     // processor operation but an i64 (which is not legal) requires two.  So the
7717     // transform should not be done in this case.
7718     if (Value.getOpcode() != ISD::TargetConstantFP) {
7719       SDValue Tmp;
7720       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
7721       default: llvm_unreachable("Unknown FP type");
7722       case MVT::f16:    // We don't do this for these yet.
7723       case MVT::f80:
7724       case MVT::f128:
7725       case MVT::ppcf128:
7726         break;
7727       case MVT::f32:
7728         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
7729             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7730           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
7731                               bitcastToAPInt().getZExtValue(), MVT::i32);
7732           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7733                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
7734                               ST->isNonTemporal(), ST->getAlignment());
7735         }
7736         break;
7737       case MVT::f64:
7738         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
7739              !ST->isVolatile()) ||
7740             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
7741           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
7742                                 getZExtValue(), MVT::i64);
7743           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7744                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
7745                               ST->isNonTemporal(), ST->getAlignment());
7746         }
7747
7748         if (!ST->isVolatile() &&
7749             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7750           // Many FP stores are not made apparent until after legalize, e.g. for
7751           // argument passing.  Since this is so common, custom legalize the
7752           // 64-bit integer store into two 32-bit stores.
7753           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
7754           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
7755           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
7756           if (TLI.isBigEndian()) std::swap(Lo, Hi);
7757
7758           unsigned Alignment = ST->getAlignment();
7759           bool isVolatile = ST->isVolatile();
7760           bool isNonTemporal = ST->isNonTemporal();
7761
7762           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
7763                                      Ptr, ST->getPointerInfo(),
7764                                      isVolatile, isNonTemporal,
7765                                      ST->getAlignment());
7766           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
7767                             DAG.getConstant(4, Ptr.getValueType()));
7768           Alignment = MinAlign(Alignment, 4U);
7769           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
7770                                      Ptr, ST->getPointerInfo().getWithOffset(4),
7771                                      isVolatile, isNonTemporal,
7772                                      Alignment);
7773           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7774                              St0, St1);
7775         }
7776
7777         break;
7778       }
7779     }
7780   }
7781
7782   // Try to infer better alignment information than the store already has.
7783   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
7784     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7785       if (Align > ST->getAlignment())
7786         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
7787                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7788                                  ST->isVolatile(), ST->isNonTemporal(), Align);
7789     }
7790   }
7791
7792   // Try transforming a pair floating point load / store ops to integer
7793   // load / store ops.
7794   SDValue NewST = TransformFPLoadStorePair(N);
7795   if (NewST.getNode())
7796     return NewST;
7797
7798   if (CombinerAA) {
7799     // Walk up chain skipping non-aliasing memory nodes.
7800     SDValue BetterChain = FindBetterChain(N, Chain);
7801
7802     // If there is a better chain.
7803     if (Chain != BetterChain) {
7804       SDValue ReplStore;
7805
7806       // Replace the chain to avoid dependency.
7807       if (ST->isTruncatingStore()) {
7808         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7809                                       ST->getPointerInfo(),
7810                                       ST->getMemoryVT(), ST->isVolatile(),
7811                                       ST->isNonTemporal(), ST->getAlignment());
7812       } else {
7813         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7814                                  ST->getPointerInfo(),
7815                                  ST->isVolatile(), ST->isNonTemporal(),
7816                                  ST->getAlignment());
7817       }
7818
7819       // Create token to keep both nodes around.
7820       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7821                                   MVT::Other, Chain, ReplStore);
7822
7823       // Make sure the new and old chains are cleaned up.
7824       AddToWorkList(Token.getNode());
7825
7826       // Don't add users to work list.
7827       return CombineTo(N, Token, false);
7828     }
7829   }
7830
7831   // Try transforming N to an indexed store.
7832   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7833     return SDValue(N, 0);
7834
7835   // FIXME: is there such a thing as a truncating indexed store?
7836   if (ST->isTruncatingStore() && ST->isUnindexed() &&
7837       Value.getValueType().isInteger()) {
7838     // See if we can simplify the input to this truncstore with knowledge that
7839     // only the low bits are being used.  For example:
7840     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
7841     SDValue Shorter =
7842       GetDemandedBits(Value,
7843                       APInt::getLowBitsSet(
7844                         Value.getValueType().getScalarType().getSizeInBits(),
7845                         ST->getMemoryVT().getScalarType().getSizeInBits()));
7846     AddToWorkList(Value.getNode());
7847     if (Shorter.getNode())
7848       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
7849                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7850                                ST->isVolatile(), ST->isNonTemporal(),
7851                                ST->getAlignment());
7852
7853     // Otherwise, see if we can simplify the operation with
7854     // SimplifyDemandedBits, which only works if the value has a single use.
7855     if (SimplifyDemandedBits(Value,
7856                         APInt::getLowBitsSet(
7857                           Value.getValueType().getScalarType().getSizeInBits(),
7858                           ST->getMemoryVT().getScalarType().getSizeInBits())))
7859       return SDValue(N, 0);
7860   }
7861
7862   // If this is a load followed by a store to the same location, then the store
7863   // is dead/noop.
7864   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
7865     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
7866         ST->isUnindexed() && !ST->isVolatile() &&
7867         // There can't be any side effects between the load and store, such as
7868         // a call or store.
7869         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
7870       // The store is dead, remove it.
7871       return Chain;
7872     }
7873   }
7874
7875   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
7876   // truncating store.  We can do this even if this is already a truncstore.
7877   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
7878       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
7879       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
7880                             ST->getMemoryVT())) {
7881     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7882                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7883                              ST->isVolatile(), ST->isNonTemporal(),
7884                              ST->getAlignment());
7885   }
7886
7887
7888   // Only perform this optimization before the types are legal, because we
7889   // don't want to generate illegal types in this optimization.
7890   if (!LegalTypes && MergeConsecutiveStores(ST))
7891     return SDValue(N, 0);
7892
7893   return ReduceLoadOpStoreWidth(N);
7894 }
7895
7896 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
7897   SDValue InVec = N->getOperand(0);
7898   SDValue InVal = N->getOperand(1);
7899   SDValue EltNo = N->getOperand(2);
7900   DebugLoc dl = N->getDebugLoc();
7901
7902   // If the inserted element is an UNDEF, just use the input vector.
7903   if (InVal.getOpcode() == ISD::UNDEF)
7904     return InVec;
7905
7906   EVT VT = InVec.getValueType();
7907
7908   // If we can't generate a legal BUILD_VECTOR, exit
7909   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
7910     return SDValue();
7911
7912   // Check that we know which element is being inserted
7913   if (!isa<ConstantSDNode>(EltNo))
7914     return SDValue();
7915   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7916
7917   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
7918   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
7919   // vector elements.
7920   SmallVector<SDValue, 8> Ops;
7921   if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
7922     Ops.append(InVec.getNode()->op_begin(),
7923                InVec.getNode()->op_end());
7924   } else if (InVec.getOpcode() == ISD::UNDEF) {
7925     unsigned NElts = VT.getVectorNumElements();
7926     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
7927   } else {
7928     return SDValue();
7929   }
7930
7931   // Insert the element
7932   if (Elt < Ops.size()) {
7933     // All the operands of BUILD_VECTOR must have the same type;
7934     // we enforce that here.
7935     EVT OpVT = Ops[0].getValueType();
7936     if (InVal.getValueType() != OpVT)
7937       InVal = OpVT.bitsGT(InVal.getValueType()) ?
7938                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
7939                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
7940     Ops[Elt] = InVal;
7941   }
7942
7943   // Return the new vector
7944   return DAG.getNode(ISD::BUILD_VECTOR, dl,
7945                      VT, &Ops[0], Ops.size());
7946 }
7947
7948 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
7949   // (vextract (scalar_to_vector val, 0) -> val
7950   SDValue InVec = N->getOperand(0);
7951   EVT VT = InVec.getValueType();
7952   EVT NVT = N->getValueType(0);
7953
7954   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7955     // Check if the result type doesn't match the inserted element type. A
7956     // SCALAR_TO_VECTOR may truncate the inserted element and the
7957     // EXTRACT_VECTOR_ELT may widen the extracted vector.
7958     SDValue InOp = InVec.getOperand(0);
7959     if (InOp.getValueType() != NVT) {
7960       assert(InOp.getValueType().isInteger() && NVT.isInteger());
7961       return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
7962     }
7963     return InOp;
7964   }
7965
7966   SDValue EltNo = N->getOperand(1);
7967   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
7968
7969   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
7970   // We only perform this optimization before the op legalization phase because
7971   // we may introduce new vector instructions which are not backed by TD
7972   // patterns. For example on AVX, extracting elements from a wide vector
7973   // without using extract_subvector.
7974   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
7975       && ConstEltNo && !LegalOperations) {
7976     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7977     int NumElem = VT.getVectorNumElements();
7978     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
7979     // Find the new index to extract from.
7980     int OrigElt = SVOp->getMaskElt(Elt);
7981
7982     // Extracting an undef index is undef.
7983     if (OrigElt == -1)
7984       return DAG.getUNDEF(NVT);
7985
7986     // Select the right vector half to extract from.
7987     if (OrigElt < NumElem) {
7988       InVec = InVec->getOperand(0);
7989     } else {
7990       InVec = InVec->getOperand(1);
7991       OrigElt -= NumElem;
7992     }
7993
7994     EVT IndexTy = N->getOperand(1).getValueType();
7995     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
7996                        InVec, DAG.getConstant(OrigElt, IndexTy));
7997   }
7998
7999   // Perform only after legalization to ensure build_vector / vector_shuffle
8000   // optimizations have already been done.
8001   if (!LegalOperations) return SDValue();
8002
8003   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8004   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8005   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8006
8007   if (ConstEltNo) {
8008     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8009     bool NewLoad = false;
8010     bool BCNumEltsChanged = false;
8011     EVT ExtVT = VT.getVectorElementType();
8012     EVT LVT = ExtVT;
8013
8014     // If the result of load has to be truncated, then it's not necessarily
8015     // profitable.
8016     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8017       return SDValue();
8018
8019     if (InVec.getOpcode() == ISD::BITCAST) {
8020       // Don't duplicate a load with other uses.
8021       if (!InVec.hasOneUse())
8022         return SDValue();
8023
8024       EVT BCVT = InVec.getOperand(0).getValueType();
8025       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8026         return SDValue();
8027       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8028         BCNumEltsChanged = true;
8029       InVec = InVec.getOperand(0);
8030       ExtVT = BCVT.getVectorElementType();
8031       NewLoad = true;
8032     }
8033
8034     LoadSDNode *LN0 = NULL;
8035     const ShuffleVectorSDNode *SVN = NULL;
8036     if (ISD::isNormalLoad(InVec.getNode())) {
8037       LN0 = cast<LoadSDNode>(InVec);
8038     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8039                InVec.getOperand(0).getValueType() == ExtVT &&
8040                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8041       // Don't duplicate a load with other uses.
8042       if (!InVec.hasOneUse())
8043         return SDValue();
8044
8045       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8046     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8047       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8048       // =>
8049       // (load $addr+1*size)
8050
8051       // Don't duplicate a load with other uses.
8052       if (!InVec.hasOneUse())
8053         return SDValue();
8054
8055       // If the bit convert changed the number of elements, it is unsafe
8056       // to examine the mask.
8057       if (BCNumEltsChanged)
8058         return SDValue();
8059
8060       // Select the input vector, guarding against out of range extract vector.
8061       unsigned NumElems = VT.getVectorNumElements();
8062       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8063       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8064
8065       if (InVec.getOpcode() == ISD::BITCAST) {
8066         // Don't duplicate a load with other uses.
8067         if (!InVec.hasOneUse())
8068           return SDValue();
8069
8070         InVec = InVec.getOperand(0);
8071       }
8072       if (ISD::isNormalLoad(InVec.getNode())) {
8073         LN0 = cast<LoadSDNode>(InVec);
8074         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8075       }
8076     }
8077
8078     // Make sure we found a non-volatile load and the extractelement is
8079     // the only use.
8080     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8081       return SDValue();
8082
8083     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8084     if (Elt == -1)
8085       return DAG.getUNDEF(LVT);
8086
8087     unsigned Align = LN0->getAlignment();
8088     if (NewLoad) {
8089       // Check the resultant load doesn't need a higher alignment than the
8090       // original load.
8091       unsigned NewAlign =
8092         TLI.getTargetData()
8093             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8094
8095       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8096         return SDValue();
8097
8098       Align = NewAlign;
8099     }
8100
8101     SDValue NewPtr = LN0->getBasePtr();
8102     unsigned PtrOff = 0;
8103
8104     if (Elt) {
8105       PtrOff = LVT.getSizeInBits() * Elt / 8;
8106       EVT PtrType = NewPtr.getValueType();
8107       if (TLI.isBigEndian())
8108         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8109       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
8110                            DAG.getConstant(PtrOff, PtrType));
8111     }
8112
8113     // The replacement we need to do here is a little tricky: we need to
8114     // replace an extractelement of a load with a load.
8115     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8116     // Note that this replacement assumes that the extractvalue is the only
8117     // use of the load; that's okay because we don't want to perform this
8118     // transformation in other cases anyway.
8119     SDValue Load;
8120     SDValue Chain;
8121     if (NVT.bitsGT(LVT)) {
8122       // If the result type of vextract is wider than the load, then issue an
8123       // extending load instead.
8124       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8125         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8126       Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
8127                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8128                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8129       Chain = Load.getValue(1);
8130     } else {
8131       Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
8132                          LN0->getPointerInfo().getWithOffset(PtrOff),
8133                          LN0->isVolatile(), LN0->isNonTemporal(), 
8134                          LN0->isInvariant(), Align);
8135       Chain = Load.getValue(1);
8136       if (NVT.bitsLT(LVT))
8137         Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
8138       else
8139         Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
8140     }
8141     WorkListRemover DeadNodes(*this);
8142     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8143     SDValue To[] = { Load, Chain };
8144     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8145     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8146     // worklist explicitly as well.
8147     AddToWorkList(Load.getNode());
8148     AddUsersToWorkList(Load.getNode()); // Add users too
8149     // Make sure to revisit this node to clean it up; it will usually be dead.
8150     AddToWorkList(N);
8151     return SDValue(N, 0);
8152   }
8153
8154   return SDValue();
8155 }
8156
8157 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
8158   unsigned NumInScalars = N->getNumOperands();
8159   DebugLoc dl = N->getDebugLoc();
8160   EVT VT = N->getValueType(0);
8161
8162   // A vector built entirely of undefs is undef.
8163   if (ISD::allOperandsUndef(N))
8164     return DAG.getUNDEF(VT);
8165
8166   // Check to see if this is a BUILD_VECTOR of a bunch of values
8167   // which come from any_extend or zero_extend nodes. If so, we can create
8168   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8169   // optimizations. We do not handle sign-extend because we can't fill the sign
8170   // using shuffles.
8171   EVT SourceType = MVT::Other;
8172   bool AllAnyExt = true;
8173
8174   for (unsigned i = 0; i != NumInScalars; ++i) {
8175     SDValue In = N->getOperand(i);
8176     // Ignore undef inputs.
8177     if (In.getOpcode() == ISD::UNDEF) continue;
8178
8179     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8180     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8181
8182     // Abort if the element is not an extension.
8183     if (!ZeroExt && !AnyExt) {
8184       SourceType = MVT::Other;
8185       break;
8186     }
8187
8188     // The input is a ZeroExt or AnyExt. Check the original type.
8189     EVT InTy = In.getOperand(0).getValueType();
8190
8191     // Check that all of the widened source types are the same.
8192     if (SourceType == MVT::Other)
8193       // First time.
8194       SourceType = InTy;
8195     else if (InTy != SourceType) {
8196       // Multiple income types. Abort.
8197       SourceType = MVT::Other;
8198       break;
8199     }
8200
8201     // Check if all of the extends are ANY_EXTENDs.
8202     AllAnyExt &= AnyExt;
8203   }
8204
8205   // In order to have valid types, all of the inputs must be extended from the
8206   // same source type and all of the inputs must be any or zero extend.
8207   // Scalar sizes must be a power of two.
8208   EVT OutScalarTy = N->getValueType(0).getScalarType();
8209   bool ValidTypes = SourceType != MVT::Other &&
8210                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8211                  isPowerOf2_32(SourceType.getSizeInBits());
8212
8213   // We perform this optimization post type-legalization because
8214   // the type-legalizer often scalarizes integer-promoted vectors.
8215   // Performing this optimization before may create bit-casts which
8216   // will be type-legalized to complex code sequences.
8217   // We perform this optimization only before the operation legalizer because we
8218   // may introduce illegal operations.
8219   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8220   // turn into a single shuffle instruction.
8221   if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) &&
8222       ValidTypes) {
8223     bool isLE = TLI.isLittleEndian();
8224     unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8225     assert(ElemRatio > 1 && "Invalid element size ratio");
8226     SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8227                                  DAG.getConstant(0, SourceType);
8228
8229     unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements();
8230     SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8231
8232     // Populate the new build_vector
8233     for (unsigned i=0; i < N->getNumOperands(); ++i) {
8234       SDValue Cast = N->getOperand(i);
8235       assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8236               Cast.getOpcode() == ISD::ZERO_EXTEND ||
8237               Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8238       SDValue In;
8239       if (Cast.getOpcode() == ISD::UNDEF)
8240         In = DAG.getUNDEF(SourceType);
8241       else
8242         In = Cast->getOperand(0);
8243       unsigned Index = isLE ? (i * ElemRatio) :
8244                               (i * ElemRatio + (ElemRatio - 1));
8245
8246       assert(Index < Ops.size() && "Invalid index");
8247       Ops[Index] = In;
8248     }
8249
8250     // The type of the new BUILD_VECTOR node.
8251     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8252     assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() &&
8253            "Invalid vector size");
8254     // Check if the new vector type is legal.
8255     if (!isTypeLegal(VecVT)) return SDValue();
8256
8257     // Make the new BUILD_VECTOR.
8258     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8259                                  VecVT, &Ops[0], Ops.size());
8260
8261     // The new BUILD_VECTOR node has the potential to be further optimized.
8262     AddToWorkList(BV.getNode());
8263     // Bitcast to the desired type.
8264     return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
8265   }
8266
8267   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
8268   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
8269   // at most two distinct vectors, turn this into a shuffle node.
8270
8271   // May only combine to shuffle after legalize if shuffle is legal.
8272   if (LegalOperations &&
8273       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
8274     return SDValue();
8275
8276   SDValue VecIn1, VecIn2;
8277   for (unsigned i = 0; i != NumInScalars; ++i) {
8278     // Ignore undef inputs.
8279     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
8280
8281     // If this input is something other than a EXTRACT_VECTOR_ELT with a
8282     // constant index, bail out.
8283     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8284         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
8285       VecIn1 = VecIn2 = SDValue(0, 0);
8286       break;
8287     }
8288
8289     // We allow up to two distinct input vectors.
8290     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
8291     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
8292       continue;
8293
8294     if (VecIn1.getNode() == 0) {
8295       VecIn1 = ExtractedFromVec;
8296     } else if (VecIn2.getNode() == 0) {
8297       VecIn2 = ExtractedFromVec;
8298     } else {
8299       // Too many inputs.
8300       VecIn1 = VecIn2 = SDValue(0, 0);
8301       break;
8302     }
8303   }
8304
8305     // If everything is good, we can make a shuffle operation.
8306   if (VecIn1.getNode()) {
8307     SmallVector<int, 8> Mask;
8308     for (unsigned i = 0; i != NumInScalars; ++i) {
8309       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
8310         Mask.push_back(-1);
8311         continue;
8312       }
8313
8314       // If extracting from the first vector, just use the index directly.
8315       SDValue Extract = N->getOperand(i);
8316       SDValue ExtVal = Extract.getOperand(1);
8317       if (Extract.getOperand(0) == VecIn1) {
8318         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
8319         if (ExtIndex > VT.getVectorNumElements())
8320           return SDValue();
8321
8322         Mask.push_back(ExtIndex);
8323         continue;
8324       }
8325
8326       // Otherwise, use InIdx + VecSize
8327       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
8328       Mask.push_back(Idx+NumInScalars);
8329     }
8330
8331     // We can't generate a shuffle node with mismatched input and output types.
8332     // Attempt to transform a single input vector to the correct type.
8333     if ((VT != VecIn1.getValueType())) {
8334       // We don't support shuffeling between TWO values of different types.
8335       if (VecIn2.getNode() != 0)
8336         return SDValue();
8337
8338       // We only support widening of vectors which are half the size of the
8339       // output registers. For example XMM->YMM widening on X86 with AVX.
8340       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
8341         return SDValue();
8342
8343       // If the input vector type has a different base type to the output
8344       // vector type, bail out.
8345       if (VecIn1.getValueType().getVectorElementType() !=
8346           VT.getVectorElementType())
8347         return SDValue();
8348
8349       // Widen the input vector by adding undef values.
8350       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8351                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
8352     }
8353
8354     // If VecIn2 is unused then change it to undef.
8355     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
8356
8357     // Check that we were able to transform all incoming values to the same
8358     // type.
8359     if (VecIn2.getValueType() != VecIn1.getValueType() ||
8360         VecIn1.getValueType() != VT)
8361           return SDValue();
8362
8363     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
8364     if (!isTypeLegal(VT))
8365       return SDValue();
8366
8367     // Return the new VECTOR_SHUFFLE node.
8368     SDValue Ops[2];
8369     Ops[0] = VecIn1;
8370     Ops[1] = VecIn2;
8371     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
8372   }
8373
8374   return SDValue();
8375 }
8376
8377 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
8378   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
8379   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
8380   // inputs come from at most two distinct vectors, turn this into a shuffle
8381   // node.
8382
8383   // If we only have one input vector, we don't need to do any concatenation.
8384   if (N->getNumOperands() == 1)
8385     return N->getOperand(0);
8386
8387   // Check if all of the operands are undefs.
8388   if (ISD::allOperandsUndef(N))
8389     return DAG.getUNDEF(N->getValueType(0));
8390
8391   return SDValue();
8392 }
8393
8394 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
8395   EVT NVT = N->getValueType(0);
8396   SDValue V = N->getOperand(0);
8397
8398   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
8399     // Handle only simple case where vector being inserted and vector
8400     // being extracted are of same type, and are half size of larger vectors.
8401     EVT BigVT = V->getOperand(0).getValueType();
8402     EVT SmallVT = V->getOperand(1).getValueType();
8403     if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
8404       return SDValue();
8405
8406     // Only handle cases where both indexes are constants with the same type.
8407     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
8408     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
8409
8410     if (InsIdx && ExtIdx &&
8411         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
8412         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
8413       // Combine:
8414       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
8415       // Into:
8416       //    indices are equal => V1
8417       //    otherwise => (extract_subvec V1, ExtIdx)
8418       if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
8419         return V->getOperand(1);
8420       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
8421                          V->getOperand(0), N->getOperand(1));
8422     }
8423   }
8424
8425   return SDValue();
8426 }
8427
8428 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
8429   EVT VT = N->getValueType(0);
8430   unsigned NumElts = VT.getVectorNumElements();
8431
8432   SDValue N0 = N->getOperand(0);
8433   SDValue N1 = N->getOperand(1);
8434
8435   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
8436
8437   // Canonicalize shuffle undef, undef -> undef
8438   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
8439     return DAG.getUNDEF(VT);
8440
8441   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8442
8443   // Canonicalize shuffle v, v -> v, undef
8444   if (N0 == N1) {
8445     SmallVector<int, 8> NewMask;
8446     for (unsigned i = 0; i != NumElts; ++i) {
8447       int Idx = SVN->getMaskElt(i);
8448       if (Idx >= (int)NumElts) Idx -= NumElts;
8449       NewMask.push_back(Idx);
8450     }
8451     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
8452                                 &NewMask[0]);
8453   }
8454
8455   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
8456   if (N0.getOpcode() == ISD::UNDEF) {
8457     SmallVector<int, 8> NewMask;
8458     for (unsigned i = 0; i != NumElts; ++i) {
8459       int Idx = SVN->getMaskElt(i);
8460       if (Idx >= 0) {
8461         if (Idx < (int)NumElts)
8462           Idx += NumElts;
8463         else
8464           Idx -= NumElts;
8465       }
8466       NewMask.push_back(Idx);
8467     }
8468     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
8469                                 &NewMask[0]);
8470   }
8471
8472   // Remove references to rhs if it is undef
8473   if (N1.getOpcode() == ISD::UNDEF) {
8474     bool Changed = false;
8475     SmallVector<int, 8> NewMask;
8476     for (unsigned i = 0; i != NumElts; ++i) {
8477       int Idx = SVN->getMaskElt(i);
8478       if (Idx >= (int)NumElts) {
8479         Idx = -1;
8480         Changed = true;
8481       }
8482       NewMask.push_back(Idx);
8483     }
8484     if (Changed)
8485       return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
8486   }
8487
8488   // If it is a splat, check if the argument vector is another splat or a
8489   // build_vector with all scalar elements the same.
8490   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
8491     SDNode *V = N0.getNode();
8492
8493     // If this is a bit convert that changes the element type of the vector but
8494     // not the number of vector elements, look through it.  Be careful not to
8495     // look though conversions that change things like v4f32 to v2f64.
8496     if (V->getOpcode() == ISD::BITCAST) {
8497       SDValue ConvInput = V->getOperand(0);
8498       if (ConvInput.getValueType().isVector() &&
8499           ConvInput.getValueType().getVectorNumElements() == NumElts)
8500         V = ConvInput.getNode();
8501     }
8502
8503     if (V->getOpcode() == ISD::BUILD_VECTOR) {
8504       assert(V->getNumOperands() == NumElts &&
8505              "BUILD_VECTOR has wrong number of operands");
8506       SDValue Base;
8507       bool AllSame = true;
8508       for (unsigned i = 0; i != NumElts; ++i) {
8509         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
8510           Base = V->getOperand(i);
8511           break;
8512         }
8513       }
8514       // Splat of <u, u, u, u>, return <u, u, u, u>
8515       if (!Base.getNode())
8516         return N0;
8517       for (unsigned i = 0; i != NumElts; ++i) {
8518         if (V->getOperand(i) != Base) {
8519           AllSame = false;
8520           break;
8521         }
8522       }
8523       // Splat of <x, x, x, x>, return <x, x, x, x>
8524       if (AllSame)
8525         return N0;
8526     }
8527   }
8528
8529   // If this shuffle node is simply a swizzle of another shuffle node,
8530   // and it reverses the swizzle of the previous shuffle then we can
8531   // optimize shuffle(shuffle(x, undef), undef) -> x.
8532   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
8533       N1.getOpcode() == ISD::UNDEF) {
8534
8535     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
8536
8537     // Shuffle nodes can only reverse shuffles with a single non-undef value.
8538     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
8539       return SDValue();
8540
8541     // The incoming shuffle must be of the same type as the result of the
8542     // current shuffle.
8543     assert(OtherSV->getOperand(0).getValueType() == VT &&
8544            "Shuffle types don't match");
8545
8546     for (unsigned i = 0; i != NumElts; ++i) {
8547       int Idx = SVN->getMaskElt(i);
8548       assert(Idx < (int)NumElts && "Index references undef operand");
8549       // Next, this index comes from the first value, which is the incoming
8550       // shuffle. Adopt the incoming index.
8551       if (Idx >= 0)
8552         Idx = OtherSV->getMaskElt(Idx);
8553
8554       // The combined shuffle must map each index to itself.
8555       if (Idx >= 0 && (unsigned)Idx != i)
8556         return SDValue();
8557     }
8558
8559     return OtherSV->getOperand(0);
8560   }
8561
8562   return SDValue();
8563 }
8564
8565 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
8566   if (!TLI.getShouldFoldAtomicFences())
8567     return SDValue();
8568
8569   SDValue atomic = N->getOperand(0);
8570   switch (atomic.getOpcode()) {
8571     case ISD::ATOMIC_CMP_SWAP:
8572     case ISD::ATOMIC_SWAP:
8573     case ISD::ATOMIC_LOAD_ADD:
8574     case ISD::ATOMIC_LOAD_SUB:
8575     case ISD::ATOMIC_LOAD_AND:
8576     case ISD::ATOMIC_LOAD_OR:
8577     case ISD::ATOMIC_LOAD_XOR:
8578     case ISD::ATOMIC_LOAD_NAND:
8579     case ISD::ATOMIC_LOAD_MIN:
8580     case ISD::ATOMIC_LOAD_MAX:
8581     case ISD::ATOMIC_LOAD_UMIN:
8582     case ISD::ATOMIC_LOAD_UMAX:
8583       break;
8584     default:
8585       return SDValue();
8586   }
8587
8588   SDValue fence = atomic.getOperand(0);
8589   if (fence.getOpcode() != ISD::MEMBARRIER)
8590     return SDValue();
8591
8592   switch (atomic.getOpcode()) {
8593     case ISD::ATOMIC_CMP_SWAP:
8594       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8595                                     fence.getOperand(0),
8596                                     atomic.getOperand(1), atomic.getOperand(2),
8597                                     atomic.getOperand(3)), atomic.getResNo());
8598     case ISD::ATOMIC_SWAP:
8599     case ISD::ATOMIC_LOAD_ADD:
8600     case ISD::ATOMIC_LOAD_SUB:
8601     case ISD::ATOMIC_LOAD_AND:
8602     case ISD::ATOMIC_LOAD_OR:
8603     case ISD::ATOMIC_LOAD_XOR:
8604     case ISD::ATOMIC_LOAD_NAND:
8605     case ISD::ATOMIC_LOAD_MIN:
8606     case ISD::ATOMIC_LOAD_MAX:
8607     case ISD::ATOMIC_LOAD_UMIN:
8608     case ISD::ATOMIC_LOAD_UMAX:
8609       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
8610                                     fence.getOperand(0),
8611                                     atomic.getOperand(1), atomic.getOperand(2)),
8612                      atomic.getResNo());
8613     default:
8614       return SDValue();
8615   }
8616 }
8617
8618 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
8619 /// an AND to a vector_shuffle with the destination vector and a zero vector.
8620 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
8621 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
8622 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
8623   EVT VT = N->getValueType(0);
8624   DebugLoc dl = N->getDebugLoc();
8625   SDValue LHS = N->getOperand(0);
8626   SDValue RHS = N->getOperand(1);
8627   if (N->getOpcode() == ISD::AND) {
8628     if (RHS.getOpcode() == ISD::BITCAST)
8629       RHS = RHS.getOperand(0);
8630     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
8631       SmallVector<int, 8> Indices;
8632       unsigned NumElts = RHS.getNumOperands();
8633       for (unsigned i = 0; i != NumElts; ++i) {
8634         SDValue Elt = RHS.getOperand(i);
8635         if (!isa<ConstantSDNode>(Elt))
8636           return SDValue();
8637
8638         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
8639           Indices.push_back(i);
8640         else if (cast<ConstantSDNode>(Elt)->isNullValue())
8641           Indices.push_back(NumElts);
8642         else
8643           return SDValue();
8644       }
8645
8646       // Let's see if the target supports this vector_shuffle.
8647       EVT RVT = RHS.getValueType();
8648       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
8649         return SDValue();
8650
8651       // Return the new VECTOR_SHUFFLE node.
8652       EVT EltVT = RVT.getVectorElementType();
8653       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
8654                                      DAG.getConstant(0, EltVT));
8655       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8656                                  RVT, &ZeroOps[0], ZeroOps.size());
8657       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
8658       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
8659       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
8660     }
8661   }
8662
8663   return SDValue();
8664 }
8665
8666 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
8667 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
8668   // After legalize, the target may be depending on adds and other
8669   // binary ops to provide legal ways to construct constants or other
8670   // things. Simplifying them may result in a loss of legality.
8671   if (LegalOperations) return SDValue();
8672
8673   assert(N->getValueType(0).isVector() &&
8674          "SimplifyVBinOp only works on vectors!");
8675
8676   SDValue LHS = N->getOperand(0);
8677   SDValue RHS = N->getOperand(1);
8678   SDValue Shuffle = XformToShuffleWithZero(N);
8679   if (Shuffle.getNode()) return Shuffle;
8680
8681   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
8682   // this operation.
8683   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
8684       RHS.getOpcode() == ISD::BUILD_VECTOR) {
8685     SmallVector<SDValue, 8> Ops;
8686     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
8687       SDValue LHSOp = LHS.getOperand(i);
8688       SDValue RHSOp = RHS.getOperand(i);
8689       // If these two elements can't be folded, bail out.
8690       if ((LHSOp.getOpcode() != ISD::UNDEF &&
8691            LHSOp.getOpcode() != ISD::Constant &&
8692            LHSOp.getOpcode() != ISD::ConstantFP) ||
8693           (RHSOp.getOpcode() != ISD::UNDEF &&
8694            RHSOp.getOpcode() != ISD::Constant &&
8695            RHSOp.getOpcode() != ISD::ConstantFP))
8696         break;
8697
8698       // Can't fold divide by zero.
8699       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
8700           N->getOpcode() == ISD::FDIV) {
8701         if ((RHSOp.getOpcode() == ISD::Constant &&
8702              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
8703             (RHSOp.getOpcode() == ISD::ConstantFP &&
8704              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
8705           break;
8706       }
8707
8708       EVT VT = LHSOp.getValueType();
8709       EVT RVT = RHSOp.getValueType();
8710       if (RVT != VT) {
8711         // Integer BUILD_VECTOR operands may have types larger than the element
8712         // size (e.g., when the element type is not legal).  Prior to type
8713         // legalization, the types may not match between the two BUILD_VECTORS.
8714         // Truncate one of the operands to make them match.
8715         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
8716           RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
8717         } else {
8718           LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
8719           VT = RVT;
8720         }
8721       }
8722       SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
8723                                    LHSOp, RHSOp);
8724       if (FoldOp.getOpcode() != ISD::UNDEF &&
8725           FoldOp.getOpcode() != ISD::Constant &&
8726           FoldOp.getOpcode() != ISD::ConstantFP)
8727         break;
8728       Ops.push_back(FoldOp);
8729       AddToWorkList(FoldOp.getNode());
8730     }
8731
8732     if (Ops.size() == LHS.getNumOperands())
8733       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8734                          LHS.getValueType(), &Ops[0], Ops.size());
8735   }
8736
8737   return SDValue();
8738 }
8739
8740 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
8741 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
8742   // After legalize, the target may be depending on adds and other
8743   // binary ops to provide legal ways to construct constants or other
8744   // things. Simplifying them may result in a loss of legality.
8745   if (LegalOperations) return SDValue();
8746
8747   assert(N->getValueType(0).isVector() &&
8748          "SimplifyVUnaryOp only works on vectors!");
8749
8750   SDValue N0 = N->getOperand(0);
8751
8752   if (N0.getOpcode() != ISD::BUILD_VECTOR)
8753     return SDValue();
8754
8755   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
8756   SmallVector<SDValue, 8> Ops;
8757   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8758     SDValue Op = N0.getOperand(i);
8759     if (Op.getOpcode() != ISD::UNDEF &&
8760         Op.getOpcode() != ISD::ConstantFP)
8761       break;
8762     EVT EltVT = Op.getValueType();
8763     SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op);
8764     if (FoldOp.getOpcode() != ISD::UNDEF &&
8765         FoldOp.getOpcode() != ISD::ConstantFP)
8766       break;
8767     Ops.push_back(FoldOp);
8768     AddToWorkList(FoldOp.getNode());
8769   }
8770
8771   if (Ops.size() != N0.getNumOperands())
8772     return SDValue();
8773
8774   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8775                      N0.getValueType(), &Ops[0], Ops.size());
8776 }
8777
8778 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
8779                                     SDValue N1, SDValue N2){
8780   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
8781
8782   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
8783                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
8784
8785   // If we got a simplified select_cc node back from SimplifySelectCC, then
8786   // break it down into a new SETCC node, and a new SELECT node, and then return
8787   // the SELECT node, since we were called with a SELECT node.
8788   if (SCC.getNode()) {
8789     // Check to see if we got a select_cc back (to turn into setcc/select).
8790     // Otherwise, just return whatever node we got back, like fabs.
8791     if (SCC.getOpcode() == ISD::SELECT_CC) {
8792       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
8793                                   N0.getValueType(),
8794                                   SCC.getOperand(0), SCC.getOperand(1),
8795                                   SCC.getOperand(4));
8796       AddToWorkList(SETCC.getNode());
8797       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
8798                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
8799     }
8800
8801     return SCC;
8802   }
8803   return SDValue();
8804 }
8805
8806 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
8807 /// are the two values being selected between, see if we can simplify the
8808 /// select.  Callers of this should assume that TheSelect is deleted if this
8809 /// returns true.  As such, they should return the appropriate thing (e.g. the
8810 /// node) back to the top-level of the DAG combiner loop to avoid it being
8811 /// looked at.
8812 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
8813                                     SDValue RHS) {
8814
8815   // Cannot simplify select with vector condition
8816   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
8817
8818   // If this is a select from two identical things, try to pull the operation
8819   // through the select.
8820   if (LHS.getOpcode() != RHS.getOpcode() ||
8821       !LHS.hasOneUse() || !RHS.hasOneUse())
8822     return false;
8823
8824   // If this is a load and the token chain is identical, replace the select
8825   // of two loads with a load through a select of the address to load from.
8826   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
8827   // constants have been dropped into the constant pool.
8828   if (LHS.getOpcode() == ISD::LOAD) {
8829     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
8830     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
8831
8832     // Token chains must be identical.
8833     if (LHS.getOperand(0) != RHS.getOperand(0) ||
8834         // Do not let this transformation reduce the number of volatile loads.
8835         LLD->isVolatile() || RLD->isVolatile() ||
8836         // If this is an EXTLOAD, the VT's must match.
8837         LLD->getMemoryVT() != RLD->getMemoryVT() ||
8838         // If this is an EXTLOAD, the kind of extension must match.
8839         (LLD->getExtensionType() != RLD->getExtensionType() &&
8840          // The only exception is if one of the extensions is anyext.
8841          LLD->getExtensionType() != ISD::EXTLOAD &&
8842          RLD->getExtensionType() != ISD::EXTLOAD) ||
8843         // FIXME: this discards src value information.  This is
8844         // over-conservative. It would be beneficial to be able to remember
8845         // both potential memory locations.  Since we are discarding
8846         // src value info, don't do the transformation if the memory
8847         // locations are not in the default address space.
8848         LLD->getPointerInfo().getAddrSpace() != 0 ||
8849         RLD->getPointerInfo().getAddrSpace() != 0)
8850       return false;
8851
8852     // Check that the select condition doesn't reach either load.  If so,
8853     // folding this will induce a cycle into the DAG.  If not, this is safe to
8854     // xform, so create a select of the addresses.
8855     SDValue Addr;
8856     if (TheSelect->getOpcode() == ISD::SELECT) {
8857       SDNode *CondNode = TheSelect->getOperand(0).getNode();
8858       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
8859           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
8860         return false;
8861       Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
8862                          LLD->getBasePtr().getValueType(),
8863                          TheSelect->getOperand(0), LLD->getBasePtr(),
8864                          RLD->getBasePtr());
8865     } else {  // Otherwise SELECT_CC
8866       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
8867       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
8868
8869       if ((LLD->hasAnyUseOfValue(1) &&
8870            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
8871           (RLD->hasAnyUseOfValue(1) &&
8872            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
8873         return false;
8874
8875       Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
8876                          LLD->getBasePtr().getValueType(),
8877                          TheSelect->getOperand(0),
8878                          TheSelect->getOperand(1),
8879                          LLD->getBasePtr(), RLD->getBasePtr(),
8880                          TheSelect->getOperand(4));
8881     }
8882
8883     SDValue Load;
8884     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
8885       Load = DAG.getLoad(TheSelect->getValueType(0),
8886                          TheSelect->getDebugLoc(),
8887                          // FIXME: Discards pointer info.
8888                          LLD->getChain(), Addr, MachinePointerInfo(),
8889                          LLD->isVolatile(), LLD->isNonTemporal(),
8890                          LLD->isInvariant(), LLD->getAlignment());
8891     } else {
8892       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
8893                             RLD->getExtensionType() : LLD->getExtensionType(),
8894                             TheSelect->getDebugLoc(),
8895                             TheSelect->getValueType(0),
8896                             // FIXME: Discards pointer info.
8897                             LLD->getChain(), Addr, MachinePointerInfo(),
8898                             LLD->getMemoryVT(), LLD->isVolatile(),
8899                             LLD->isNonTemporal(), LLD->getAlignment());
8900     }
8901
8902     // Users of the select now use the result of the load.
8903     CombineTo(TheSelect, Load);
8904
8905     // Users of the old loads now use the new load's chain.  We know the
8906     // old-load value is dead now.
8907     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
8908     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
8909     return true;
8910   }
8911
8912   return false;
8913 }
8914
8915 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
8916 /// where 'cond' is the comparison specified by CC.
8917 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
8918                                       SDValue N2, SDValue N3,
8919                                       ISD::CondCode CC, bool NotExtCompare) {
8920   // (x ? y : y) -> y.
8921   if (N2 == N3) return N2;
8922
8923   EVT VT = N2.getValueType();
8924   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
8925   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
8926   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
8927
8928   // Determine if the condition we're dealing with is constant
8929   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
8930                               N0, N1, CC, DL, false);
8931   if (SCC.getNode()) AddToWorkList(SCC.getNode());
8932   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
8933
8934   // fold select_cc true, x, y -> x
8935   if (SCCC && !SCCC->isNullValue())
8936     return N2;
8937   // fold select_cc false, x, y -> y
8938   if (SCCC && SCCC->isNullValue())
8939     return N3;
8940
8941   // Check to see if we can simplify the select into an fabs node
8942   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
8943     // Allow either -0.0 or 0.0
8944     if (CFP->getValueAPF().isZero()) {
8945       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
8946       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
8947           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
8948           N2 == N3.getOperand(0))
8949         return DAG.getNode(ISD::FABS, DL, VT, N0);
8950
8951       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
8952       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
8953           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
8954           N2.getOperand(0) == N3)
8955         return DAG.getNode(ISD::FABS, DL, VT, N3);
8956     }
8957   }
8958
8959   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
8960   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
8961   // in it.  This is a win when the constant is not otherwise available because
8962   // it replaces two constant pool loads with one.  We only do this if the FP
8963   // type is known to be legal, because if it isn't, then we are before legalize
8964   // types an we want the other legalization to happen first (e.g. to avoid
8965   // messing with soft float) and if the ConstantFP is not legal, because if
8966   // it is legal, we may not need to store the FP constant in a constant pool.
8967   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
8968     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
8969       if (TLI.isTypeLegal(N2.getValueType()) &&
8970           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
8971            TargetLowering::Legal) &&
8972           // If both constants have multiple uses, then we won't need to do an
8973           // extra load, they are likely around in registers for other users.
8974           (TV->hasOneUse() || FV->hasOneUse())) {
8975         Constant *Elts[] = {
8976           const_cast<ConstantFP*>(FV->getConstantFPValue()),
8977           const_cast<ConstantFP*>(TV->getConstantFPValue())
8978         };
8979         Type *FPTy = Elts[0]->getType();
8980         const TargetData &TD = *TLI.getTargetData();
8981
8982         // Create a ConstantArray of the two constants.
8983         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
8984         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
8985                                             TD.getPrefTypeAlignment(FPTy));
8986         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8987
8988         // Get the offsets to the 0 and 1 element of the array so that we can
8989         // select between them.
8990         SDValue Zero = DAG.getIntPtrConstant(0);
8991         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
8992         SDValue One = DAG.getIntPtrConstant(EltSize);
8993
8994         SDValue Cond = DAG.getSetCC(DL,
8995                                     TLI.getSetCCResultType(N0.getValueType()),
8996                                     N0, N1, CC);
8997         AddToWorkList(Cond.getNode());
8998         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
8999                                         Cond, One, Zero);
9000         AddToWorkList(CstOffset.getNode());
9001         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9002                             CstOffset);
9003         AddToWorkList(CPIdx.getNode());
9004         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9005                            MachinePointerInfo::getConstantPool(), false,
9006                            false, false, Alignment);
9007
9008       }
9009     }
9010
9011   // Check to see if we can perform the "gzip trick", transforming
9012   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9013   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9014       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9015        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9016     EVT XType = N0.getValueType();
9017     EVT AType = N2.getValueType();
9018     if (XType.bitsGE(AType)) {
9019       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9020       // single-bit constant.
9021       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9022         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9023         ShCtV = XType.getSizeInBits()-ShCtV-1;
9024         SDValue ShCt = DAG.getConstant(ShCtV,
9025                                        getShiftAmountTy(N0.getValueType()));
9026         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
9027                                     XType, N0, ShCt);
9028         AddToWorkList(Shift.getNode());
9029
9030         if (XType.bitsGT(AType)) {
9031           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9032           AddToWorkList(Shift.getNode());
9033         }
9034
9035         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9036       }
9037
9038       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
9039                                   XType, N0,
9040                                   DAG.getConstant(XType.getSizeInBits()-1,
9041                                          getShiftAmountTy(N0.getValueType())));
9042       AddToWorkList(Shift.getNode());
9043
9044       if (XType.bitsGT(AType)) {
9045         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9046         AddToWorkList(Shift.getNode());
9047       }
9048
9049       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9050     }
9051   }
9052
9053   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9054   // where y is has a single bit set.
9055   // A plaintext description would be, we can turn the SELECT_CC into an AND
9056   // when the condition can be materialized as an all-ones register.  Any
9057   // single bit-test can be materialized as an all-ones register with
9058   // shift-left and shift-right-arith.
9059   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9060       N0->getValueType(0) == VT &&
9061       N1C && N1C->isNullValue() &&
9062       N2C && N2C->isNullValue()) {
9063     SDValue AndLHS = N0->getOperand(0);
9064     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9065     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9066       // Shift the tested bit over the sign bit.
9067       APInt AndMask = ConstAndRHS->getAPIntValue();
9068       SDValue ShlAmt =
9069         DAG.getConstant(AndMask.countLeadingZeros(),
9070                         getShiftAmountTy(AndLHS.getValueType()));
9071       SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
9072
9073       // Now arithmetic right shift it all the way over, so the result is either
9074       // all-ones, or zero.
9075       SDValue ShrAmt =
9076         DAG.getConstant(AndMask.getBitWidth()-1,
9077                         getShiftAmountTy(Shl.getValueType()));
9078       SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
9079
9080       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9081     }
9082   }
9083
9084   // fold select C, 16, 0 -> shl C, 4
9085   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9086     TLI.getBooleanContents(N0.getValueType().isVector()) ==
9087       TargetLowering::ZeroOrOneBooleanContent) {
9088
9089     // If the caller doesn't want us to simplify this into a zext of a compare,
9090     // don't do it.
9091     if (NotExtCompare && N2C->getAPIntValue() == 1)
9092       return SDValue();
9093
9094     // Get a SetCC of the condition
9095     // FIXME: Should probably make sure that setcc is legal if we ever have a
9096     // target where it isn't.
9097     SDValue Temp, SCC;
9098     // cast from setcc result type to select result type
9099     if (LegalTypes) {
9100       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
9101                           N0, N1, CC);
9102       if (N2.getValueType().bitsLT(SCC.getValueType()))
9103         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
9104       else
9105         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9106                            N2.getValueType(), SCC);
9107     } else {
9108       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
9109       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9110                          N2.getValueType(), SCC);
9111     }
9112
9113     AddToWorkList(SCC.getNode());
9114     AddToWorkList(Temp.getNode());
9115
9116     if (N2C->getAPIntValue() == 1)
9117       return Temp;
9118
9119     // shl setcc result by log2 n2c
9120     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9121                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
9122                                        getShiftAmountTy(Temp.getValueType())));
9123   }
9124
9125   // Check to see if this is the equivalent of setcc
9126   // FIXME: Turn all of these into setcc if setcc if setcc is legal
9127   // otherwise, go ahead with the folds.
9128   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9129     EVT XType = N0.getValueType();
9130     if (!LegalOperations ||
9131         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
9132       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
9133       if (Res.getValueType() != VT)
9134         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9135       return Res;
9136     }
9137
9138     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9139     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9140         (!LegalOperations ||
9141          TLI.isOperationLegal(ISD::CTLZ, XType))) {
9142       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
9143       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9144                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
9145                                        getShiftAmountTy(Ctlz.getValueType())));
9146     }
9147     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9148     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9149       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
9150                                   XType, DAG.getConstant(0, XType), N0);
9151       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
9152       return DAG.getNode(ISD::SRL, DL, XType,
9153                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
9154                          DAG.getConstant(XType.getSizeInBits()-1,
9155                                          getShiftAmountTy(XType)));
9156     }
9157     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
9158     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
9159       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
9160                                  DAG.getConstant(XType.getSizeInBits()-1,
9161                                          getShiftAmountTy(N0.getValueType())));
9162       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
9163     }
9164   }
9165
9166   // Check to see if this is an integer abs.
9167   // select_cc setg[te] X,  0,  X, -X ->
9168   // select_cc setgt    X, -1,  X, -X ->
9169   // select_cc setl[te] X,  0, -X,  X ->
9170   // select_cc setlt    X,  1, -X,  X ->
9171   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9172   if (N1C) {
9173     ConstantSDNode *SubC = NULL;
9174     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
9175          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
9176         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
9177       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
9178     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
9179               (N1C->isOne() && CC == ISD::SETLT)) &&
9180              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
9181       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
9182
9183     EVT XType = N0.getValueType();
9184     if (SubC && SubC->isNullValue() && XType.isInteger()) {
9185       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
9186                                   N0,
9187                                   DAG.getConstant(XType.getSizeInBits()-1,
9188                                          getShiftAmountTy(N0.getValueType())));
9189       SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
9190                                 XType, N0, Shift);
9191       AddToWorkList(Shift.getNode());
9192       AddToWorkList(Add.getNode());
9193       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
9194     }
9195   }
9196
9197   return SDValue();
9198 }
9199
9200 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
9201 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
9202                                    SDValue N1, ISD::CondCode Cond,
9203                                    DebugLoc DL, bool foldBooleans) {
9204   TargetLowering::DAGCombinerInfo
9205     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
9206   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
9207 }
9208
9209 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
9210 /// return a DAG expression to select that will generate the same value by
9211 /// multiplying by a magic number.  See:
9212 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9213 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
9214   std::vector<SDNode*> Built;
9215   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
9216
9217   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9218        ii != ee; ++ii)
9219     AddToWorkList(*ii);
9220   return S;
9221 }
9222
9223 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
9224 /// return a DAG expression to select that will generate the same value by
9225 /// multiplying by a magic number.  See:
9226 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9227 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
9228   std::vector<SDNode*> Built;
9229   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
9230
9231   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9232        ii != ee; ++ii)
9233     AddToWorkList(*ii);
9234   return S;
9235 }
9236
9237 /// FindBaseOffset - Return true if base is a frame index, which is known not
9238 // to alias with anything but itself.  Provides base object and offset as
9239 // results.
9240 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
9241                            const GlobalValue *&GV, const void *&CV) {
9242   // Assume it is a primitive operation.
9243   Base = Ptr; Offset = 0; GV = 0; CV = 0;
9244
9245   // If it's an adding a simple constant then integrate the offset.
9246   if (Base.getOpcode() == ISD::ADD) {
9247     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
9248       Base = Base.getOperand(0);
9249       Offset += C->getZExtValue();
9250     }
9251   }
9252
9253   // Return the underlying GlobalValue, and update the Offset.  Return false
9254   // for GlobalAddressSDNode since the same GlobalAddress may be represented
9255   // by multiple nodes with different offsets.
9256   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
9257     GV = G->getGlobal();
9258     Offset += G->getOffset();
9259     return false;
9260   }
9261
9262   // Return the underlying Constant value, and update the Offset.  Return false
9263   // for ConstantSDNodes since the same constant pool entry may be represented
9264   // by multiple nodes with different offsets.
9265   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
9266     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
9267                                          : (const void *)C->getConstVal();
9268     Offset += C->getOffset();
9269     return false;
9270   }
9271   // If it's any of the following then it can't alias with anything but itself.
9272   return isa<FrameIndexSDNode>(Base);
9273 }
9274
9275 /// isAlias - Return true if there is any possibility that the two addresses
9276 /// overlap.
9277 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
9278                           const Value *SrcValue1, int SrcValueOffset1,
9279                           unsigned SrcValueAlign1,
9280                           const MDNode *TBAAInfo1,
9281                           SDValue Ptr2, int64_t Size2,
9282                           const Value *SrcValue2, int SrcValueOffset2,
9283                           unsigned SrcValueAlign2,
9284                           const MDNode *TBAAInfo2) const {
9285   // If they are the same then they must be aliases.
9286   if (Ptr1 == Ptr2) return true;
9287
9288   // Gather base node and offset information.
9289   SDValue Base1, Base2;
9290   int64_t Offset1, Offset2;
9291   const GlobalValue *GV1, *GV2;
9292   const void *CV1, *CV2;
9293   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
9294   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
9295
9296   // If they have a same base address then check to see if they overlap.
9297   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
9298     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
9299
9300   // It is possible for different frame indices to alias each other, mostly
9301   // when tail call optimization reuses return address slots for arguments.
9302   // To catch this case, look up the actual index of frame indices to compute
9303   // the real alias relationship.
9304   if (isFrameIndex1 && isFrameIndex2) {
9305     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9306     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
9307     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
9308     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
9309   }
9310
9311   // Otherwise, if we know what the bases are, and they aren't identical, then
9312   // we know they cannot alias.
9313   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
9314     return false;
9315
9316   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
9317   // compared to the size and offset of the access, we may be able to prove they
9318   // do not alias.  This check is conservative for now to catch cases created by
9319   // splitting vector types.
9320   if ((SrcValueAlign1 == SrcValueAlign2) &&
9321       (SrcValueOffset1 != SrcValueOffset2) &&
9322       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
9323     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
9324     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
9325
9326     // There is no overlap between these relatively aligned accesses of similar
9327     // size, return no alias.
9328     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
9329       return false;
9330   }
9331
9332   if (CombinerGlobalAA) {
9333     // Use alias analysis information.
9334     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
9335     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
9336     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
9337     AliasAnalysis::AliasResult AAResult =
9338       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
9339                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
9340     if (AAResult == AliasAnalysis::NoAlias)
9341       return false;
9342   }
9343
9344   // Otherwise we have to assume they alias.
9345   return true;
9346 }
9347
9348 /// FindAliasInfo - Extracts the relevant alias information from the memory
9349 /// node.  Returns true if the operand was a load.
9350 bool DAGCombiner::FindAliasInfo(SDNode *N,
9351                                 SDValue &Ptr, int64_t &Size,
9352                                 const Value *&SrcValue,
9353                                 int &SrcValueOffset,
9354                                 unsigned &SrcValueAlign,
9355                                 const MDNode *&TBAAInfo) const {
9356   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
9357
9358   Ptr = LS->getBasePtr();
9359   Size = LS->getMemoryVT().getSizeInBits() >> 3;
9360   SrcValue = LS->getSrcValue();
9361   SrcValueOffset = LS->getSrcValueOffset();
9362   SrcValueAlign = LS->getOriginalAlignment();
9363   TBAAInfo = LS->getTBAAInfo();
9364   return isa<LoadSDNode>(LS);
9365 }
9366
9367 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
9368 /// looking for aliasing nodes and adding them to the Aliases vector.
9369 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
9370                                    SmallVector<SDValue, 8> &Aliases) {
9371   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
9372   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
9373
9374   // Get alias information for node.
9375   SDValue Ptr;
9376   int64_t Size;
9377   const Value *SrcValue;
9378   int SrcValueOffset;
9379   unsigned SrcValueAlign;
9380   const MDNode *SrcTBAAInfo;
9381   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
9382                               SrcValueAlign, SrcTBAAInfo);
9383
9384   // Starting off.
9385   Chains.push_back(OriginalChain);
9386   unsigned Depth = 0;
9387
9388   // Look at each chain and determine if it is an alias.  If so, add it to the
9389   // aliases list.  If not, then continue up the chain looking for the next
9390   // candidate.
9391   while (!Chains.empty()) {
9392     SDValue Chain = Chains.back();
9393     Chains.pop_back();
9394
9395     // For TokenFactor nodes, look at each operand and only continue up the
9396     // chain until we find two aliases.  If we've seen two aliases, assume we'll
9397     // find more and revert to original chain since the xform is unlikely to be
9398     // profitable.
9399     //
9400     // FIXME: The depth check could be made to return the last non-aliasing
9401     // chain we found before we hit a tokenfactor rather than the original
9402     // chain.
9403     if (Depth > 6 || Aliases.size() == 2) {
9404       Aliases.clear();
9405       Aliases.push_back(OriginalChain);
9406       break;
9407     }
9408
9409     // Don't bother if we've been before.
9410     if (!Visited.insert(Chain.getNode()))
9411       continue;
9412
9413     switch (Chain.getOpcode()) {
9414     case ISD::EntryToken:
9415       // Entry token is ideal chain operand, but handled in FindBetterChain.
9416       break;
9417
9418     case ISD::LOAD:
9419     case ISD::STORE: {
9420       // Get alias information for Chain.
9421       SDValue OpPtr;
9422       int64_t OpSize;
9423       const Value *OpSrcValue;
9424       int OpSrcValueOffset;
9425       unsigned OpSrcValueAlign;
9426       const MDNode *OpSrcTBAAInfo;
9427       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
9428                                     OpSrcValue, OpSrcValueOffset,
9429                                     OpSrcValueAlign,
9430                                     OpSrcTBAAInfo);
9431
9432       // If chain is alias then stop here.
9433       if (!(IsLoad && IsOpLoad) &&
9434           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
9435                   SrcTBAAInfo,
9436                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
9437                   OpSrcValueAlign, OpSrcTBAAInfo)) {
9438         Aliases.push_back(Chain);
9439       } else {
9440         // Look further up the chain.
9441         Chains.push_back(Chain.getOperand(0));
9442         ++Depth;
9443       }
9444       break;
9445     }
9446
9447     case ISD::TokenFactor:
9448       // We have to check each of the operands of the token factor for "small"
9449       // token factors, so we queue them up.  Adding the operands to the queue
9450       // (stack) in reverse order maintains the original order and increases the
9451       // likelihood that getNode will find a matching token factor (CSE.)
9452       if (Chain.getNumOperands() > 16) {
9453         Aliases.push_back(Chain);
9454         break;
9455       }
9456       for (unsigned n = Chain.getNumOperands(); n;)
9457         Chains.push_back(Chain.getOperand(--n));
9458       ++Depth;
9459       break;
9460
9461     default:
9462       // For all other instructions we will just have to take what we can get.
9463       Aliases.push_back(Chain);
9464       break;
9465     }
9466   }
9467 }
9468
9469 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
9470 /// for a better chain (aliasing node.)
9471 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
9472   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
9473
9474   // Accumulate all the aliases to this node.
9475   GatherAllAliases(N, OldChain, Aliases);
9476
9477   // If no operands then chain to entry token.
9478   if (Aliases.size() == 0)
9479     return DAG.getEntryNode();
9480
9481   // If a single operand then chain to it.  We don't need to revisit it.
9482   if (Aliases.size() == 1)
9483     return Aliases[0];
9484
9485   // Construct a custom tailored token factor.
9486   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
9487                      &Aliases[0], Aliases.size());
9488 }
9489
9490 // SelectionDAG::Combine - This is the entry point for the file.
9491 //
9492 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
9493                            CodeGenOpt::Level OptLevel) {
9494   /// run - This is the main entry point to this class.
9495   ///
9496   DAGCombiner(*this, AA, OptLevel).Run(Level);
9497 }