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