Optimize ZERO_EXTEND and SIGN_EXTEND in both SelectionDAG Builder and type
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeIntegerTypes.cpp
1 //===----- LegalizeIntegerTypes.cpp - Legalization of integer types -------===//
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 file implements integer type expansion and promotion for LegalizeTypes.
11 // Promotion is the act of changing a computation in an illegal type into a
12 // computation in a larger type.  For example, implementing i8 arithmetic in an
13 // i32 register (often needed on powerpc).
14 // Expansion is the act of changing a computation in an illegal type into a
15 // computation in two identical registers of a smaller type.  For example,
16 // implementing i64 arithmetic in two i32 registers (often needed on 32-bit
17 // targets).
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "LegalizeTypes.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace llvm;
26
27 #define DEBUG_TYPE "legalize-types"
28
29 //===----------------------------------------------------------------------===//
30 //  Integer Result Promotion
31 //===----------------------------------------------------------------------===//
32
33 /// PromoteIntegerResult - This method is called when a result of a node is
34 /// found to be in need of promotion to a larger type.  At this point, the node
35 /// may also have invalid operands or may have other results that need
36 /// expansion, we just know that (at least) one result needs promotion.
37 void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
38   DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG); dbgs() << "\n");
39   SDValue Res = SDValue();
40
41   // See if the target wants to custom expand this node.
42   if (CustomLowerNode(N, N->getValueType(ResNo), true))
43     return;
44
45   switch (N->getOpcode()) {
46   default:
47 #ifndef NDEBUG
48     dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
49     N->dump(&DAG); dbgs() << "\n";
50 #endif
51     llvm_unreachable("Do not know how to promote this operator!");
52   case ISD::MERGE_VALUES:Res = PromoteIntRes_MERGE_VALUES(N, ResNo); break;
53   case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
54   case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
55   case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
56   case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
57   case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
58   case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
59   case ISD::CONVERT_RNDSAT:
60                          Res = PromoteIntRes_CONVERT_RNDSAT(N); break;
61   case ISD::CTLZ_ZERO_UNDEF:
62   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
63   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
64   case ISD::CTTZ_ZERO_UNDEF:
65   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
66   case ISD::EXTRACT_VECTOR_ELT:
67                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
68   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
69   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
70   case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
71   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
72   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
73   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
74   case ISD::SIGN_EXTEND_INREG:
75                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
76   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
77   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
78   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
79   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
80   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
81
82   case ISD::EXTRACT_SUBVECTOR:
83                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
84   case ISD::VECTOR_SHUFFLE:
85                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
86   case ISD::INSERT_VECTOR_ELT:
87                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
88   case ISD::BUILD_VECTOR:
89                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
90   case ISD::SCALAR_TO_VECTOR:
91                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
92   case ISD::CONCAT_VECTORS:
93                          Res = PromoteIntRes_CONCAT_VECTORS(N); break;
94
95   case ISD::SIGN_EXTEND:
96   case ISD::ZERO_EXTEND:
97   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
98
99   case ISD::FP_TO_SINT:
100   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
101
102   case ISD::FP_TO_FP16:  Res = PromoteIntRes_FP_TO_FP16(N); break;
103
104   case ISD::AND:
105   case ISD::OR:
106   case ISD::XOR:
107   case ISD::ADD:
108   case ISD::SUB:
109   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
110
111   case ISD::SDIV:
112   case ISD::SREM:        Res = PromoteIntRes_SDIV(N); break;
113
114   case ISD::UDIV:
115   case ISD::UREM:        Res = PromoteIntRes_UDIV(N); break;
116
117   case ISD::SADDO:
118   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
119   case ISD::UADDO:
120   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
121   case ISD::SMULO:
122   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
123
124   case ISD::ATOMIC_LOAD:
125     Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
126
127   case ISD::ATOMIC_LOAD_ADD:
128   case ISD::ATOMIC_LOAD_SUB:
129   case ISD::ATOMIC_LOAD_AND:
130   case ISD::ATOMIC_LOAD_OR:
131   case ISD::ATOMIC_LOAD_XOR:
132   case ISD::ATOMIC_LOAD_NAND:
133   case ISD::ATOMIC_LOAD_MIN:
134   case ISD::ATOMIC_LOAD_MAX:
135   case ISD::ATOMIC_LOAD_UMIN:
136   case ISD::ATOMIC_LOAD_UMAX:
137   case ISD::ATOMIC_SWAP:
138     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
139
140   case ISD::ATOMIC_CMP_SWAP:
141   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
142     Res = PromoteIntRes_AtomicCmpSwap(cast<AtomicSDNode>(N), ResNo);
143     break;
144   }
145
146   // If the result is null then the sub-method took care of registering it.
147   if (Res.getNode())
148     SetPromotedInteger(SDValue(N, ResNo), Res);
149 }
150
151 SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N,
152                                                      unsigned ResNo) {
153   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
154   return GetPromotedInteger(Op);
155 }
156
157 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
158   // Sign-extend the new bits, and continue the assertion.
159   SDValue Op = SExtPromotedInteger(N->getOperand(0));
160   return DAG.getNode(ISD::AssertSext, SDLoc(N),
161                      Op.getValueType(), Op, N->getOperand(1));
162 }
163
164 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
165   // Zero the new bits, and continue the assertion.
166   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
167   return DAG.getNode(ISD::AssertZext, SDLoc(N),
168                      Op.getValueType(), Op, N->getOperand(1));
169 }
170
171 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
172   EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
173   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
174                               N->getMemoryVT(), ResVT,
175                               N->getChain(), N->getBasePtr(),
176                               N->getMemOperand(), N->getOrdering(),
177                               N->getSynchScope());
178   // Legalized the chain result - switch anything that used the old chain to
179   // use the new one.
180   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
181   return Res;
182 }
183
184 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
185   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
186   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
187                               N->getMemoryVT(),
188                               N->getChain(), N->getBasePtr(),
189                               Op2, N->getMemOperand(), N->getOrdering(),
190                               N->getSynchScope());
191   // Legalized the chain result - switch anything that used the old chain to
192   // use the new one.
193   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
194   return Res;
195 }
196
197 SDValue DAGTypeLegalizer::PromoteIntRes_AtomicCmpSwap(AtomicSDNode *N,
198                                                       unsigned ResNo) {
199   if (ResNo == 1) {
200     assert(N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
201     EVT SVT = getSetCCResultType(N->getOperand(2).getValueType());
202     EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
203
204     // Only use the result of getSetCCResultType if it is legal,
205     // otherwise just use the promoted result type (NVT).
206     if (!TLI.isTypeLegal(SVT))
207       SVT = NVT;
208
209     SDVTList VTs = DAG.getVTList(N->getValueType(0), SVT, MVT::Other);
210     SDValue Res = DAG.getAtomicCmpSwap(
211         ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, SDLoc(N), N->getMemoryVT(), VTs,
212         N->getChain(), N->getBasePtr(), N->getOperand(2), N->getOperand(3),
213         N->getMemOperand(), N->getSuccessOrdering(), N->getFailureOrdering(),
214         N->getSynchScope());
215     ReplaceValueWith(SDValue(N, 0), Res.getValue(0));
216     ReplaceValueWith(SDValue(N, 2), Res.getValue(2));
217     return Res.getValue(1);
218   }
219
220   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
221   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
222   SDVTList VTs =
223       DAG.getVTList(Op2.getValueType(), N->getValueType(1), MVT::Other);
224   SDValue Res = DAG.getAtomicCmpSwap(
225       N->getOpcode(), SDLoc(N), N->getMemoryVT(), VTs, N->getChain(),
226       N->getBasePtr(), Op2, Op3, N->getMemOperand(), N->getSuccessOrdering(),
227       N->getFailureOrdering(), N->getSynchScope());
228   // Update the use to N with the newly created Res.
229   for (unsigned i = 1, NumResults = N->getNumValues(); i < NumResults; ++i)
230     ReplaceValueWith(SDValue(N, i), Res.getValue(i));
231   return Res;
232 }
233
234 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
235   SDValue InOp = N->getOperand(0);
236   EVT InVT = InOp.getValueType();
237   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
238   EVT OutVT = N->getValueType(0);
239   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
240   SDLoc dl(N);
241
242   switch (getTypeAction(InVT)) {
243   case TargetLowering::TypeLegal:
244     break;
245   case TargetLowering::TypePromoteInteger:
246     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector() && !NInVT.isVector())
247       // The input promotes to the same size.  Convert the promoted value.
248       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
249     break;
250   case TargetLowering::TypeSoftenFloat:
251     // Promote the integer operand by hand.
252     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
253   case TargetLowering::TypeExpandInteger:
254   case TargetLowering::TypeExpandFloat:
255     break;
256   case TargetLowering::TypeScalarizeVector:
257     // Convert the element to an integer and promote it by hand.
258     if (!NOutVT.isVector())
259       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
260                          BitConvertToInteger(GetScalarizedVector(InOp)));
261     break;
262   case TargetLowering::TypeSplitVector: {
263     // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
264     // pieces of the input into integers and reassemble in the final type.
265     SDValue Lo, Hi;
266     GetSplitVector(N->getOperand(0), Lo, Hi);
267     Lo = BitConvertToInteger(Lo);
268     Hi = BitConvertToInteger(Hi);
269
270     if (TLI.isBigEndian())
271       std::swap(Lo, Hi);
272
273     InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
274                        EVT::getIntegerVT(*DAG.getContext(),
275                                          NOutVT.getSizeInBits()),
276                        JoinIntegers(Lo, Hi));
277     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
278   }
279   case TargetLowering::TypeWidenVector:
280     // The input is widened to the same size. Convert to the widened value.
281     // Make sure that the outgoing value is not a vector, because this would
282     // make us bitcast between two vectors which are legalized in different ways.
283     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector())
284       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetWidenedVector(InOp));
285   }
286
287   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
288                      CreateStackStoreLoad(InOp, OutVT));
289 }
290
291 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
292   SDValue Op = GetPromotedInteger(N->getOperand(0));
293   EVT OVT = N->getValueType(0);
294   EVT NVT = Op.getValueType();
295   SDLoc dl(N);
296
297   unsigned DiffBits = NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits();
298   return DAG.getNode(ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
299                      DAG.getConstant(DiffBits, TLI.getShiftAmountTy(NVT)));
300 }
301
302 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
303   // The pair element type may be legal, or may not promote to the same type as
304   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
305   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N),
306                      TLI.getTypeToTransformTo(*DAG.getContext(),
307                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
308                      N->getOperand(1)));
309 }
310
311 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
312   EVT VT = N->getValueType(0);
313   // FIXME there is no actual debug info here
314   SDLoc dl(N);
315   // Zero extend things like i1, sign extend everything else.  It shouldn't
316   // matter in theory which one we pick, but this tends to give better code?
317   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
318   SDValue Result = DAG.getNode(Opc, dl,
319                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
320                                SDValue(N, 0));
321   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
322   return Result;
323 }
324
325 SDValue DAGTypeLegalizer::PromoteIntRes_CONVERT_RNDSAT(SDNode *N) {
326   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
327   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
328            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
329            CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
330           "can only promote integers");
331   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
332   return DAG.getConvertRndSat(OutVT, SDLoc(N), N->getOperand(0),
333                               N->getOperand(1), N->getOperand(2),
334                               N->getOperand(3), N->getOperand(4), CvtCode);
335 }
336
337 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
338   // Zero extend to the promoted type and do the count there.
339   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
340   SDLoc dl(N);
341   EVT OVT = N->getValueType(0);
342   EVT NVT = Op.getValueType();
343   Op = DAG.getNode(N->getOpcode(), dl, NVT, Op);
344   // Subtract off the extra leading bits in the bigger type.
345   return DAG.getNode(ISD::SUB, dl, NVT, Op,
346                      DAG.getConstant(NVT.getSizeInBits() -
347                                      OVT.getSizeInBits(), NVT));
348 }
349
350 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
351   // Zero extend to the promoted type and do the count there.
352   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
353   return DAG.getNode(ISD::CTPOP, SDLoc(N), Op.getValueType(), Op);
354 }
355
356 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
357   SDValue Op = GetPromotedInteger(N->getOperand(0));
358   EVT OVT = N->getValueType(0);
359   EVT NVT = Op.getValueType();
360   SDLoc dl(N);
361   if (N->getOpcode() == ISD::CTTZ) {
362     // The count is the same in the promoted type except if the original
363     // value was zero.  This can be handled by setting the bit just off
364     // the top of the original type.
365     APInt TopBit(NVT.getSizeInBits(), 0);
366     TopBit.setBit(OVT.getSizeInBits());
367     Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
368   }
369   return DAG.getNode(N->getOpcode(), dl, NVT, Op);
370 }
371
372 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
373   SDLoc dl(N);
374   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
375   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
376                      N->getOperand(1));
377 }
378
379 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
380   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
381   unsigned NewOpc = N->getOpcode();
382   SDLoc dl(N);
383
384   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
385   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
386   // and SINT conversions are Custom, there is no way to tell which is
387   // preferable. We choose SINT because that's the right thing on PPC.)
388   if (N->getOpcode() == ISD::FP_TO_UINT &&
389       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
390       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
391     NewOpc = ISD::FP_TO_SINT;
392
393   SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
394
395   // Assert that the converted value fits in the original type.  If it doesn't
396   // (eg: because the value being converted is too big), then the result of the
397   // original operation was undefined anyway, so the assert is still correct.
398   return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
399                      ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
400                      DAG.getValueType(N->getValueType(0).getScalarType()));
401 }
402
403 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_FP16(SDNode *N) {
404   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
405   SDLoc dl(N);
406
407   SDValue Res = DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
408
409   return DAG.getNode(ISD::AssertZext, dl,
410                      NVT, Res, DAG.getValueType(N->getValueType(0)));
411 }
412
413 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
414   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
415   SDLoc dl(N);
416
417   if (getTypeAction(N->getOperand(0).getValueType())
418       == TargetLowering::TypePromoteInteger) {
419     SDValue Res = GetPromotedInteger(N->getOperand(0));
420     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
421
422     // If the result and operand types are the same after promotion, simplify
423     // to an in-register extension.
424     if (NVT == Res.getValueType()) {
425       // The high bits are not guaranteed to be anything.  Insert an extend.
426       if (N->getOpcode() == ISD::SIGN_EXTEND)
427         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
428                            DAG.getValueType(N->getOperand(0).getValueType()));
429       if (N->getOpcode() == ISD::ZERO_EXTEND)
430         return DAG.getZeroExtendInReg(Res, dl,
431                       N->getOperand(0).getValueType().getScalarType());
432       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
433       return Res;
434     }
435   }
436
437   // Otherwise, just extend the original operand all the way to the larger type.
438   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
439 }
440
441 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
442   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
443   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
444   ISD::LoadExtType ExtType =
445     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
446   SDLoc dl(N);
447   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
448                                N->getMemoryVT(), N->getMemOperand());
449
450   // Legalized the chain result - switch anything that used the old chain to
451   // use the new one.
452   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
453   return Res;
454 }
455
456 /// Promote the overflow flag of an overflowing arithmetic node.
457 SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
458   // Simply change the return type of the boolean result.
459   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
460   EVT ValueVTs[] = { N->getValueType(0), NVT };
461   SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
462   SDValue Res = DAG.getNode(N->getOpcode(), SDLoc(N),
463                             DAG.getVTList(ValueVTs), Ops);
464
465   // Modified the sum result - switch anything that used the old sum to use
466   // the new one.
467   ReplaceValueWith(SDValue(N, 0), Res);
468
469   return SDValue(Res.getNode(), 1);
470 }
471
472 SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
473   if (ResNo == 1)
474     return PromoteIntRes_Overflow(N);
475
476   // The operation overflowed iff the result in the larger type is not the
477   // sign extension of its truncation to the original type.
478   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
479   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
480   EVT OVT = N->getOperand(0).getValueType();
481   EVT NVT = LHS.getValueType();
482   SDLoc dl(N);
483
484   // Do the arithmetic in the larger type.
485   unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
486   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
487
488   // Calculate the overflow flag: sign extend the arithmetic result from
489   // the original type.
490   SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
491                             DAG.getValueType(OVT));
492   // Overflowed if and only if this is not equal to Res.
493   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
494
495   // Use the calculated overflow everywhere.
496   ReplaceValueWith(SDValue(N, 1), Ofl);
497
498   return Res;
499 }
500
501 SDValue DAGTypeLegalizer::PromoteIntRes_SDIV(SDNode *N) {
502   // Sign extend the input.
503   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
504   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
505   return DAG.getNode(N->getOpcode(), SDLoc(N),
506                      LHS.getValueType(), LHS, RHS);
507 }
508
509 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
510   SDValue LHS = GetPromotedInteger(N->getOperand(1));
511   SDValue RHS = GetPromotedInteger(N->getOperand(2));
512   return DAG.getSelect(SDLoc(N),
513                        LHS.getValueType(), N->getOperand(0), LHS, RHS);
514 }
515
516 SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
517   SDValue Mask = N->getOperand(0);
518   EVT OpTy = N->getOperand(1).getValueType();
519
520   // Promote all the way up to the canonical SetCC type.
521   Mask = PromoteTargetBoolean(Mask, OpTy);
522   SDValue LHS = GetPromotedInteger(N->getOperand(1));
523   SDValue RHS = GetPromotedInteger(N->getOperand(2));
524   return DAG.getNode(ISD::VSELECT, SDLoc(N),
525                      LHS.getValueType(), Mask, LHS, RHS);
526 }
527
528 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
529   SDValue LHS = GetPromotedInteger(N->getOperand(2));
530   SDValue RHS = GetPromotedInteger(N->getOperand(3));
531   return DAG.getNode(ISD::SELECT_CC, SDLoc(N),
532                      LHS.getValueType(), N->getOperand(0),
533                      N->getOperand(1), LHS, RHS, N->getOperand(4));
534 }
535
536 SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
537   EVT SVT = getSetCCResultType(N->getOperand(0).getValueType());
538
539   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
540
541   // Only use the result of getSetCCResultType if it is legal,
542   // otherwise just use the promoted result type (NVT).
543   if (!TLI.isTypeLegal(SVT))
544     SVT = NVT;
545
546   SDLoc dl(N);
547   assert(SVT.isVector() == N->getOperand(0).getValueType().isVector() &&
548          "Vector compare must return a vector result!");
549
550   SDValue LHS = N->getOperand(0);
551   SDValue RHS = N->getOperand(1);
552   if (LHS.getValueType() != RHS.getValueType()) {
553     if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger &&
554         !LHS.getValueType().isVector())
555       LHS = GetPromotedInteger(LHS);
556     if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger &&
557         !RHS.getValueType().isVector())
558       RHS = GetPromotedInteger(RHS);
559   }
560
561   // Get the SETCC result using the canonical SETCC type.
562   SDValue SetCC = DAG.getNode(N->getOpcode(), dl, SVT, LHS, RHS,
563                               N->getOperand(2));
564
565   assert(NVT.bitsLE(SVT) && "Integer type overpromoted?");
566   // Convert to the expected type.
567   return DAG.getNode(ISD::TRUNCATE, dl, NVT, SetCC);
568 }
569
570 SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
571   SDValue Res = GetPromotedInteger(N->getOperand(0));
572   SDValue Amt = N->getOperand(1);
573   Amt = Amt.getValueType().isVector() ? ZExtPromotedInteger(Amt) : Amt;
574   return DAG.getNode(ISD::SHL, SDLoc(N), Res.getValueType(), Res, Amt);
575 }
576
577 SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
578   SDValue Op = GetPromotedInteger(N->getOperand(0));
579   return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N),
580                      Op.getValueType(), Op, N->getOperand(1));
581 }
582
583 SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
584   // The input may have strange things in the top bits of the registers, but
585   // these operations don't care.  They may have weird bits going out, but
586   // that too is okay if they are integer operations.
587   SDValue LHS = GetPromotedInteger(N->getOperand(0));
588   SDValue RHS = GetPromotedInteger(N->getOperand(1));
589   return DAG.getNode(N->getOpcode(), SDLoc(N),
590                      LHS.getValueType(), LHS, RHS);
591 }
592
593 SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
594   // The input value must be properly sign extended.
595   SDValue Res = SExtPromotedInteger(N->getOperand(0));
596   SDValue Amt = N->getOperand(1);
597   Amt = Amt.getValueType().isVector() ? ZExtPromotedInteger(Amt) : Amt;
598   return DAG.getNode(ISD::SRA, SDLoc(N), Res.getValueType(), Res, Amt);
599 }
600
601 SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
602   // The input value must be properly zero extended.
603   SDValue Res = ZExtPromotedInteger(N->getOperand(0));
604   SDValue Amt = N->getOperand(1);
605   Amt = Amt.getValueType().isVector() ? ZExtPromotedInteger(Amt) : Amt;
606   return DAG.getNode(ISD::SRL, SDLoc(N), Res.getValueType(), Res, Amt);
607 }
608
609 SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
610   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
611   SDValue Res;
612   SDValue InOp = N->getOperand(0);
613   SDLoc dl(N);
614
615   switch (getTypeAction(InOp.getValueType())) {
616   default: llvm_unreachable("Unknown type action!");
617   case TargetLowering::TypeLegal:
618   case TargetLowering::TypeExpandInteger:
619     Res = InOp;
620     break;
621   case TargetLowering::TypePromoteInteger:
622     Res = GetPromotedInteger(InOp);
623     break;
624   case TargetLowering::TypeSplitVector:
625     EVT InVT = InOp.getValueType();
626     assert(InVT.isVector() && "Cannot split scalar types");
627     unsigned NumElts = InVT.getVectorNumElements();
628     assert(NumElts == NVT.getVectorNumElements() &&
629            "Dst and Src must have the same number of elements");
630     assert(isPowerOf2_32(NumElts) &&
631            "Promoted vector type must be a power of two");
632
633     SDValue EOp1, EOp2;
634     GetSplitVector(InOp, EOp1, EOp2);
635
636     EVT HalfNVT = EVT::getVectorVT(*DAG.getContext(), NVT.getScalarType(),
637                                    NumElts/2);
638     EOp1 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp1);
639     EOp2 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp2);
640
641     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, EOp1, EOp2);
642   }
643
644   // Truncate to NVT instead of VT
645   return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
646 }
647
648 SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
649   if (ResNo == 1)
650     return PromoteIntRes_Overflow(N);
651
652   // The operation overflowed iff the result in the larger type is not the
653   // zero extension of its truncation to the original type.
654   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
655   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
656   EVT OVT = N->getOperand(0).getValueType();
657   EVT NVT = LHS.getValueType();
658   SDLoc dl(N);
659
660   // Do the arithmetic in the larger type.
661   unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
662   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
663
664   // Calculate the overflow flag: zero extend the arithmetic result from
665   // the original type.
666   SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
667   // Overflowed if and only if this is not equal to Res.
668   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
669
670   // Use the calculated overflow everywhere.
671   ReplaceValueWith(SDValue(N, 1), Ofl);
672
673   return Res;
674 }
675
676 SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
677   // Promote the overflow bit trivially.
678   if (ResNo == 1)
679     return PromoteIntRes_Overflow(N);
680
681   SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
682   SDLoc DL(N);
683   EVT SmallVT = LHS.getValueType();
684
685   // To determine if the result overflowed in a larger type, we extend the
686   // input to the larger type, do the multiply (checking if it overflows),
687   // then also check the high bits of the result to see if overflow happened
688   // there.
689   if (N->getOpcode() == ISD::SMULO) {
690     LHS = SExtPromotedInteger(LHS);
691     RHS = SExtPromotedInteger(RHS);
692   } else {
693     LHS = ZExtPromotedInteger(LHS);
694     RHS = ZExtPromotedInteger(RHS);
695   }
696   SDVTList VTs = DAG.getVTList(LHS.getValueType(), N->getValueType(1));
697   SDValue Mul = DAG.getNode(N->getOpcode(), DL, VTs, LHS, RHS);
698
699   // Overflow occurred if it occurred in the larger type, or if the high part
700   // of the result does not zero/sign-extend the low part.  Check this second
701   // possibility first.
702   SDValue Overflow;
703   if (N->getOpcode() == ISD::UMULO) {
704     // Unsigned overflow occurred if the high part is non-zero.
705     SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
706                              DAG.getIntPtrConstant(SmallVT.getSizeInBits()));
707     Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
708                             DAG.getConstant(0, Hi.getValueType()), ISD::SETNE);
709   } else {
710     // Signed overflow occurred if the high part does not sign extend the low.
711     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
712                                Mul, DAG.getValueType(SmallVT));
713     Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
714   }
715
716   // The only other way for overflow to occur is if the multiplication in the
717   // larger type itself overflowed.
718   Overflow = DAG.getNode(ISD::OR, DL, N->getValueType(1), Overflow,
719                          SDValue(Mul.getNode(), 1));
720
721   // Use the calculated overflow everywhere.
722   ReplaceValueWith(SDValue(N, 1), Overflow);
723   return Mul;
724 }
725
726 SDValue DAGTypeLegalizer::PromoteIntRes_UDIV(SDNode *N) {
727   // Zero extend the input.
728   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
729   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
730   return DAG.getNode(N->getOpcode(), SDLoc(N),
731                      LHS.getValueType(), LHS, RHS);
732 }
733
734 SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
735   return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
736                                                N->getValueType(0)));
737 }
738
739 SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
740   SDValue Chain = N->getOperand(0); // Get the chain.
741   SDValue Ptr = N->getOperand(1); // Get the pointer.
742   EVT VT = N->getValueType(0);
743   SDLoc dl(N);
744
745   MVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
746   unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
747   // The argument is passed as NumRegs registers of type RegVT.
748
749   SmallVector<SDValue, 8> Parts(NumRegs);
750   for (unsigned i = 0; i < NumRegs; ++i) {
751     Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
752                             N->getConstantOperandVal(3));
753     Chain = Parts[i].getValue(1);
754   }
755
756   // Handle endianness of the load.
757   if (TLI.isBigEndian())
758     std::reverse(Parts.begin(), Parts.end());
759
760   // Assemble the parts in the promoted type.
761   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
762   SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
763   for (unsigned i = 1; i < NumRegs; ++i) {
764     SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
765     // Shift it to the right position and "or" it in.
766     Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
767                        DAG.getConstant(i * RegVT.getSizeInBits(),
768                                        TLI.getPointerTy()));
769     Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
770   }
771
772   // Modified the chain result - switch anything that used the old chain to
773   // use the new one.
774   ReplaceValueWith(SDValue(N, 1), Chain);
775
776   return Res;
777 }
778
779 //===----------------------------------------------------------------------===//
780 //  Integer Operand Promotion
781 //===----------------------------------------------------------------------===//
782
783 /// PromoteIntegerOperand - This method is called when the specified operand of
784 /// the specified node is found to need promotion.  At this point, all of the
785 /// result types of the node are known to be legal, but other operands of the
786 /// node may need promotion or expansion as well as the specified one.
787 bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
788   DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG); dbgs() << "\n");
789   SDValue Res = SDValue();
790
791   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
792     return false;
793
794   switch (N->getOpcode()) {
795     default:
796   #ifndef NDEBUG
797     dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
798     N->dump(&DAG); dbgs() << "\n";
799   #endif
800     llvm_unreachable("Do not know how to promote this operator's operand!");
801
802   case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
803   case ISD::ATOMIC_STORE:
804     Res = PromoteIntOp_ATOMIC_STORE(cast<AtomicSDNode>(N));
805     break;
806   case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
807   case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
808   case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
809   case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
810   case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
811   case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
812   case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
813   case ISD::CONVERT_RNDSAT:
814                           Res = PromoteIntOp_CONVERT_RNDSAT(N); break;
815   case ISD::INSERT_VECTOR_ELT:
816                           Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
817   case ISD::SCALAR_TO_VECTOR:
818                           Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
819   case ISD::VSELECT:
820   case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
821   case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
822   case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
823   case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
824   case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
825   case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
826                                                    OpNo); break;
827   case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
828   case ISD::FP16_TO_FP:
829   case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
830   case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
831
832   case ISD::SHL:
833   case ISD::SRA:
834   case ISD::SRL:
835   case ISD::ROTL:
836   case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
837   }
838
839   // If the result is null, the sub-method took care of registering results etc.
840   if (!Res.getNode()) return false;
841
842   // If the result is N, the sub-method updated N in place.  Tell the legalizer
843   // core about this.
844   if (Res.getNode() == N)
845     return true;
846
847   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
848          "Invalid operand expansion");
849
850   ReplaceValueWith(SDValue(N, 0), Res);
851   return false;
852 }
853
854 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
855 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
856 void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
857                                             ISD::CondCode CCCode) {
858   // We have to insert explicit sign or zero extends.  Note that we could
859   // insert sign extends for ALL conditions, but zero extend is cheaper on
860   // many machines (an AND instead of two shifts), so prefer it.
861   switch (CCCode) {
862   default: llvm_unreachable("Unknown integer comparison!");
863   case ISD::SETEQ:
864   case ISD::SETNE: {
865     SDValue OpL, OpR;
866
867     OpL = GetPromotedInteger(NewLHS);
868     OpR = GetPromotedInteger(NewRHS);
869
870     // We would prefer to promote the comparison operand with sign extension,
871     // if we find the operand is actually to truncate an AssertSext. With this
872     // optimization, we can avoid inserting real truncate instruction, which
873     // is redudant eventually.
874     if (OpL->getOpcode() == ISD::AssertSext &&
875         cast<VTSDNode>(OpL->getOperand(1))->getVT() == NewLHS.getValueType() &&
876         OpR->getOpcode() == ISD::AssertSext &&
877         cast<VTSDNode>(OpR->getOperand(1))->getVT() == NewRHS.getValueType()) {
878       NewLHS = OpL;
879       NewRHS = OpR;
880     } else {
881       NewLHS = ZExtPromotedInteger(NewLHS);
882       NewRHS = ZExtPromotedInteger(NewRHS);
883     }
884     break;
885   }
886   case ISD::SETUGE:
887   case ISD::SETUGT:
888   case ISD::SETULE:
889   case ISD::SETULT:
890     // ALL of these operations will work if we either sign or zero extend
891     // the operands (including the unsigned comparisons!).  Zero extend is
892     // usually a simpler/cheaper operation, so prefer it.
893     NewLHS = ZExtPromotedInteger(NewLHS);
894     NewRHS = ZExtPromotedInteger(NewRHS);
895     break;
896   case ISD::SETGE:
897   case ISD::SETGT:
898   case ISD::SETLT:
899   case ISD::SETLE:
900     NewLHS = SExtPromotedInteger(NewLHS);
901     NewRHS = SExtPromotedInteger(NewRHS);
902     break;
903   }
904 }
905
906 SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
907   SDValue Op = GetPromotedInteger(N->getOperand(0));
908   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), N->getValueType(0), Op);
909 }
910
911 SDValue DAGTypeLegalizer::PromoteIntOp_ATOMIC_STORE(AtomicSDNode *N) {
912   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
913   return DAG.getAtomic(N->getOpcode(), SDLoc(N), N->getMemoryVT(),
914                        N->getChain(), N->getBasePtr(), Op2, N->getMemOperand(),
915                        N->getOrdering(), N->getSynchScope());
916 }
917
918 SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
919   // This should only occur in unusual situations like bitcasting to an
920   // x86_fp80, so just turn it into a store+load
921   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
922 }
923
924 SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
925   assert(OpNo == 2 && "Don't know how to promote this operand!");
926
927   SDValue LHS = N->getOperand(2);
928   SDValue RHS = N->getOperand(3);
929   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
930
931   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
932   // legal types.
933   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
934                                 N->getOperand(1), LHS, RHS, N->getOperand(4)),
935                  0);
936 }
937
938 SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
939   assert(OpNo == 1 && "only know how to promote condition");
940
941   // Promote all the way up to the canonical SetCC type.
942   SDValue Cond = PromoteTargetBoolean(N->getOperand(1), MVT::Other);
943
944   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
945   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
946                                         N->getOperand(2)), 0);
947 }
948
949 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
950   // Since the result type is legal, the operands must promote to it.
951   EVT OVT = N->getOperand(0).getValueType();
952   SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
953   SDValue Hi = GetPromotedInteger(N->getOperand(1));
954   assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
955   SDLoc dl(N);
956
957   Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
958                    DAG.getConstant(OVT.getSizeInBits(), TLI.getPointerTy()));
959   return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
960 }
961
962 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
963   // The vector type is legal but the element type is not.  This implies
964   // that the vector is a power-of-two in length and that the element
965   // type does not have a strange size (eg: it is not i1).
966   EVT VecVT = N->getValueType(0);
967   unsigned NumElts = VecVT.getVectorNumElements();
968   assert(!((NumElts & 1) && (!TLI.isTypeLegal(VecVT))) &&
969                  "Legal vector of one illegal element?");
970
971   // Promote the inserted value.  The type does not need to match the
972   // vector element type.  Check that any extra bits introduced will be
973   // truncated away.
974   assert(N->getOperand(0).getValueType().getSizeInBits() >=
975          N->getValueType(0).getVectorElementType().getSizeInBits() &&
976          "Type of inserted value narrower than vector element type!");
977
978   SmallVector<SDValue, 16> NewOps;
979   for (unsigned i = 0; i < NumElts; ++i)
980     NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
981
982   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
983 }
984
985 SDValue DAGTypeLegalizer::PromoteIntOp_CONVERT_RNDSAT(SDNode *N) {
986   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
987   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
988            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
989            CvtCode == ISD::CVT_FS || CvtCode == ISD::CVT_FU) &&
990            "can only promote integer arguments");
991   SDValue InOp = GetPromotedInteger(N->getOperand(0));
992   return DAG.getConvertRndSat(N->getValueType(0), SDLoc(N), InOp,
993                               N->getOperand(1), N->getOperand(2),
994                               N->getOperand(3), N->getOperand(4), CvtCode);
995 }
996
997 SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
998                                                          unsigned OpNo) {
999   if (OpNo == 1) {
1000     // Promote the inserted value.  This is valid because the type does not
1001     // have to match the vector element type.
1002
1003     // Check that any extra bits introduced will be truncated away.
1004     assert(N->getOperand(1).getValueType().getSizeInBits() >=
1005            N->getValueType(0).getVectorElementType().getSizeInBits() &&
1006            "Type of inserted value narrower than vector element type!");
1007     return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1008                                   GetPromotedInteger(N->getOperand(1)),
1009                                   N->getOperand(2)),
1010                    0);
1011   }
1012
1013   assert(OpNo == 2 && "Different operand and result vector types?");
1014
1015   // Promote the index.
1016   SDValue Idx = DAG.getZExtOrTrunc(N->getOperand(2), SDLoc(N),
1017                                    TLI.getVectorIdxTy());
1018   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1019                                 N->getOperand(1), Idx), 0);
1020 }
1021
1022 SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
1023   // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
1024   // the operand in place.
1025   return SDValue(DAG.UpdateNodeOperands(N,
1026                                 GetPromotedInteger(N->getOperand(0))), 0);
1027 }
1028
1029 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
1030   assert(OpNo == 0 && "Only know how to promote the condition!");
1031   SDValue Cond = N->getOperand(0);
1032   EVT OpTy = N->getOperand(1).getValueType();
1033
1034   // Promote all the way up to the canonical SetCC type.
1035   EVT OpVT = N->getOpcode() == ISD::SELECT ? OpTy.getScalarType() : OpTy;
1036   Cond = PromoteTargetBoolean(Cond, OpVT);
1037
1038   return SDValue(DAG.UpdateNodeOperands(N, Cond, N->getOperand(1),
1039                                         N->getOperand(2)), 0);
1040 }
1041
1042 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
1043   assert(OpNo == 0 && "Don't know how to promote this operand!");
1044
1045   SDValue LHS = N->getOperand(0);
1046   SDValue RHS = N->getOperand(1);
1047   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
1048
1049   // The CC (#4) and the possible return values (#2 and #3) have legal types.
1050   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2),
1051                                 N->getOperand(3), N->getOperand(4)), 0);
1052 }
1053
1054 SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
1055   assert(OpNo == 0 && "Don't know how to promote this operand!");
1056
1057   SDValue LHS = N->getOperand(0);
1058   SDValue RHS = N->getOperand(1);
1059   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
1060
1061   // The CC (#2) is always legal.
1062   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2)), 0);
1063 }
1064
1065 SDValue DAGTypeLegalizer::PromoteIntOp_Shift(SDNode *N) {
1066   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1067                                 ZExtPromotedInteger(N->getOperand(1))), 0);
1068 }
1069
1070 SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
1071   SDValue Op = GetPromotedInteger(N->getOperand(0));
1072   SDLoc dl(N);
1073   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1074   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(),
1075                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1076 }
1077
1078 SDValue DAGTypeLegalizer::PromoteIntOp_SINT_TO_FP(SDNode *N) {
1079   return SDValue(DAG.UpdateNodeOperands(N,
1080                                 SExtPromotedInteger(N->getOperand(0))), 0);
1081 }
1082
1083 SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
1084   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
1085   SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
1086   SDLoc dl(N);
1087
1088   SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
1089
1090   // Truncate the value and store the result.
1091   return DAG.getTruncStore(Ch, dl, Val, Ptr,
1092                            N->getMemoryVT(), N->getMemOperand());
1093 }
1094
1095 SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
1096   SDValue Op = GetPromotedInteger(N->getOperand(0));
1097   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), Op);
1098 }
1099
1100 SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
1101   return SDValue(DAG.UpdateNodeOperands(N,
1102                                 ZExtPromotedInteger(N->getOperand(0))), 0);
1103 }
1104
1105 SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
1106   SDLoc dl(N);
1107   SDValue Op = GetPromotedInteger(N->getOperand(0));
1108   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1109   return DAG.getZeroExtendInReg(Op, dl,
1110                                 N->getOperand(0).getValueType().getScalarType());
1111 }
1112
1113
1114 //===----------------------------------------------------------------------===//
1115 //  Integer Result Expansion
1116 //===----------------------------------------------------------------------===//
1117
1118 /// ExpandIntegerResult - This method is called when the specified result of the
1119 /// specified node is found to need expansion.  At this point, the node may also
1120 /// have invalid operands or may have other results that need promotion, we just
1121 /// know that (at least) one result needs expansion.
1122 void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
1123   DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG); dbgs() << "\n");
1124   SDValue Lo, Hi;
1125   Lo = Hi = SDValue();
1126
1127   // See if the target wants to custom expand this node.
1128   if (CustomLowerNode(N, N->getValueType(ResNo), true))
1129     return;
1130
1131   switch (N->getOpcode()) {
1132   default:
1133 #ifndef NDEBUG
1134     dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1135     N->dump(&DAG); dbgs() << "\n";
1136 #endif
1137     llvm_unreachable("Do not know how to expand the result of this operator!");
1138
1139   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
1140   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1141   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1142   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1143
1144   case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1145   case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1146   case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1147   case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1148   case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1149
1150   case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1151   case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1152   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1153   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1154   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1155   case ISD::CTLZ_ZERO_UNDEF:
1156   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1157   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1158   case ISD::CTTZ_ZERO_UNDEF:
1159   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1160   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1161   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1162   case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1163   case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1164   case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1165   case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1166   case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1167   case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1168   case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1169   case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1170   case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1171   case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1172   case ISD::ATOMIC_LOAD: ExpandIntRes_ATOMIC_LOAD(N, Lo, Hi); break;
1173
1174   case ISD::ATOMIC_LOAD_ADD:
1175   case ISD::ATOMIC_LOAD_SUB:
1176   case ISD::ATOMIC_LOAD_AND:
1177   case ISD::ATOMIC_LOAD_OR:
1178   case ISD::ATOMIC_LOAD_XOR:
1179   case ISD::ATOMIC_LOAD_NAND:
1180   case ISD::ATOMIC_LOAD_MIN:
1181   case ISD::ATOMIC_LOAD_MAX:
1182   case ISD::ATOMIC_LOAD_UMIN:
1183   case ISD::ATOMIC_LOAD_UMAX:
1184   case ISD::ATOMIC_SWAP:
1185   case ISD::ATOMIC_CMP_SWAP: {
1186     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1187     SplitInteger(Tmp.first, Lo, Hi);
1188     ReplaceValueWith(SDValue(N, 1), Tmp.second);
1189     break;
1190   }
1191   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
1192     AtomicSDNode *AN = cast<AtomicSDNode>(N);
1193     SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::Other);
1194     SDValue Tmp = DAG.getAtomicCmpSwap(
1195         ISD::ATOMIC_CMP_SWAP, SDLoc(N), AN->getMemoryVT(), VTs,
1196         N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3),
1197         AN->getMemOperand(), AN->getSuccessOrdering(), AN->getFailureOrdering(),
1198         AN->getSynchScope());
1199
1200     // Expanding to the strong ATOMIC_CMP_SWAP node means we can determine
1201     // success simply by comparing the loaded value against the ingoing
1202     // comparison.
1203     SDValue Success = DAG.getSetCC(SDLoc(N), N->getValueType(1), Tmp,
1204                                    N->getOperand(2), ISD::SETEQ);
1205
1206     SplitInteger(Tmp, Lo, Hi);
1207     ReplaceValueWith(SDValue(N, 1), Success);
1208     ReplaceValueWith(SDValue(N, 2), Tmp.getValue(1));
1209     break;
1210   }
1211
1212   case ISD::AND:
1213   case ISD::OR:
1214   case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1215
1216   case ISD::ADD:
1217   case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
1218
1219   case ISD::ADDC:
1220   case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
1221
1222   case ISD::ADDE:
1223   case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
1224
1225   case ISD::SHL:
1226   case ISD::SRA:
1227   case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1228
1229   case ISD::SADDO:
1230   case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
1231   case ISD::UADDO:
1232   case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
1233   case ISD::UMULO:
1234   case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
1235   }
1236
1237   // If Lo/Hi is null, the sub-method took care of registering results etc.
1238   if (Lo.getNode())
1239     SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1240 }
1241
1242 /// Lower an atomic node to the appropriate builtin call.
1243 std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
1244   unsigned Opc = Node->getOpcode();
1245   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
1246   RTLIB::Libcall LC;
1247
1248   switch (Opc) {
1249   default:
1250     llvm_unreachable("Unhandled atomic intrinsic Expand!");
1251   case ISD::ATOMIC_SWAP:
1252     switch (VT.SimpleTy) {
1253     default: llvm_unreachable("Unexpected value type for atomic!");
1254     case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
1255     case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
1256     case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
1257     case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
1258     case MVT::i128:LC = RTLIB::SYNC_LOCK_TEST_AND_SET_16;break;
1259     }
1260     break;
1261   case ISD::ATOMIC_CMP_SWAP:
1262     switch (VT.SimpleTy) {
1263     default: llvm_unreachable("Unexpected value type for atomic!");
1264     case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
1265     case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
1266     case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
1267     case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
1268     case MVT::i128:LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_16;break;
1269     }
1270     break;
1271   case ISD::ATOMIC_LOAD_ADD:
1272     switch (VT.SimpleTy) {
1273     default: llvm_unreachable("Unexpected value type for atomic!");
1274     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
1275     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
1276     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
1277     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
1278     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_ADD_16;break;
1279     }
1280     break;
1281   case ISD::ATOMIC_LOAD_SUB:
1282     switch (VT.SimpleTy) {
1283     default: llvm_unreachable("Unexpected value type for atomic!");
1284     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
1285     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
1286     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
1287     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
1288     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_SUB_16;break;
1289     }
1290     break;
1291   case ISD::ATOMIC_LOAD_AND:
1292     switch (VT.SimpleTy) {
1293     default: llvm_unreachable("Unexpected value type for atomic!");
1294     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
1295     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
1296     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
1297     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
1298     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_AND_16;break;
1299     }
1300     break;
1301   case ISD::ATOMIC_LOAD_OR:
1302     switch (VT.SimpleTy) {
1303     default: llvm_unreachable("Unexpected value type for atomic!");
1304     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
1305     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
1306     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
1307     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
1308     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_OR_16;break;
1309     }
1310     break;
1311   case ISD::ATOMIC_LOAD_XOR:
1312     switch (VT.SimpleTy) {
1313     default: llvm_unreachable("Unexpected value type for atomic!");
1314     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
1315     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
1316     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
1317     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
1318     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_XOR_16;break;
1319     }
1320     break;
1321   case ISD::ATOMIC_LOAD_NAND:
1322     switch (VT.SimpleTy) {
1323     default: llvm_unreachable("Unexpected value type for atomic!");
1324     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
1325     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
1326     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
1327     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
1328     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_NAND_16;break;
1329     }
1330     break;
1331   }
1332
1333   return ExpandChainLibCall(LC, Node, false);
1334 }
1335
1336 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1337 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1338 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt,
1339                                              SDValue &Lo, SDValue &Hi) {
1340   assert(Amt && "Expected zero shifts to be already optimized away.");
1341   SDLoc DL(N);
1342   // Expand the incoming operand to be shifted, so that we have its parts
1343   SDValue InL, InH;
1344   GetExpandedInteger(N->getOperand(0), InL, InH);
1345
1346   EVT NVT = InL.getValueType();
1347   unsigned VTBits = N->getValueType(0).getSizeInBits();
1348   unsigned NVTBits = NVT.getSizeInBits();
1349   EVT ShTy = N->getOperand(1).getValueType();
1350
1351   if (N->getOpcode() == ISD::SHL) {
1352     if (Amt > VTBits) {
1353       Lo = Hi = DAG.getConstant(0, NVT);
1354     } else if (Amt > NVTBits) {
1355       Lo = DAG.getConstant(0, NVT);
1356       Hi = DAG.getNode(ISD::SHL, DL,
1357                        NVT, InL, DAG.getConstant(Amt-NVTBits, ShTy));
1358     } else if (Amt == NVTBits) {
1359       Lo = DAG.getConstant(0, NVT);
1360       Hi = InL;
1361     } else if (Amt == 1 &&
1362                TLI.isOperationLegalOrCustom(ISD::ADDC,
1363                               TLI.getTypeToExpandTo(*DAG.getContext(), NVT))) {
1364       // Emit this X << 1 as X+X.
1365       SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1366       SDValue LoOps[2] = { InL, InL };
1367       Lo = DAG.getNode(ISD::ADDC, DL, VTList, LoOps);
1368       SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1369       Hi = DAG.getNode(ISD::ADDE, DL, VTList, HiOps);
1370     } else {
1371       Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, ShTy));
1372       Hi = DAG.getNode(ISD::OR, DL, NVT,
1373                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1374                                    DAG.getConstant(Amt, ShTy)),
1375                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1376                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1377     }
1378     return;
1379   }
1380
1381   if (N->getOpcode() == ISD::SRL) {
1382     if (Amt > VTBits) {
1383       Lo = DAG.getConstant(0, NVT);
1384       Hi = DAG.getConstant(0, NVT);
1385     } else if (Amt > NVTBits) {
1386       Lo = DAG.getNode(ISD::SRL, DL,
1387                        NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1388       Hi = DAG.getConstant(0, NVT);
1389     } else if (Amt == NVTBits) {
1390       Lo = InH;
1391       Hi = DAG.getConstant(0, NVT);
1392     } else {
1393       Lo = DAG.getNode(ISD::OR, DL, NVT,
1394                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1395                                    DAG.getConstant(Amt, ShTy)),
1396                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1397                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1398       Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1399     }
1400     return;
1401   }
1402
1403   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1404   if (Amt > VTBits) {
1405     Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1406                           DAG.getConstant(NVTBits-1, ShTy));
1407   } else if (Amt > NVTBits) {
1408     Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1409                      DAG.getConstant(Amt-NVTBits, ShTy));
1410     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1411                      DAG.getConstant(NVTBits-1, ShTy));
1412   } else if (Amt == NVTBits) {
1413     Lo = InH;
1414     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1415                      DAG.getConstant(NVTBits-1, ShTy));
1416   } else {
1417     Lo = DAG.getNode(ISD::OR, DL, NVT,
1418                      DAG.getNode(ISD::SRL, DL, NVT, InL,
1419                                  DAG.getConstant(Amt, ShTy)),
1420                      DAG.getNode(ISD::SHL, DL, NVT, InH,
1421                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1422     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1423   }
1424 }
1425
1426 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1427 /// this shift based on knowledge of the high bit of the shift amount.  If we
1428 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1429 /// shift amount.
1430 bool DAGTypeLegalizer::
1431 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1432   SDValue Amt = N->getOperand(1);
1433   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1434   EVT ShTy = Amt.getValueType();
1435   unsigned ShBits = ShTy.getScalarType().getSizeInBits();
1436   unsigned NVTBits = NVT.getScalarType().getSizeInBits();
1437   assert(isPowerOf2_32(NVTBits) &&
1438          "Expanded integer type size not a power of two!");
1439   SDLoc dl(N);
1440
1441   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1442   APInt KnownZero, KnownOne;
1443   DAG.computeKnownBits(N->getOperand(1), KnownZero, KnownOne);
1444
1445   // If we don't know anything about the high bits, exit.
1446   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1447     return false;
1448
1449   // Get the incoming operand to be shifted.
1450   SDValue InL, InH;
1451   GetExpandedInteger(N->getOperand(0), InL, InH);
1452
1453   // If we know that any of the high bits of the shift amount are one, then we
1454   // can do this as a couple of simple shifts.
1455   if (KnownOne.intersects(HighBitMask)) {
1456     // Mask out the high bit, which we know is set.
1457     Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
1458                       DAG.getConstant(~HighBitMask, ShTy));
1459
1460     switch (N->getOpcode()) {
1461     default: llvm_unreachable("Unknown shift");
1462     case ISD::SHL:
1463       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1464       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
1465       return true;
1466     case ISD::SRL:
1467       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1468       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
1469       return true;
1470     case ISD::SRA:
1471       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
1472                        DAG.getConstant(NVTBits-1, ShTy));
1473       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
1474       return true;
1475     }
1476   }
1477
1478   // If we know that all of the high bits of the shift amount are zero, then we
1479   // can do this as a couple of simple shifts.
1480   if ((KnownZero & HighBitMask) == HighBitMask) {
1481     // Calculate 31-x. 31 is used instead of 32 to avoid creating an undefined
1482     // shift if x is zero.  We can use XOR here because x is known to be smaller
1483     // than 32.
1484     SDValue Amt2 = DAG.getNode(ISD::XOR, dl, ShTy, Amt,
1485                                DAG.getConstant(NVTBits-1, ShTy));
1486
1487     unsigned Op1, Op2;
1488     switch (N->getOpcode()) {
1489     default: llvm_unreachable("Unknown shift");
1490     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1491     case ISD::SRL:
1492     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1493     }
1494
1495     // When shifting right the arithmetic for Lo and Hi is swapped.
1496     if (N->getOpcode() != ISD::SHL)
1497       std::swap(InL, InH);
1498
1499     // Use a little trick to get the bits that move from Lo to Hi. First
1500     // shift by one bit.
1501     SDValue Sh1 = DAG.getNode(Op2, dl, NVT, InL, DAG.getConstant(1, ShTy));
1502     // Then compute the remaining shift with amount-1.
1503     SDValue Sh2 = DAG.getNode(Op2, dl, NVT, Sh1, Amt2);
1504
1505     Lo = DAG.getNode(N->getOpcode(), dl, NVT, InL, Amt);
1506     Hi = DAG.getNode(ISD::OR, dl, NVT, DAG.getNode(Op1, dl, NVT, InH, Amt),Sh2);
1507
1508     if (N->getOpcode() != ISD::SHL)
1509       std::swap(Hi, Lo);
1510     return true;
1511   }
1512
1513   return false;
1514 }
1515
1516 /// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
1517 /// of any size.
1518 bool DAGTypeLegalizer::
1519 ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1520   SDValue Amt = N->getOperand(1);
1521   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1522   EVT ShTy = Amt.getValueType();
1523   unsigned NVTBits = NVT.getSizeInBits();
1524   assert(isPowerOf2_32(NVTBits) &&
1525          "Expanded integer type size not a power of two!");
1526   SDLoc dl(N);
1527
1528   // Get the incoming operand to be shifted.
1529   SDValue InL, InH;
1530   GetExpandedInteger(N->getOperand(0), InL, InH);
1531
1532   SDValue NVBitsNode = DAG.getConstant(NVTBits, ShTy);
1533   SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
1534   SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
1535   SDValue isShort = DAG.getSetCC(dl, getSetCCResultType(ShTy),
1536                                  Amt, NVBitsNode, ISD::SETULT);
1537
1538   SDValue LoS, HiS, LoL, HiL;
1539   switch (N->getOpcode()) {
1540   default: llvm_unreachable("Unknown shift");
1541   case ISD::SHL:
1542     // Short: ShAmt < NVTBits
1543     LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
1544     HiS = DAG.getNode(ISD::OR, dl, NVT,
1545                       DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
1546     // FIXME: If Amt is zero, the following shift generates an undefined result
1547     // on some architectures.
1548                       DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
1549
1550     // Long: ShAmt >= NVTBits
1551     LoL = DAG.getConstant(0, NVT);                        // Lo part is zero.
1552     HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
1553
1554     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
1555     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1556     return true;
1557   case ISD::SRL:
1558     // Short: ShAmt < NVTBits
1559     HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
1560     LoS = DAG.getNode(ISD::OR, dl, NVT,
1561                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1562     // FIXME: If Amt is zero, the following shift generates an undefined result
1563     // on some architectures.
1564                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1565
1566     // Long: ShAmt >= NVTBits
1567     HiL = DAG.getConstant(0, NVT);                        // Hi part is zero.
1568     LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1569
1570     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
1571     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1572     return true;
1573   case ISD::SRA:
1574     // Short: ShAmt < NVTBits
1575     HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
1576     LoS = DAG.getNode(ISD::OR, dl, NVT,
1577                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1578     // FIXME: If Amt is zero, the following shift generates an undefined result
1579     // on some architectures.
1580                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1581
1582     // Long: ShAmt >= NVTBits
1583     HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
1584                       DAG.getConstant(NVTBits-1, ShTy));
1585     LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1586
1587     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
1588     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1589     return true;
1590   }
1591 }
1592
1593 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1594                                            SDValue &Lo, SDValue &Hi) {
1595   SDLoc dl(N);
1596   // Expand the subcomponents.
1597   SDValue LHSL, LHSH, RHSL, RHSH;
1598   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1599   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1600
1601   EVT NVT = LHSL.getValueType();
1602   SDValue LoOps[2] = { LHSL, RHSL };
1603   SDValue HiOps[3] = { LHSH, RHSH };
1604
1605   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1606   // them.  TODO: Teach operation legalization how to expand unsupported
1607   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1608   // a carry of type MVT::Glue, but there doesn't seem to be any way to
1609   // generate a value of this type in the expanded code sequence.
1610   bool hasCarry =
1611     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1612                                    ISD::ADDC : ISD::SUBC,
1613                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1614
1615   if (hasCarry) {
1616     SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1617     if (N->getOpcode() == ISD::ADD) {
1618       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
1619       HiOps[2] = Lo.getValue(1);
1620       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
1621     } else {
1622       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
1623       HiOps[2] = Lo.getValue(1);
1624       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
1625     }
1626     return;
1627   }
1628
1629   if (N->getOpcode() == ISD::ADD) {
1630     Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps);
1631     Hi = DAG.getNode(ISD::ADD, dl, NVT, makeArrayRef(HiOps, 2));
1632     SDValue Cmp1 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[0],
1633                                 ISD::SETULT);
1634     SDValue Carry1 = DAG.getSelect(dl, NVT, Cmp1,
1635                                    DAG.getConstant(1, NVT),
1636                                    DAG.getConstant(0, NVT));
1637     SDValue Cmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[1],
1638                                 ISD::SETULT);
1639     SDValue Carry2 = DAG.getSelect(dl, NVT, Cmp2,
1640                                    DAG.getConstant(1, NVT), Carry1);
1641     Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
1642   } else {
1643     Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps);
1644     Hi = DAG.getNode(ISD::SUB, dl, NVT, makeArrayRef(HiOps, 2));
1645     SDValue Cmp =
1646       DAG.getSetCC(dl, getSetCCResultType(LoOps[0].getValueType()),
1647                    LoOps[0], LoOps[1], ISD::SETULT);
1648     SDValue Borrow = DAG.getSelect(dl, NVT, Cmp,
1649                                    DAG.getConstant(1, NVT),
1650                                    DAG.getConstant(0, NVT));
1651     Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
1652   }
1653 }
1654
1655 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1656                                             SDValue &Lo, SDValue &Hi) {
1657   // Expand the subcomponents.
1658   SDValue LHSL, LHSH, RHSL, RHSH;
1659   SDLoc dl(N);
1660   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1661   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1662   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1663   SDValue LoOps[2] = { LHSL, RHSL };
1664   SDValue HiOps[3] = { LHSH, RHSH };
1665
1666   if (N->getOpcode() == ISD::ADDC) {
1667     Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
1668     HiOps[2] = Lo.getValue(1);
1669     Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
1670   } else {
1671     Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
1672     HiOps[2] = Lo.getValue(1);
1673     Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
1674   }
1675
1676   // Legalized the flag result - switch anything that used the old flag to
1677   // use the new one.
1678   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1679 }
1680
1681 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1682                                             SDValue &Lo, SDValue &Hi) {
1683   // Expand the subcomponents.
1684   SDValue LHSL, LHSH, RHSL, RHSH;
1685   SDLoc dl(N);
1686   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1687   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1688   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1689   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1690   SDValue HiOps[3] = { LHSH, RHSH };
1691
1692   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps);
1693   HiOps[2] = Lo.getValue(1);
1694   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps);
1695
1696   // Legalized the flag result - switch anything that used the old flag to
1697   // use the new one.
1698   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1699 }
1700
1701 void DAGTypeLegalizer::ExpandIntRes_MERGE_VALUES(SDNode *N, unsigned ResNo,
1702                                                  SDValue &Lo, SDValue &Hi) {
1703   SDValue Res = DisintegrateMERGE_VALUES(N, ResNo);
1704   SplitInteger(Res, Lo, Hi);
1705 }
1706
1707 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1708                                                SDValue &Lo, SDValue &Hi) {
1709   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1710   SDLoc dl(N);
1711   SDValue Op = N->getOperand(0);
1712   if (Op.getValueType().bitsLE(NVT)) {
1713     // The low part is any extension of the input (which degenerates to a copy).
1714     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
1715     Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
1716   } else {
1717     // For example, extension of an i48 to an i64.  The operand type necessarily
1718     // promotes to the result type, so will end up being expanded too.
1719     assert(getTypeAction(Op.getValueType()) ==
1720            TargetLowering::TypePromoteInteger &&
1721            "Only know how to promote this result!");
1722     SDValue Res = GetPromotedInteger(Op);
1723     assert(Res.getValueType() == N->getValueType(0) &&
1724            "Operand over promoted?");
1725     // Split the promoted operand.  This will simplify when it is expanded.
1726     SplitInteger(Res, Lo, Hi);
1727   }
1728 }
1729
1730 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1731                                                SDValue &Lo, SDValue &Hi) {
1732   SDLoc dl(N);
1733   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1734   EVT NVT = Lo.getValueType();
1735   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1736   unsigned NVTBits = NVT.getSizeInBits();
1737   unsigned EVTBits = EVT.getSizeInBits();
1738
1739   if (NVTBits < EVTBits) {
1740     Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
1741                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1742                                                         EVTBits - NVTBits)));
1743   } else {
1744     Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
1745     // The high part replicates the sign bit of Lo, make it explicit.
1746     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1747                      DAG.getConstant(NVTBits-1, TLI.getPointerTy()));
1748   }
1749 }
1750
1751 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1752                                                SDValue &Lo, SDValue &Hi) {
1753   SDLoc dl(N);
1754   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1755   EVT NVT = Lo.getValueType();
1756   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1757   unsigned NVTBits = NVT.getSizeInBits();
1758   unsigned EVTBits = EVT.getSizeInBits();
1759
1760   if (NVTBits < EVTBits) {
1761     Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
1762                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1763                                                         EVTBits - NVTBits)));
1764   } else {
1765     Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
1766     // The high part must be zero, make it explicit.
1767     Hi = DAG.getConstant(0, NVT);
1768   }
1769 }
1770
1771 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1772                                           SDValue &Lo, SDValue &Hi) {
1773   SDLoc dl(N);
1774   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1775   Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
1776   Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
1777 }
1778
1779 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1780                                              SDValue &Lo, SDValue &Hi) {
1781   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1782   unsigned NBitWidth = NVT.getSizeInBits();
1783   auto Constant = cast<ConstantSDNode>(N);
1784   const APInt &Cst = Constant->getAPIntValue();
1785   bool IsTarget = Constant->isTargetOpcode();
1786   bool IsOpaque = Constant->isOpaque();
1787   Lo = DAG.getConstant(Cst.trunc(NBitWidth), NVT, IsTarget, IsOpaque);
1788   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT, IsTarget,
1789                        IsOpaque);
1790 }
1791
1792 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1793                                          SDValue &Lo, SDValue &Hi) {
1794   SDLoc dl(N);
1795   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1796   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1797   EVT NVT = Lo.getValueType();
1798
1799   SDValue HiNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Hi,
1800                                    DAG.getConstant(0, NVT), ISD::SETNE);
1801
1802   SDValue LoLZ = DAG.getNode(N->getOpcode(), dl, NVT, Lo);
1803   SDValue HiLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, NVT, Hi);
1804
1805   Lo = DAG.getSelect(dl, NVT, HiNotZero, HiLZ,
1806                      DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
1807                                  DAG.getConstant(NVT.getSizeInBits(), NVT)));
1808   Hi = DAG.getConstant(0, NVT);
1809 }
1810
1811 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1812                                           SDValue &Lo, SDValue &Hi) {
1813   SDLoc dl(N);
1814   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1815   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1816   EVT NVT = Lo.getValueType();
1817   Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
1818                    DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
1819   Hi = DAG.getConstant(0, NVT);
1820 }
1821
1822 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1823                                          SDValue &Lo, SDValue &Hi) {
1824   SDLoc dl(N);
1825   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1826   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1827   EVT NVT = Lo.getValueType();
1828
1829   SDValue LoNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo,
1830                                    DAG.getConstant(0, NVT), ISD::SETNE);
1831
1832   SDValue LoLZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, NVT, Lo);
1833   SDValue HiLZ = DAG.getNode(N->getOpcode(), dl, NVT, Hi);
1834
1835   Lo = DAG.getSelect(dl, NVT, LoNotZero, LoLZ,
1836                      DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
1837                                  DAG.getConstant(NVT.getSizeInBits(), NVT)));
1838   Hi = DAG.getConstant(0, NVT);
1839 }
1840
1841 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1842                                                SDValue &Hi) {
1843   SDLoc dl(N);
1844   EVT VT = N->getValueType(0);
1845   SDValue Op = N->getOperand(0);
1846   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1847   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1848   SplitInteger(TLI.makeLibCall(DAG, LC, VT, &Op, 1, true/*irrelevant*/,
1849                                dl).first,
1850                Lo, Hi);
1851 }
1852
1853 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1854                                                SDValue &Hi) {
1855   SDLoc dl(N);
1856   EVT VT = N->getValueType(0);
1857   SDValue Op = N->getOperand(0);
1858   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1859   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1860   SplitInteger(TLI.makeLibCall(DAG, LC, VT, &Op, 1, false/*irrelevant*/,
1861                                dl).first,
1862                Lo, Hi);
1863 }
1864
1865 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1866                                          SDValue &Lo, SDValue &Hi) {
1867   if (ISD::isNormalLoad(N)) {
1868     ExpandRes_NormalLoad(N, Lo, Hi);
1869     return;
1870   }
1871
1872   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1873
1874   EVT VT = N->getValueType(0);
1875   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1876   SDValue Ch  = N->getChain();
1877   SDValue Ptr = N->getBasePtr();
1878   ISD::LoadExtType ExtType = N->getExtensionType();
1879   unsigned Alignment = N->getAlignment();
1880   bool isVolatile = N->isVolatile();
1881   bool isNonTemporal = N->isNonTemporal();
1882   bool isInvariant = N->isInvariant();
1883   AAMDNodes AAInfo = N->getAAInfo();
1884   SDLoc dl(N);
1885
1886   assert(NVT.isByteSized() && "Expanded type not byte sized!");
1887
1888   if (N->getMemoryVT().bitsLE(NVT)) {
1889     EVT MemVT = N->getMemoryVT();
1890
1891     Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1892                         MemVT, isVolatile, isNonTemporal, isInvariant,
1893                         Alignment, AAInfo);
1894
1895     // Remember the chain.
1896     Ch = Lo.getValue(1);
1897
1898     if (ExtType == ISD::SEXTLOAD) {
1899       // The high part is obtained by SRA'ing all but one of the bits of the
1900       // lo part.
1901       unsigned LoSize = Lo.getValueType().getSizeInBits();
1902       Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1903                        DAG.getConstant(LoSize-1, TLI.getPointerTy()));
1904     } else if (ExtType == ISD::ZEXTLOAD) {
1905       // The high part is just a zero.
1906       Hi = DAG.getConstant(0, NVT);
1907     } else {
1908       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1909       // The high part is undefined.
1910       Hi = DAG.getUNDEF(NVT);
1911     }
1912   } else if (TLI.isLittleEndian()) {
1913     // Little-endian - low bits are at low addresses.
1914     Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
1915                      isVolatile, isNonTemporal, isInvariant, Alignment,
1916                      AAInfo);
1917
1918     unsigned ExcessBits =
1919       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1920     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
1921
1922     // Increment the pointer to the other half.
1923     unsigned IncrementSize = NVT.getSizeInBits()/8;
1924     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1925                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
1926     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
1927                         N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
1928                         isVolatile, isNonTemporal, isInvariant,
1929                         MinAlign(Alignment, IncrementSize), AAInfo);
1930
1931     // Build a factor node to remember that this load is independent of the
1932     // other one.
1933     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1934                      Hi.getValue(1));
1935   } else {
1936     // Big-endian - high bits are at low addresses.  Favor aligned loads at
1937     // the cost of some bit-fiddling.
1938     EVT MemVT = N->getMemoryVT();
1939     unsigned EBytes = MemVT.getStoreSize();
1940     unsigned IncrementSize = NVT.getSizeInBits()/8;
1941     unsigned ExcessBits = (EBytes - IncrementSize)*8;
1942
1943     // Load both the high bits and maybe some of the low bits.
1944     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1945                         EVT::getIntegerVT(*DAG.getContext(),
1946                                           MemVT.getSizeInBits() - ExcessBits),
1947                         isVolatile, isNonTemporal, isInvariant, Alignment,
1948                         AAInfo);
1949
1950     // Increment the pointer to the other half.
1951     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1952                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
1953     // Load the rest of the low bits.
1954     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
1955                         N->getPointerInfo().getWithOffset(IncrementSize),
1956                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
1957                         isVolatile, isNonTemporal, isInvariant,
1958                         MinAlign(Alignment, IncrementSize), AAInfo);
1959
1960     // Build a factor node to remember that this load is independent of the
1961     // other one.
1962     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1963                      Hi.getValue(1));
1964
1965     if (ExcessBits < NVT.getSizeInBits()) {
1966       // Transfer low bits from the bottom of Hi to the top of Lo.
1967       Lo = DAG.getNode(ISD::OR, dl, NVT, Lo,
1968                        DAG.getNode(ISD::SHL, dl, NVT, Hi,
1969                                    DAG.getConstant(ExcessBits,
1970                                                    TLI.getPointerTy())));
1971       // Move high bits to the right position in Hi.
1972       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl,
1973                        NVT, Hi,
1974                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1975                                        TLI.getPointerTy()));
1976     }
1977   }
1978
1979   // Legalized the chain result - switch anything that used the old chain to
1980   // use the new one.
1981   ReplaceValueWith(SDValue(N, 1), Ch);
1982 }
1983
1984 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1985                                             SDValue &Lo, SDValue &Hi) {
1986   SDLoc dl(N);
1987   SDValue LL, LH, RL, RH;
1988   GetExpandedInteger(N->getOperand(0), LL, LH);
1989   GetExpandedInteger(N->getOperand(1), RL, RH);
1990   Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
1991   Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
1992 }
1993
1994 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1995                                         SDValue &Lo, SDValue &Hi) {
1996   EVT VT = N->getValueType(0);
1997   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1998   SDLoc dl(N);
1999
2000   SDValue LL, LH, RL, RH;
2001   GetExpandedInteger(N->getOperand(0), LL, LH);
2002   GetExpandedInteger(N->getOperand(1), RL, RH);
2003
2004   if (TLI.expandMUL(N, Lo, Hi, NVT, DAG, LL, LH, RL, RH))
2005     return;
2006
2007   // If nothing else, we can make a libcall.
2008   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2009   if (VT == MVT::i16)
2010     LC = RTLIB::MUL_I16;
2011   else if (VT == MVT::i32)
2012     LC = RTLIB::MUL_I32;
2013   else if (VT == MVT::i64)
2014     LC = RTLIB::MUL_I64;
2015   else if (VT == MVT::i128)
2016     LC = RTLIB::MUL_I128;
2017   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
2018
2019   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2020   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, true/*irrelevant*/,
2021                                dl).first,
2022                Lo, Hi);
2023 }
2024
2025 void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
2026                                              SDValue &Lo, SDValue &Hi) {
2027   SDValue LHS = Node->getOperand(0);
2028   SDValue RHS = Node->getOperand(1);
2029   SDLoc dl(Node);
2030
2031   // Expand the result by simply replacing it with the equivalent
2032   // non-overflow-checking operation.
2033   SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
2034                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2035                             LHS, RHS);
2036   SplitInteger(Sum, Lo, Hi);
2037
2038   // Compute the overflow.
2039   //
2040   //   LHSSign -> LHS >= 0
2041   //   RHSSign -> RHS >= 0
2042   //   SumSign -> Sum >= 0
2043   //
2044   //   Add:
2045   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
2046   //   Sub:
2047   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
2048   //
2049   EVT OType = Node->getValueType(1);
2050   SDValue Zero = DAG.getConstant(0, LHS.getValueType());
2051
2052   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2053   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2054   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2055                                     Node->getOpcode() == ISD::SADDO ?
2056                                     ISD::SETEQ : ISD::SETNE);
2057
2058   SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2059   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2060
2061   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2062
2063   // Use the calculated overflow everywhere.
2064   ReplaceValueWith(SDValue(Node, 1), Cmp);
2065 }
2066
2067 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
2068                                          SDValue &Lo, SDValue &Hi) {
2069   EVT VT = N->getValueType(0);
2070   SDLoc dl(N);
2071
2072   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2073   if (VT == MVT::i16)
2074     LC = RTLIB::SDIV_I16;
2075   else if (VT == MVT::i32)
2076     LC = RTLIB::SDIV_I32;
2077   else if (VT == MVT::i64)
2078     LC = RTLIB::SDIV_I64;
2079   else if (VT == MVT::i128)
2080     LC = RTLIB::SDIV_I128;
2081   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
2082
2083   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2084   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, true, dl).first, Lo, Hi);
2085 }
2086
2087 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
2088                                           SDValue &Lo, SDValue &Hi) {
2089   EVT VT = N->getValueType(0);
2090   SDLoc dl(N);
2091
2092   // If we can emit an efficient shift operation, do so now.  Check to see if
2093   // the RHS is a constant.
2094   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2095     return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
2096
2097   // If we can determine that the high bit of the shift is zero or one, even if
2098   // the low bits are variable, emit this shift in an optimized form.
2099   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
2100     return;
2101
2102   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
2103   unsigned PartsOpc;
2104   if (N->getOpcode() == ISD::SHL) {
2105     PartsOpc = ISD::SHL_PARTS;
2106   } else if (N->getOpcode() == ISD::SRL) {
2107     PartsOpc = ISD::SRL_PARTS;
2108   } else {
2109     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2110     PartsOpc = ISD::SRA_PARTS;
2111   }
2112
2113   // Next check to see if the target supports this SHL_PARTS operation or if it
2114   // will custom expand it.
2115   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2116   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
2117   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
2118       Action == TargetLowering::Custom) {
2119     // Expand the subcomponents.
2120     SDValue LHSL, LHSH;
2121     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2122     EVT VT = LHSL.getValueType();
2123
2124     // If the shift amount operand is coming from a vector legalization it may
2125     // have an illegal type.  Fix that first by casting the operand, otherwise
2126     // the new SHL_PARTS operation would need further legalization.
2127     SDValue ShiftOp = N->getOperand(1);
2128     EVT ShiftTy = TLI.getShiftAmountTy(VT);
2129     assert(ShiftTy.getScalarType().getSizeInBits() >=
2130            Log2_32_Ceil(VT.getScalarType().getSizeInBits()) &&
2131            "ShiftAmountTy is too small to cover the range of this type!");
2132     if (ShiftOp.getValueType() != ShiftTy)
2133       ShiftOp = DAG.getZExtOrTrunc(ShiftOp, dl, ShiftTy);
2134
2135     SDValue Ops[] = { LHSL, LHSH, ShiftOp };
2136     Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops);
2137     Hi = Lo.getValue(1);
2138     return;
2139   }
2140
2141   // Otherwise, emit a libcall.
2142   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2143   bool isSigned;
2144   if (N->getOpcode() == ISD::SHL) {
2145     isSigned = false; /*sign irrelevant*/
2146     if (VT == MVT::i16)
2147       LC = RTLIB::SHL_I16;
2148     else if (VT == MVT::i32)
2149       LC = RTLIB::SHL_I32;
2150     else if (VT == MVT::i64)
2151       LC = RTLIB::SHL_I64;
2152     else if (VT == MVT::i128)
2153       LC = RTLIB::SHL_I128;
2154   } else if (N->getOpcode() == ISD::SRL) {
2155     isSigned = false;
2156     if (VT == MVT::i16)
2157       LC = RTLIB::SRL_I16;
2158     else if (VT == MVT::i32)
2159       LC = RTLIB::SRL_I32;
2160     else if (VT == MVT::i64)
2161       LC = RTLIB::SRL_I64;
2162     else if (VT == MVT::i128)
2163       LC = RTLIB::SRL_I128;
2164   } else {
2165     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2166     isSigned = true;
2167     if (VT == MVT::i16)
2168       LC = RTLIB::SRA_I16;
2169     else if (VT == MVT::i32)
2170       LC = RTLIB::SRA_I32;
2171     else if (VT == MVT::i64)
2172       LC = RTLIB::SRA_I64;
2173     else if (VT == MVT::i128)
2174       LC = RTLIB::SRA_I128;
2175   }
2176
2177   if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
2178     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2179     SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, isSigned, dl).first, Lo,
2180                  Hi);
2181     return;
2182   }
2183
2184   if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
2185     llvm_unreachable("Unsupported shift!");
2186 }
2187
2188 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
2189                                                 SDValue &Lo, SDValue &Hi) {
2190   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2191   SDLoc dl(N);
2192   SDValue Op = N->getOperand(0);
2193   if (Op.getValueType().bitsLE(NVT)) {
2194     // The low part is sign extension of the input (degenerates to a copy).
2195     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
2196     // The high part is obtained by SRA'ing all but one of the bits of low part.
2197     unsigned LoSize = NVT.getSizeInBits();
2198     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2199                      DAG.getConstant(LoSize-1, TLI.getPointerTy()));
2200   } else {
2201     // For example, extension of an i48 to an i64.  The operand type necessarily
2202     // promotes to the result type, so will end up being expanded too.
2203     assert(getTypeAction(Op.getValueType()) ==
2204            TargetLowering::TypePromoteInteger &&
2205            "Only know how to promote this result!");
2206     SDValue Res = GetPromotedInteger(Op);
2207     assert(Res.getValueType() == N->getValueType(0) &&
2208            "Operand over promoted?");
2209     // Split the promoted operand.  This will simplify when it is expanded.
2210     SplitInteger(Res, Lo, Hi);
2211     unsigned ExcessBits =
2212       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2213     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2214                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2215                                                         ExcessBits)));
2216   }
2217 }
2218
2219 void DAGTypeLegalizer::
2220 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
2221   SDLoc dl(N);
2222   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2223   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2224
2225   if (EVT.bitsLE(Lo.getValueType())) {
2226     // sext_inreg the low part if needed.
2227     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
2228                      N->getOperand(1));
2229
2230     // The high part gets the sign extension from the lo-part.  This handles
2231     // things like sextinreg V:i64 from i8.
2232     Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
2233                      DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
2234                                      TLI.getPointerTy()));
2235   } else {
2236     // For example, extension of an i48 to an i64.  Leave the low part alone,
2237     // sext_inreg the high part.
2238     unsigned ExcessBits =
2239       EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
2240     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2241                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2242                                                         ExcessBits)));
2243   }
2244 }
2245
2246 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
2247                                          SDValue &Lo, SDValue &Hi) {
2248   EVT VT = N->getValueType(0);
2249   SDLoc dl(N);
2250
2251   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2252   if (VT == MVT::i16)
2253     LC = RTLIB::SREM_I16;
2254   else if (VT == MVT::i32)
2255     LC = RTLIB::SREM_I32;
2256   else if (VT == MVT::i64)
2257     LC = RTLIB::SREM_I64;
2258   else if (VT == MVT::i128)
2259     LC = RTLIB::SREM_I128;
2260   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
2261
2262   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2263   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, true, dl).first, Lo, Hi);
2264 }
2265
2266 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
2267                                              SDValue &Lo, SDValue &Hi) {
2268   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2269   SDLoc dl(N);
2270   Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
2271   Hi = DAG.getNode(ISD::SRL, dl,
2272                    N->getOperand(0).getValueType(), N->getOperand(0),
2273                    DAG.getConstant(NVT.getSizeInBits(), TLI.getPointerTy()));
2274   Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
2275 }
2276
2277 void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2278                                              SDValue &Lo, SDValue &Hi) {
2279   SDValue LHS = N->getOperand(0);
2280   SDValue RHS = N->getOperand(1);
2281   SDLoc dl(N);
2282
2283   // Expand the result by simply replacing it with the equivalent
2284   // non-overflow-checking operation.
2285   SDValue Sum = DAG.getNode(N->getOpcode() == ISD::UADDO ?
2286                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2287                             LHS, RHS);
2288   SplitInteger(Sum, Lo, Hi);
2289
2290   // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2291   // overflows iff a - b > a.
2292   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS,
2293                              N->getOpcode () == ISD::UADDO ?
2294                              ISD::SETULT : ISD::SETUGT);
2295
2296   // Use the calculated overflow everywhere.
2297   ReplaceValueWith(SDValue(N, 1), Ofl);
2298 }
2299
2300 void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
2301                                           SDValue &Lo, SDValue &Hi) {
2302   EVT VT = N->getValueType(0);
2303   SDLoc dl(N);
2304
2305   // A divide for UMULO should be faster than a function call.
2306   if (N->getOpcode() == ISD::UMULO) {
2307     SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
2308
2309     SDValue MUL = DAG.getNode(ISD::MUL, dl, LHS.getValueType(), LHS, RHS);
2310     SplitInteger(MUL, Lo, Hi);
2311
2312     // A divide for UMULO will be faster than a function call. Select to
2313     // make sure we aren't using 0.
2314     SDValue isZero = DAG.getSetCC(dl, getSetCCResultType(VT),
2315                                   RHS, DAG.getConstant(0, VT), ISD::SETEQ);
2316     SDValue NotZero = DAG.getSelect(dl, VT, isZero,
2317                                     DAG.getConstant(1, VT), RHS);
2318     SDValue DIV = DAG.getNode(ISD::UDIV, dl, VT, MUL, NotZero);
2319     SDValue Overflow = DAG.getSetCC(dl, N->getValueType(1), DIV, LHS,
2320                                     ISD::SETNE);
2321     Overflow = DAG.getSelect(dl, N->getValueType(1), isZero,
2322                              DAG.getConstant(0, N->getValueType(1)),
2323                              Overflow);
2324     ReplaceValueWith(SDValue(N, 1), Overflow);
2325     return;
2326   }
2327
2328   Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
2329   EVT PtrVT = TLI.getPointerTy();
2330   Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
2331
2332   // Replace this with a libcall that will check overflow.
2333   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2334   if (VT == MVT::i32)
2335     LC = RTLIB::MULO_I32;
2336   else if (VT == MVT::i64)
2337     LC = RTLIB::MULO_I64;
2338   else if (VT == MVT::i128)
2339     LC = RTLIB::MULO_I128;
2340   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
2341
2342   SDValue Temp = DAG.CreateStackTemporary(PtrVT);
2343   // Temporary for the overflow value, default it to zero.
2344   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl,
2345                                DAG.getConstant(0, PtrVT), Temp,
2346                                MachinePointerInfo(), false, false, 0);
2347
2348   TargetLowering::ArgListTy Args;
2349   TargetLowering::ArgListEntry Entry;
2350   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2351     EVT ArgVT = N->getOperand(i).getValueType();
2352     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2353     Entry.Node = N->getOperand(i);
2354     Entry.Ty = ArgTy;
2355     Entry.isSExt = true;
2356     Entry.isZExt = false;
2357     Args.push_back(Entry);
2358   }
2359
2360   // Also pass the address of the overflow check.
2361   Entry.Node = Temp;
2362   Entry.Ty = PtrTy->getPointerTo();
2363   Entry.isSExt = true;
2364   Entry.isZExt = false;
2365   Args.push_back(Entry);
2366
2367   SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
2368
2369   TargetLowering::CallLoweringInfo CLI(DAG);
2370   CLI.setDebugLoc(dl).setChain(Chain)
2371     .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Func, std::move(Args), 0)
2372     .setSExtResult();
2373
2374   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2375
2376   SplitInteger(CallInfo.first, Lo, Hi);
2377   SDValue Temp2 = DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
2378                               MachinePointerInfo(), false, false, false, 0);
2379   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2380                              DAG.getConstant(0, PtrVT),
2381                              ISD::SETNE);
2382   // Use the overflow from the libcall everywhere.
2383   ReplaceValueWith(SDValue(N, 1), Ofl);
2384 }
2385
2386 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2387                                          SDValue &Lo, SDValue &Hi) {
2388   EVT VT = N->getValueType(0);
2389   SDLoc dl(N);
2390
2391   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2392   if (VT == MVT::i16)
2393     LC = RTLIB::UDIV_I16;
2394   else if (VT == MVT::i32)
2395     LC = RTLIB::UDIV_I32;
2396   else if (VT == MVT::i64)
2397     LC = RTLIB::UDIV_I64;
2398   else if (VT == MVT::i128)
2399     LC = RTLIB::UDIV_I128;
2400   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2401
2402   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2403   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, false, dl).first, Lo, Hi);
2404 }
2405
2406 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2407                                          SDValue &Lo, SDValue &Hi) {
2408   EVT VT = N->getValueType(0);
2409   SDLoc dl(N);
2410
2411   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2412   if (VT == MVT::i16)
2413     LC = RTLIB::UREM_I16;
2414   else if (VT == MVT::i32)
2415     LC = RTLIB::UREM_I32;
2416   else if (VT == MVT::i64)
2417     LC = RTLIB::UREM_I64;
2418   else if (VT == MVT::i128)
2419     LC = RTLIB::UREM_I128;
2420   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2421
2422   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2423   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, false, dl).first, Lo, Hi);
2424 }
2425
2426 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2427                                                 SDValue &Lo, SDValue &Hi) {
2428   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2429   SDLoc dl(N);
2430   SDValue Op = N->getOperand(0);
2431   if (Op.getValueType().bitsLE(NVT)) {
2432     // The low part is zero extension of the input (degenerates to a copy).
2433     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2434     Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
2435   } else {
2436     // For example, extension of an i48 to an i64.  The operand type necessarily
2437     // promotes to the result type, so will end up being expanded too.
2438     assert(getTypeAction(Op.getValueType()) ==
2439            TargetLowering::TypePromoteInteger &&
2440            "Only know how to promote this result!");
2441     SDValue Res = GetPromotedInteger(Op);
2442     assert(Res.getValueType() == N->getValueType(0) &&
2443            "Operand over promoted?");
2444     // Split the promoted operand.  This will simplify when it is expanded.
2445     SplitInteger(Res, Lo, Hi);
2446     unsigned ExcessBits =
2447       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2448     Hi = DAG.getZeroExtendInReg(Hi, dl,
2449                                 EVT::getIntegerVT(*DAG.getContext(),
2450                                                   ExcessBits));
2451   }
2452 }
2453
2454 void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
2455                                                 SDValue &Lo, SDValue &Hi) {
2456   SDLoc dl(N);
2457   EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
2458   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
2459   SDValue Zero = DAG.getConstant(0, VT);
2460   SDValue Swap = DAG.getAtomicCmpSwap(
2461       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl,
2462       cast<AtomicSDNode>(N)->getMemoryVT(), VTs, N->getOperand(0),
2463       N->getOperand(1), Zero, Zero, cast<AtomicSDNode>(N)->getMemOperand(),
2464       cast<AtomicSDNode>(N)->getOrdering(),
2465       cast<AtomicSDNode>(N)->getOrdering(),
2466       cast<AtomicSDNode>(N)->getSynchScope());
2467
2468   ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2469   ReplaceValueWith(SDValue(N, 1), Swap.getValue(2));
2470 }
2471
2472 //===----------------------------------------------------------------------===//
2473 //  Integer Operand Expansion
2474 //===----------------------------------------------------------------------===//
2475
2476 /// ExpandIntegerOperand - This method is called when the specified operand of
2477 /// the specified node is found to need expansion.  At this point, all of the
2478 /// result types of the node are known to be legal, but other operands of the
2479 /// node may need promotion or expansion as well as the specified one.
2480 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2481   DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2482   SDValue Res = SDValue();
2483
2484   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2485     return false;
2486
2487   switch (N->getOpcode()) {
2488   default:
2489   #ifndef NDEBUG
2490     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2491     N->dump(&DAG); dbgs() << "\n";
2492   #endif
2493     llvm_unreachable("Do not know how to expand this operator's operand!");
2494
2495   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2496   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2497   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2498   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2499   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2500   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2501   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2502   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2503   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2504   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2505   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2506   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2507
2508   case ISD::SHL:
2509   case ISD::SRA:
2510   case ISD::SRL:
2511   case ISD::ROTL:
2512   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2513   case ISD::RETURNADDR:
2514   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2515
2516   case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
2517   }
2518
2519   // If the result is null, the sub-method took care of registering results etc.
2520   if (!Res.getNode()) return false;
2521
2522   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2523   // core about this.
2524   if (Res.getNode() == N)
2525     return true;
2526
2527   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2528          "Invalid operand expansion");
2529
2530   ReplaceValueWith(SDValue(N, 0), Res);
2531   return false;
2532 }
2533
2534 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2535 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2536 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2537                                                   SDValue &NewRHS,
2538                                                   ISD::CondCode &CCCode,
2539                                                   SDLoc dl) {
2540   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2541   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2542   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2543
2544   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2545     if (RHSLo == RHSHi) {
2546       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2547         if (RHSCST->isAllOnesValue()) {
2548           // Equality comparison to -1.
2549           NewLHS = DAG.getNode(ISD::AND, dl,
2550                                LHSLo.getValueType(), LHSLo, LHSHi);
2551           NewRHS = RHSLo;
2552           return;
2553         }
2554       }
2555     }
2556
2557     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2558     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2559     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2560     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2561     return;
2562   }
2563
2564   // If this is a comparison of the sign bit, just look at the top part.
2565   // X > -1,  x < 0
2566   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2567     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2568         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2569       NewLHS = LHSHi;
2570       NewRHS = RHSHi;
2571       return;
2572     }
2573
2574   // FIXME: This generated code sucks.
2575   ISD::CondCode LowCC;
2576   switch (CCCode) {
2577   default: llvm_unreachable("Unknown integer setcc!");
2578   case ISD::SETLT:
2579   case ISD::SETULT: LowCC = ISD::SETULT; break;
2580   case ISD::SETGT:
2581   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2582   case ISD::SETLE:
2583   case ISD::SETULE: LowCC = ISD::SETULE; break;
2584   case ISD::SETGE:
2585   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2586   }
2587
2588   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
2589   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
2590   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
2591
2592   // NOTE: on targets without efficient SELECT of bools, we can always use
2593   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2594   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, AfterLegalizeTypes, true,
2595                                                  nullptr);
2596   SDValue Tmp1, Tmp2;
2597   if (TLI.isTypeLegal(LHSLo.getValueType()) &&
2598       TLI.isTypeLegal(RHSLo.getValueType()))
2599     Tmp1 = TLI.SimplifySetCC(getSetCCResultType(LHSLo.getValueType()),
2600                              LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
2601   if (!Tmp1.getNode())
2602     Tmp1 = DAG.getSetCC(dl, getSetCCResultType(LHSLo.getValueType()),
2603                         LHSLo, RHSLo, LowCC);
2604   if (TLI.isTypeLegal(LHSHi.getValueType()) &&
2605       TLI.isTypeLegal(RHSHi.getValueType()))
2606     Tmp2 = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()),
2607                              LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
2608   if (!Tmp2.getNode())
2609     Tmp2 = DAG.getNode(ISD::SETCC, dl,
2610                        getSetCCResultType(LHSHi.getValueType()),
2611                        LHSHi, RHSHi, DAG.getCondCode(CCCode));
2612
2613   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
2614   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
2615   if ((Tmp1C && Tmp1C->isNullValue()) ||
2616       (Tmp2C && Tmp2C->isNullValue() &&
2617        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2618         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
2619       (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
2620        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
2621         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
2622     // low part is known false, returns high part.
2623     // For LE / GE, if high part is known false, ignore the low part.
2624     // For LT / GT, if high part is known true, ignore the low part.
2625     NewLHS = Tmp2;
2626     NewRHS = SDValue();
2627     return;
2628   }
2629
2630   NewLHS = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()),
2631                              LHSHi, RHSHi, ISD::SETEQ, false,
2632                              DagCombineInfo, dl);
2633   if (!NewLHS.getNode())
2634     NewLHS = DAG.getSetCC(dl, getSetCCResultType(LHSHi.getValueType()),
2635                           LHSHi, RHSHi, ISD::SETEQ);
2636   NewLHS = DAG.getSelect(dl, Tmp1.getValueType(),
2637                          NewLHS, Tmp1, Tmp2);
2638   NewRHS = SDValue();
2639 }
2640
2641 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2642   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2643   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2644   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2645
2646   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2647   // against zero to select between true and false values.
2648   if (!NewRHS.getNode()) {
2649     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2650     CCCode = ISD::SETNE;
2651   }
2652
2653   // Update N to have the operands specified.
2654   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2655                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2656                                 N->getOperand(4)), 0);
2657 }
2658
2659 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2660   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2661   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2662   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2663
2664   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2665   // against zero to select between true and false values.
2666   if (!NewRHS.getNode()) {
2667     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2668     CCCode = ISD::SETNE;
2669   }
2670
2671   // Update N to have the operands specified.
2672   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2673                                 N->getOperand(2), N->getOperand(3),
2674                                 DAG.getCondCode(CCCode)), 0);
2675 }
2676
2677 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2678   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2679   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2680   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2681
2682   // If ExpandSetCCOperands returned a scalar, use it.
2683   if (!NewRHS.getNode()) {
2684     assert(NewLHS.getValueType() == N->getValueType(0) &&
2685            "Unexpected setcc expansion!");
2686     return NewLHS;
2687   }
2688
2689   // Otherwise, update N to have the operands specified.
2690   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2691                                 DAG.getCondCode(CCCode)), 0);
2692 }
2693
2694 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
2695   // The value being shifted is legal, but the shift amount is too big.
2696   // It follows that either the result of the shift is undefined, or the
2697   // upper half of the shift amount is zero.  Just use the lower half.
2698   SDValue Lo, Hi;
2699   GetExpandedInteger(N->getOperand(1), Lo, Hi);
2700   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
2701 }
2702
2703 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
2704   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
2705   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
2706   // constant to valid type.
2707   SDValue Lo, Hi;
2708   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2709   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
2710 }
2711
2712 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2713   SDValue Op = N->getOperand(0);
2714   EVT DstVT = N->getValueType(0);
2715   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2716   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2717          "Don't know how to expand this SINT_TO_FP!");
2718   return TLI.makeLibCall(DAG, LC, DstVT, &Op, 1, true, SDLoc(N)).first;
2719 }
2720
2721 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2722   if (ISD::isNormalStore(N))
2723     return ExpandOp_NormalStore(N, OpNo);
2724
2725   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2726   assert(OpNo == 1 && "Can only expand the stored value so far");
2727
2728   EVT VT = N->getOperand(1).getValueType();
2729   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2730   SDValue Ch  = N->getChain();
2731   SDValue Ptr = N->getBasePtr();
2732   unsigned Alignment = N->getAlignment();
2733   bool isVolatile = N->isVolatile();
2734   bool isNonTemporal = N->isNonTemporal();
2735   AAMDNodes AAInfo = N->getAAInfo();
2736   SDLoc dl(N);
2737   SDValue Lo, Hi;
2738
2739   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2740
2741   if (N->getMemoryVT().bitsLE(NVT)) {
2742     GetExpandedInteger(N->getValue(), Lo, Hi);
2743     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2744                              N->getMemoryVT(), isVolatile, isNonTemporal,
2745                              Alignment, AAInfo);
2746   }
2747
2748   if (TLI.isLittleEndian()) {
2749     // Little-endian - low bits are at low addresses.
2750     GetExpandedInteger(N->getValue(), Lo, Hi);
2751
2752     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2753                       isVolatile, isNonTemporal, Alignment, AAInfo);
2754
2755     unsigned ExcessBits =
2756       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2757     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2758
2759     // Increment the pointer to the other half.
2760     unsigned IncrementSize = NVT.getSizeInBits()/8;
2761     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2762                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
2763     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
2764                            N->getPointerInfo().getWithOffset(IncrementSize),
2765                            NEVT, isVolatile, isNonTemporal,
2766                            MinAlign(Alignment, IncrementSize), AAInfo);
2767     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2768   }
2769
2770   // Big-endian - high bits are at low addresses.  Favor aligned stores at
2771   // the cost of some bit-fiddling.
2772   GetExpandedInteger(N->getValue(), Lo, Hi);
2773
2774   EVT ExtVT = N->getMemoryVT();
2775   unsigned EBytes = ExtVT.getStoreSize();
2776   unsigned IncrementSize = NVT.getSizeInBits()/8;
2777   unsigned ExcessBits = (EBytes - IncrementSize)*8;
2778   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
2779                                ExtVT.getSizeInBits() - ExcessBits);
2780
2781   if (ExcessBits < NVT.getSizeInBits()) {
2782     // Transfer high bits from the top of Lo to the bottom of Hi.
2783     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
2784                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2785                                      TLI.getPointerTy()));
2786     Hi = DAG.getNode(ISD::OR, dl, NVT, Hi,
2787                      DAG.getNode(ISD::SRL, dl, NVT, Lo,
2788                                  DAG.getConstant(ExcessBits,
2789                                                  TLI.getPointerTy())));
2790   }
2791
2792   // Store both the high bits and maybe some of the low bits.
2793   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(),
2794                          HiVT, isVolatile, isNonTemporal, Alignment, AAInfo);
2795
2796   // Increment the pointer to the other half.
2797   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2798                     DAG.getConstant(IncrementSize, Ptr.getValueType()));
2799   // Store the lowest ExcessBits bits in the second half.
2800   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
2801                          N->getPointerInfo().getWithOffset(IncrementSize),
2802                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
2803                          isVolatile, isNonTemporal,
2804                          MinAlign(Alignment, IncrementSize), AAInfo);
2805   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2806 }
2807
2808 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2809   SDValue InL, InH;
2810   GetExpandedInteger(N->getOperand(0), InL, InH);
2811   // Just truncate the low part of the source.
2812   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), InL);
2813 }
2814
2815 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2816   SDValue Op = N->getOperand(0);
2817   EVT SrcVT = Op.getValueType();
2818   EVT DstVT = N->getValueType(0);
2819   SDLoc dl(N);
2820
2821   // The following optimization is valid only if every value in SrcVT (when
2822   // treated as signed) is representable in DstVT.  Check that the mantissa
2823   // size of DstVT is >= than the number of bits in SrcVT -1.
2824   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(DstVT);
2825   if (APFloat::semanticsPrecision(sem) >= SrcVT.getSizeInBits()-1 &&
2826       TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2827     // Do a signed conversion then adjust the result.
2828     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
2829     SignedConv = TLI.LowerOperation(SignedConv, DAG);
2830
2831     // The result of the signed conversion needs adjusting if the 'sign bit' of
2832     // the incoming integer was set.  To handle this, we dynamically test to see
2833     // if it is set, and, if so, add a fudge factor.
2834
2835     const uint64_t F32TwoE32  = 0x4F800000ULL;
2836     const uint64_t F32TwoE64  = 0x5F800000ULL;
2837     const uint64_t F32TwoE128 = 0x7F800000ULL;
2838
2839     APInt FF(32, 0);
2840     if (SrcVT == MVT::i32)
2841       FF = APInt(32, F32TwoE32);
2842     else if (SrcVT == MVT::i64)
2843       FF = APInt(32, F32TwoE64);
2844     else if (SrcVT == MVT::i128)
2845       FF = APInt(32, F32TwoE128);
2846     else
2847       llvm_unreachable("Unsupported UINT_TO_FP!");
2848
2849     // Check whether the sign bit is set.
2850     SDValue Lo, Hi;
2851     GetExpandedInteger(Op, Lo, Hi);
2852     SDValue SignSet = DAG.getSetCC(dl,
2853                                    getSetCCResultType(Hi.getValueType()),
2854                                    Hi, DAG.getConstant(0, Hi.getValueType()),
2855                                    ISD::SETLT);
2856
2857     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2858     SDValue FudgePtr = DAG.getConstantPool(
2859                                ConstantInt::get(*DAG.getContext(), FF.zext(64)),
2860                                            TLI.getPointerTy());
2861
2862     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2863     SDValue Zero = DAG.getIntPtrConstant(0);
2864     SDValue Four = DAG.getIntPtrConstant(4);
2865     if (TLI.isBigEndian()) std::swap(Zero, Four);
2866     SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet,
2867                                    Zero, Four);
2868     unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2869     FudgePtr = DAG.getNode(ISD::ADD, dl, FudgePtr.getValueType(),
2870                            FudgePtr, Offset);
2871     Alignment = std::min(Alignment, 4u);
2872
2873     // Load the value out, extending it from f32 to the destination float type.
2874     // FIXME: Avoid the extend by constructing the right constant pool?
2875     SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(),
2876                                    FudgePtr,
2877                                    MachinePointerInfo::getConstantPool(),
2878                                    MVT::f32,
2879                                    false, false, false, Alignment);
2880     return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
2881   }
2882
2883   // Otherwise, use a libcall.
2884   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2885   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2886          "Don't know how to expand this UINT_TO_FP!");
2887   return TLI.makeLibCall(DAG, LC, DstVT, &Op, 1, true, dl).first;
2888 }
2889
2890 SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
2891   SDLoc dl(N);
2892   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2893                                cast<AtomicSDNode>(N)->getMemoryVT(),
2894                                N->getOperand(0),
2895                                N->getOperand(1), N->getOperand(2),
2896                                cast<AtomicSDNode>(N)->getMemOperand(),
2897                                cast<AtomicSDNode>(N)->getOrdering(),
2898                                cast<AtomicSDNode>(N)->getSynchScope());
2899   return Swap.getValue(1);
2900 }
2901
2902
2903 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
2904   SDValue InOp0 = N->getOperand(0);
2905   EVT InVT = InOp0.getValueType();
2906
2907   EVT OutVT = N->getValueType(0);
2908   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2909   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2910   unsigned OutNumElems = OutVT.getVectorNumElements();
2911   EVT NOutVTElem = NOutVT.getVectorElementType();
2912
2913   SDLoc dl(N);
2914   SDValue BaseIdx = N->getOperand(1);
2915
2916   SmallVector<SDValue, 8> Ops;
2917   Ops.reserve(OutNumElems);
2918   for (unsigned i = 0; i != OutNumElems; ++i) {
2919
2920     // Extract the element from the original vector.
2921     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
2922       BaseIdx, DAG.getConstant(i, BaseIdx.getValueType()));
2923     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2924       InVT.getVectorElementType(), N->getOperand(0), Index);
2925
2926     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
2927     // Insert the converted element to the new vector.
2928     Ops.push_back(Op);
2929   }
2930
2931   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
2932 }
2933
2934
2935 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
2936   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
2937   EVT VT = N->getValueType(0);
2938   SDLoc dl(N);
2939
2940   unsigned NumElts = VT.getVectorNumElements();
2941   SmallVector<int, 8> NewMask;
2942   for (unsigned i = 0; i != NumElts; ++i) {
2943     NewMask.push_back(SV->getMaskElt(i));
2944   }
2945
2946   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2947   SDValue V1 = GetPromotedInteger(N->getOperand(1));
2948   EVT OutVT = V0.getValueType();
2949
2950   return DAG.getVectorShuffle(OutVT, dl, V0, V1, &NewMask[0]);
2951 }
2952
2953
2954 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
2955   EVT OutVT = N->getValueType(0);
2956   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2957   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2958   unsigned NumElems = N->getNumOperands();
2959   EVT NOutVTElem = NOutVT.getVectorElementType();
2960
2961   SDLoc dl(N);
2962
2963   SmallVector<SDValue, 8> Ops;
2964   Ops.reserve(NumElems);
2965   for (unsigned i = 0; i != NumElems; ++i) {
2966     SDValue Op;
2967     // BUILD_VECTOR integer operand types are allowed to be larger than the
2968     // result's element type. This may still be true after the promotion. For
2969     // example, we might be promoting (<v?i1> = BV <i32>, <i32>, ...) to
2970     // (v?i16 = BV <i32>, <i32>, ...), and we can't any_extend <i32> to <i16>.
2971     if (N->getOperand(i).getValueType().bitsLT(NOutVTElem))
2972       Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
2973     else
2974       Op = N->getOperand(i);
2975     Ops.push_back(Op);
2976   }
2977
2978   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
2979 }
2980
2981 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
2982
2983   SDLoc dl(N);
2984
2985   assert(!N->getOperand(0).getValueType().isVector() &&
2986          "Input must be a scalar");
2987
2988   EVT OutVT = N->getValueType(0);
2989   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2990   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2991   EVT NOutVTElem = NOutVT.getVectorElementType();
2992
2993   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
2994
2995   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
2996 }
2997
2998 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
2999   SDLoc dl(N);
3000
3001   EVT OutVT = N->getValueType(0);
3002   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3003   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3004
3005   EVT InElemTy = OutVT.getVectorElementType();
3006   EVT OutElemTy = NOutVT.getVectorElementType();
3007
3008   unsigned NumElem = N->getOperand(0).getValueType().getVectorNumElements();
3009   unsigned NumOutElem = NOutVT.getVectorNumElements();
3010   unsigned NumOperands = N->getNumOperands();
3011   assert(NumElem * NumOperands == NumOutElem &&
3012          "Unexpected number of elements");
3013
3014   // Take the elements from the first vector.
3015   SmallVector<SDValue, 8> Ops(NumOutElem);
3016   for (unsigned i = 0; i < NumOperands; ++i) {
3017     SDValue Op = N->getOperand(i);
3018     for (unsigned j = 0; j < NumElem; ++j) {
3019       SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3020                                 InElemTy, Op, DAG.getConstant(j,
3021                                               TLI.getVectorIdxTy()));
3022       Ops[i * NumElem + j] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
3023     }
3024   }
3025
3026   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
3027 }
3028
3029 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
3030   EVT OutVT = N->getValueType(0);
3031   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3032   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3033
3034   EVT NOutVTElem = NOutVT.getVectorElementType();
3035
3036   SDLoc dl(N);
3037   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3038
3039   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
3040     NOutVTElem, N->getOperand(1));
3041   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
3042     V0, ConvElem, N->getOperand(2));
3043 }
3044
3045 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
3046   SDLoc dl(N);
3047   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3048   SDValue V1 = DAG.getZExtOrTrunc(N->getOperand(1), dl, TLI.getVectorIdxTy());
3049   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3050     V0->getValueType(0).getScalarType(), V0, V1);
3051
3052   // EXTRACT_VECTOR_ELT can return types which are wider than the incoming
3053   // element types. If this is the case then we need to expand the outgoing
3054   // value and not truncate it.
3055   return DAG.getAnyExtOrTrunc(Ext, dl, N->getValueType(0));
3056 }
3057
3058 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
3059   SDLoc dl(N);
3060   unsigned NumElems = N->getNumOperands();
3061
3062   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
3063
3064   SmallVector<SDValue, 8> NewOps;
3065   NewOps.reserve(NumElems);
3066
3067   // For each incoming vector
3068   for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
3069     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
3070     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
3071     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
3072
3073     for (unsigned i=0; i<NumElem; ++i) {
3074       // Extract element from incoming vector
3075       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy,
3076       Incoming, DAG.getConstant(i, TLI.getVectorIdxTy()));
3077       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
3078       NewOps.push_back(Tr);
3079     }
3080   }
3081
3082   return DAG.getNode(ISD::BUILD_VECTOR, dl,  N->getValueType(0), NewOps);
3083 }