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