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