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