Fix PR3011: LegalizeTypes support for scalarizing
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeVectorTypes.cpp
1 //===------- LegalizeVectorTypes.cpp - Legalization of vector 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 performs vector type splitting and scalarization for LegalizeTypes.
11 // Scalarization is the act of changing a computation in an illegal one-element
12 // vector type to be a computation in its scalar element type.  For example,
13 // implementing <1 x f32> arithmetic in a scalar f32 register.  This is needed
14 // as a base case when scalarizing vector arithmetic like <4 x f32>, which
15 // eventually decomposes to scalars if the target doesn't support v4f32 or v2f32
16 // types.
17 // Splitting is the act of changing a computation in an invalid vector type to
18 // be a computation in multiple vectors of a smaller type.  For example,
19 // implementing <128 x f32> operations in terms of two <64 x f32> operations.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "LegalizeTypes.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //  Result Vector Scalarization: <1 x ty> -> ty.
28 //===----------------------------------------------------------------------===//
29
30 void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) {
31   DEBUG(cerr << "Scalarize node result " << ResNo << ": "; N->dump(&DAG);
32         cerr << "\n");
33   SDValue R = SDValue();
34
35   switch (N->getOpcode()) {
36   default:
37 #ifndef NDEBUG
38     cerr << "ScalarizeVectorResult #" << ResNo << ": ";
39     N->dump(&DAG); cerr << "\n";
40 #endif
41     assert(0 && "Do not know how to scalarize the result of this operator!");
42     abort();
43
44   case ISD::BIT_CONVERT:    R = ScalarizeVecRes_BIT_CONVERT(N); break;
45   case ISD::BUILD_VECTOR:   R = N->getOperand(0); break;
46   case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break;
47   case ISD::FPOWI:          R = ScalarizeVecRes_FPOWI(N); break;
48   case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break;
49   case ISD::LOAD:           R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break;
50   case ISD::SELECT:         R = ScalarizeVecRes_SELECT(N); break;
51   case ISD::SELECT_CC:      R = ScalarizeVecRes_SELECT_CC(N); break;
52   case ISD::UNDEF:          R = ScalarizeVecRes_UNDEF(N); break;
53   case ISD::VECTOR_SHUFFLE: R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break;
54   case ISD::VSETCC:         R = ScalarizeVecRes_VSETCC(N); break;
55
56   case ISD::CTLZ:
57   case ISD::CTPOP:
58   case ISD::CTTZ:
59   case ISD::FABS:
60   case ISD::FCOS:
61   case ISD::FNEG:
62   case ISD::FP_TO_SINT:
63   case ISD::FP_TO_UINT:
64   case ISD::FSIN:
65   case ISD::FSQRT:
66   case ISD::FTRUNC:
67   case ISD::FFLOOR:
68   case ISD::FCEIL:
69   case ISD::FRINT:
70   case ISD::FNEARBYINT:
71   case ISD::SINT_TO_FP:
72   case ISD::TRUNCATE:
73   case ISD::UINT_TO_FP: R = ScalarizeVecRes_UnaryOp(N); break;
74
75   case ISD::ADD:
76   case ISD::AND:
77   case ISD::FADD:
78   case ISD::FDIV:
79   case ISD::FMUL:
80   case ISD::FPOW:
81   case ISD::FREM:
82   case ISD::FSUB:
83   case ISD::MUL:
84   case ISD::OR:
85   case ISD::SDIV:
86   case ISD::SREM:
87   case ISD::SUB:
88   case ISD::UDIV:
89   case ISD::UREM:
90   case ISD::XOR:  R = ScalarizeVecRes_BinOp(N); break;
91   }
92
93   // If R is null, the sub-method took care of registering the result.
94   if (R.getNode())
95     SetScalarizedVector(SDValue(N, ResNo), R);
96 }
97
98 SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) {
99   SDValue LHS = GetScalarizedVector(N->getOperand(0));
100   SDValue RHS = GetScalarizedVector(N->getOperand(1));
101   return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
102 }
103
104 SDValue DAGTypeLegalizer::ScalarizeVecRes_BIT_CONVERT(SDNode *N) {
105   MVT NewVT = N->getValueType(0).getVectorElementType();
106   return DAG.getNode(ISD::BIT_CONVERT, NewVT, N->getOperand(0));
107 }
108
109 SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
110   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
111                      N->getValueType(0).getVectorElementType(),
112                      N->getOperand(0), N->getOperand(1));
113 }
114
115 SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) {
116   SDValue Op = GetScalarizedVector(N->getOperand(0));
117   return DAG.getNode(ISD::FPOWI, Op.getValueType(), Op, N->getOperand(1));
118 }
119
120 SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) {
121   // The value to insert may have a wider type than the vector element type,
122   // so be sure to truncate it to the element type if necessary.
123   SDValue Op = N->getOperand(1);
124   MVT EltVT = N->getValueType(0).getVectorElementType();
125   if (Op.getValueType() != EltVT)
126     // FIXME: Can this happen for floating point types?
127     Op = DAG.getNode(ISD::TRUNCATE, EltVT, Op);
128   return Op;
129 }
130
131 SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) {
132   assert(N->isUnindexed() && "Indexed vector load?");
133
134   SDValue Result = DAG.getLoad(ISD::UNINDEXED, N->getExtensionType(),
135                                N->getValueType(0).getVectorElementType(),
136                                N->getChain(), N->getBasePtr(),
137                                DAG.getNode(ISD::UNDEF,
138                                            N->getBasePtr().getValueType()),
139                                N->getSrcValue(), N->getSrcValueOffset(),
140                                N->getMemoryVT().getVectorElementType(),
141                                N->isVolatile(), N->getAlignment());
142
143   // Legalized the chain result - switch anything that used the old chain to
144   // use the new one.
145   ReplaceValueWith(SDValue(N, 1), Result.getValue(1));
146   return Result;
147 }
148
149 SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) {
150   // Get the dest type - it doesn't always match the input type, e.g. int_to_fp.
151   MVT DestVT = N->getValueType(0).getVectorElementType();
152   SDValue Op = GetScalarizedVector(N->getOperand(0));
153   return DAG.getNode(N->getOpcode(), DestVT, Op);
154 }
155
156 SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) {
157   return DAG.getNode(ISD::UNDEF, N->getValueType(0).getVectorElementType());
158 }
159
160 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
161   SDValue LHS = GetScalarizedVector(N->getOperand(1));
162   return DAG.getNode(ISD::SELECT, LHS.getValueType(), N->getOperand(0), LHS,
163                      GetScalarizedVector(N->getOperand(2)));
164 }
165
166 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) {
167   SDValue LHS = GetScalarizedVector(N->getOperand(2));
168   return DAG.getNode(ISD::SELECT_CC, LHS.getValueType(),
169                      N->getOperand(0), N->getOperand(1),
170                      LHS, GetScalarizedVector(N->getOperand(3)),
171                      N->getOperand(4));
172 }
173
174 SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) {
175   // Figure out if the scalar is the LHS or RHS and return it.
176   SDValue Arg = N->getOperand(2).getOperand(0);
177   if (Arg.getOpcode() == ISD::UNDEF)
178     return DAG.getNode(ISD::UNDEF, N->getValueType(0).getVectorElementType());
179   unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue();
180   return GetScalarizedVector(N->getOperand(Op));
181 }
182
183 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSETCC(SDNode *N) {
184   MVT NewVT = N->getValueType(0).getVectorElementType();
185   SDValue LHS = GetScalarizedVector(N->getOperand(0));
186   SDValue RHS = GetScalarizedVector(N->getOperand(1));
187   LHS = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHS), LHS, RHS,
188                     N->getOperand(2));
189   return
190     DAG.getNode(ISD::SELECT, NewVT, LHS,
191                 DAG.getConstant(APInt::getAllOnesValue(NewVT.getSizeInBits()),
192                                 NewVT),
193                 DAG.getConstant(0ULL, NewVT));
194 }
195
196
197 //===----------------------------------------------------------------------===//
198 //  Operand Vector Scalarization <1 x ty> -> ty.
199 //===----------------------------------------------------------------------===//
200
201 bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) {
202   DEBUG(cerr << "Scalarize node operand " << OpNo << ": "; N->dump(&DAG);
203         cerr << "\n");
204   SDValue Res = SDValue();
205
206   if (Res.getNode() == 0) {
207     switch (N->getOpcode()) {
208     default:
209 #ifndef NDEBUG
210       cerr << "ScalarizeVectorOperand Op #" << OpNo << ": ";
211       N->dump(&DAG); cerr << "\n";
212 #endif
213       assert(0 && "Do not know how to scalarize this operator's operand!");
214       abort();
215
216     case ISD::BIT_CONVERT:
217       Res = ScalarizeVecOp_BIT_CONVERT(N); break;
218
219     case ISD::CONCAT_VECTORS:
220       Res = ScalarizeVecOp_CONCAT_VECTORS(N); break;
221
222     case ISD::EXTRACT_VECTOR_ELT:
223       Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N); break;
224
225     case ISD::STORE:
226       Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo); break;
227     }
228   }
229
230   // If the result is null, the sub-method took care of registering results etc.
231   if (!Res.getNode()) return false;
232
233   // If the result is N, the sub-method updated N in place.  Check to see if any
234   // operands are new, and if so, mark them.
235   if (Res.getNode() == N) {
236     // Mark N as new and remark N and its operands.  This allows us to correctly
237     // revisit N if it needs another step of promotion and allows us to visit
238     // any new operands to N.
239     ReanalyzeNode(N);
240     return true;
241   }
242
243   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
244          "Invalid operand expansion");
245
246   ReplaceValueWith(SDValue(N, 0), Res);
247   return false;
248 }
249
250 /// ScalarizeVecOp_BIT_CONVERT - If the value to convert is a vector that needs
251 /// to be scalarized, it must be <1 x ty>.  Convert the element instead.
252 SDValue DAGTypeLegalizer::ScalarizeVecOp_BIT_CONVERT(SDNode *N) {
253   SDValue Elt = GetScalarizedVector(N->getOperand(0));
254   return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Elt);
255 }
256
257 /// ScalarizeVecOp_CONCAT_VECTORS - The vectors to concatenate have length one -
258 /// use a BUILD_VECTOR instead.
259 SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) {
260   SmallVector<SDValue, 8> Ops(N->getNumOperands());
261   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
262     Ops[i] = GetScalarizedVector(N->getOperand(i));
263   return DAG.getNode(ISD::BUILD_VECTOR, N->getValueType(0),
264                      &Ops[0], Ops.size());
265 }
266
267 /// ScalarizeVecOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to
268 /// be scalarized, it must be <1 x ty>, so just return the element, ignoring the
269 /// index.
270 SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
271   return GetScalarizedVector(N->getOperand(0));
272 }
273
274 /// ScalarizeVecOp_STORE - If the value to store is a vector that needs to be
275 /// scalarized, it must be <1 x ty>.  Just store the element.
276 SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){
277   assert(N->isUnindexed() && "Indexed store of one-element vector?");
278   assert(OpNo == 1 && "Do not know how to scalarize this operand!");
279
280   if (N->isTruncatingStore())
281     return DAG.getTruncStore(N->getChain(),
282                              GetScalarizedVector(N->getOperand(1)),
283                              N->getBasePtr(),
284                              N->getSrcValue(), N->getSrcValueOffset(),
285                              N->getMemoryVT().getVectorElementType(),
286                              N->isVolatile(), N->getAlignment());
287
288   return DAG.getStore(N->getChain(), GetScalarizedVector(N->getOperand(1)),
289                       N->getBasePtr(), N->getSrcValue(), N->getSrcValueOffset(),
290                       N->isVolatile(), N->getAlignment());
291 }
292
293
294 //===----------------------------------------------------------------------===//
295 //  Result Vector Splitting
296 //===----------------------------------------------------------------------===//
297
298 /// SplitVectorResult - This method is called when the specified result of the
299 /// specified node is found to need vector splitting.  At this point, the node
300 /// may also have invalid operands or may have other results that need
301 /// legalization, we just know that (at least) one result needs vector
302 /// splitting.
303 void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) {
304   DEBUG(cerr << "Split node result: "; N->dump(&DAG); cerr << "\n");
305   SDValue Lo, Hi;
306
307   switch (N->getOpcode()) {
308   default:
309 #ifndef NDEBUG
310     cerr << "SplitVectorResult #" << ResNo << ": ";
311     N->dump(&DAG); cerr << "\n";
312 #endif
313     assert(0 && "Do not know how to split the result of this operator!");
314     abort();
315
316   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, Lo, Hi); break;
317   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
318   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
319   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
320
321   case ISD::BIT_CONVERT:    SplitVecRes_BIT_CONVERT(N, Lo, Hi); break;
322   case ISD::BUILD_VECTOR:   SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break;
323   case ISD::CONCAT_VECTORS: SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break;
324   case ISD::FPOWI:          SplitVecRes_FPOWI(N, Lo, Hi); break;
325   case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break;
326   case ISD::LOAD:           SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi);break;
327   case ISD::VECTOR_SHUFFLE: SplitVecRes_VECTOR_SHUFFLE(N, Lo, Hi); break;
328   case ISD::VSETCC:         SplitVecRes_VSETCC(N, Lo, Hi); break;
329
330   case ISD::CTTZ:
331   case ISD::CTLZ:
332   case ISD::CTPOP:
333   case ISD::FNEG:
334   case ISD::FABS:
335   case ISD::FSQRT:
336   case ISD::FSIN:
337   case ISD::FCOS:
338   case ISD::FTRUNC:
339   case ISD::FFLOOR:
340   case ISD::FCEIL:
341   case ISD::FRINT:
342   case ISD::FNEARBYINT:
343   case ISD::FP_TO_SINT:
344   case ISD::FP_TO_UINT:
345   case ISD::SINT_TO_FP:
346   case ISD::TRUNCATE:
347   case ISD::UINT_TO_FP: SplitVecRes_UnaryOp(N, Lo, Hi); break;
348
349   case ISD::ADD:
350   case ISD::SUB:
351   case ISD::MUL:
352   case ISD::FADD:
353   case ISD::FSUB:
354   case ISD::FMUL:
355   case ISD::SDIV:
356   case ISD::UDIV:
357   case ISD::FDIV:
358   case ISD::FPOW:
359   case ISD::AND:
360   case ISD::OR:
361   case ISD::XOR:
362   case ISD::UREM:
363   case ISD::SREM:
364   case ISD::FREM: SplitVecRes_BinOp(N, Lo, Hi); break;
365   }
366
367   // If Lo/Hi is null, the sub-method took care of registering results etc.
368   if (Lo.getNode())
369     SetSplitVector(SDValue(N, ResNo), Lo, Hi);
370 }
371
372 void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo,
373                                          SDValue &Hi) {
374   SDValue LHSLo, LHSHi;
375   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
376   SDValue RHSLo, RHSHi;
377   GetSplitVector(N->getOperand(1), RHSLo, RHSHi);
378
379   Lo = DAG.getNode(N->getOpcode(), LHSLo.getValueType(), LHSLo, RHSLo);
380   Hi = DAG.getNode(N->getOpcode(), LHSHi.getValueType(), LHSHi, RHSHi);
381 }
382
383 void DAGTypeLegalizer::SplitVecRes_BIT_CONVERT(SDNode *N, SDValue &Lo,
384                                                SDValue &Hi) {
385   // We know the result is a vector.  The input may be either a vector or a
386   // scalar value.
387   MVT LoVT, HiVT;
388   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
389
390   SDValue InOp = N->getOperand(0);
391   MVT InVT = InOp.getValueType();
392
393   // Handle some special cases efficiently.
394   switch (getTypeAction(InVT)) {
395   default:
396     assert(false && "Unknown type action!");
397   case Legal:
398   case PromoteInteger:
399   case SoftenFloat:
400   case ScalarizeVector:
401     break;
402   case ExpandInteger:
403   case ExpandFloat:
404     // A scalar to vector conversion, where the scalar needs expansion.
405     // If the vector is being split in two then we can just convert the
406     // expanded pieces.
407     if (LoVT == HiVT) {
408       GetExpandedOp(InOp, Lo, Hi);
409       if (TLI.isBigEndian())
410         std::swap(Lo, Hi);
411       Lo = DAG.getNode(ISD::BIT_CONVERT, LoVT, Lo);
412       Hi = DAG.getNode(ISD::BIT_CONVERT, HiVT, Hi);
413       return;
414     }
415     break;
416   case SplitVector:
417     // If the input is a vector that needs to be split, convert each split
418     // piece of the input now.
419     GetSplitVector(InOp, Lo, Hi);
420     Lo = DAG.getNode(ISD::BIT_CONVERT, LoVT, Lo);
421     Hi = DAG.getNode(ISD::BIT_CONVERT, HiVT, Hi);
422     return;
423   }
424
425   // In the general case, convert the input to an integer and split it by hand.
426   MVT LoIntVT = MVT::getIntegerVT(LoVT.getSizeInBits());
427   MVT HiIntVT = MVT::getIntegerVT(HiVT.getSizeInBits());
428   if (TLI.isBigEndian())
429     std::swap(LoIntVT, HiIntVT);
430
431   SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi);
432
433   if (TLI.isBigEndian())
434     std::swap(Lo, Hi);
435   Lo = DAG.getNode(ISD::BIT_CONVERT, LoVT, Lo);
436   Hi = DAG.getNode(ISD::BIT_CONVERT, HiVT, Hi);
437 }
438
439 void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo,
440                                                 SDValue &Hi) {
441   MVT LoVT, HiVT;
442   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
443   unsigned LoNumElts = LoVT.getVectorNumElements();
444   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts);
445   Lo = DAG.getNode(ISD::BUILD_VECTOR, LoVT, &LoOps[0], LoOps.size());
446
447   SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end());
448   Hi = DAG.getNode(ISD::BUILD_VECTOR, HiVT, &HiOps[0], HiOps.size());
449 }
450
451 void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo,
452                                                   SDValue &Hi) {
453   assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS");
454   unsigned NumSubvectors = N->getNumOperands() / 2;
455   if (NumSubvectors == 1) {
456     Lo = N->getOperand(0);
457     Hi = N->getOperand(1);
458     return;
459   }
460
461   MVT LoVT, HiVT;
462   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
463
464   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors);
465   Lo = DAG.getNode(ISD::CONCAT_VECTORS, LoVT, &LoOps[0], LoOps.size());
466
467   SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end());
468   Hi = DAG.getNode(ISD::CONCAT_VECTORS, HiVT, &HiOps[0], HiOps.size());
469 }
470
471 void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo,
472                                          SDValue &Hi) {
473   GetSplitVector(N->getOperand(0), Lo, Hi);
474   Lo = DAG.getNode(ISD::FPOWI, Lo.getValueType(), Lo, N->getOperand(1));
475   Hi = DAG.getNode(ISD::FPOWI, Hi.getValueType(), Hi, N->getOperand(1));
476 }
477
478 void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo,
479                                                      SDValue &Hi) {
480   SDValue Vec = N->getOperand(0);
481   SDValue Elt = N->getOperand(1);
482   SDValue Idx = N->getOperand(2);
483   GetSplitVector(Vec, Lo, Hi);
484
485   if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
486     unsigned IdxVal = CIdx->getZExtValue();
487     unsigned LoNumElts = Lo.getValueType().getVectorNumElements();
488     if (IdxVal < LoNumElts)
489       Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, Lo.getValueType(), Lo, Elt, Idx);
490     else
491       Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, Hi.getValueType(), Hi, Elt,
492                        DAG.getIntPtrConstant(IdxVal - LoNumElts));
493     return;
494   }
495
496   // Spill the vector to the stack.
497   MVT VecVT = Vec.getValueType();
498   MVT EltVT = VecVT.getVectorElementType();
499   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
500   SDValue Store = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
501
502   // Store the new element.  This may be larger than the vector element type,
503   // so use a truncating store.
504   SDValue EltPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
505   Store = DAG.getTruncStore(Store, Elt, EltPtr, NULL, 0, EltVT);
506
507   // Reload the vector from the stack.
508   SDValue Load = DAG.getLoad(VecVT, Store, StackPtr, NULL, 0);
509
510   // Split it.
511   SplitVecRes_LOAD(cast<LoadSDNode>(Load.getNode()), Lo, Hi);
512 }
513
514 void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo,
515                                         SDValue &Hi) {
516   assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!");
517   MVT LoVT, HiVT;
518   GetSplitDestVTs(LD->getValueType(0), LoVT, HiVT);
519
520   ISD::LoadExtType ExtType = LD->getExtensionType();
521   SDValue Ch = LD->getChain();
522   SDValue Ptr = LD->getBasePtr();
523   SDValue Offset = DAG.getNode(ISD::UNDEF, Ptr.getValueType());
524   const Value *SV = LD->getSrcValue();
525   int SVOffset = LD->getSrcValueOffset();
526   MVT MemoryVT = LD->getMemoryVT();
527   unsigned Alignment = LD->getAlignment();
528   bool isVolatile = LD->isVolatile();
529
530   MVT LoMemVT, HiMemVT;
531   GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
532
533   Lo = DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, Ch, Ptr, Offset,
534                    SV, SVOffset, LoMemVT, isVolatile, Alignment);
535
536   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
537   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
538                     DAG.getIntPtrConstant(IncrementSize));
539   SVOffset += IncrementSize;
540   Alignment = MinAlign(Alignment, IncrementSize);
541   Hi = DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, Ch, Ptr, Offset,
542                    SV, SVOffset, HiMemVT, isVolatile, Alignment);
543
544   // Build a factor node to remember that this load is independent of the
545   // other one.
546   Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
547                    Hi.getValue(1));
548
549   // Legalized the chain result - switch anything that used the old chain to
550   // use the new one.
551   ReplaceValueWith(SDValue(LD, 1), Ch);
552 }
553
554 void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo,
555                                            SDValue &Hi) {
556   // Get the dest types - they may not match the input types, e.g. int_to_fp.
557   MVT LoVT, HiVT;
558   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
559
560   // Split the input.
561   MVT InVT = N->getOperand(0).getValueType();
562   switch (getTypeAction(InVT)) {
563   default: assert(0 && "Unexpected type action!");
564   case Legal: {
565     assert(LoVT == HiVT && "Legal non-power-of-two vector type?");
566     MVT InNVT = MVT::getVectorVT(InVT.getVectorElementType(),
567                                  LoVT.getVectorNumElements());
568     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, InNVT, N->getOperand(0),
569                      DAG.getIntPtrConstant(0));
570     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, InNVT, N->getOperand(0),
571                      DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
572     break;
573   }
574   case SplitVector:
575     GetSplitVector(N->getOperand(0), Lo, Hi);
576     break;
577   }
578
579   Lo = DAG.getNode(N->getOpcode(), LoVT, Lo);
580   Hi = DAG.getNode(N->getOpcode(), HiVT, Hi);
581 }
582
583 void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(SDNode *N, SDValue &Lo,
584                                                   SDValue &Hi) {
585   // Build the low part.
586   SDValue Mask = N->getOperand(2);
587   SmallVector<SDValue, 16> Ops;
588   MVT LoVT, HiVT;
589   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
590   MVT EltVT = LoVT.getVectorElementType();
591   unsigned LoNumElts = LoVT.getVectorNumElements();
592   unsigned NumElements = Mask.getNumOperands();
593
594   // Insert all of the elements from the input that are needed.  We use
595   // buildvector of extractelement here because the input vectors will have
596   // to be legalized, so this makes the code simpler.
597   for (unsigned i = 0; i != LoNumElts; ++i) {
598     SDValue Arg = Mask.getOperand(i);
599     if (Arg.getOpcode() == ISD::UNDEF) {
600       Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
601     } else {
602       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
603       SDValue InVec = N->getOperand(0);
604       if (Idx >= NumElements) {
605         InVec = N->getOperand(1);
606         Idx -= NumElements;
607       }
608       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, InVec,
609                                 DAG.getIntPtrConstant(Idx)));
610     }
611   }
612   Lo = DAG.getNode(ISD::BUILD_VECTOR, LoVT, &Ops[0], Ops.size());
613   Ops.clear();
614
615   for (unsigned i = LoNumElts; i != NumElements; ++i) {
616     unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
617     SDValue InVec = N->getOperand(0);
618     if (Idx >= NumElements) {
619       InVec = N->getOperand(1);
620       Idx -= NumElements;
621     }
622     Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, InVec,
623                               DAG.getIntPtrConstant(Idx)));
624   }
625   Hi = DAG.getNode(ISD::BUILD_VECTOR, HiVT, &Ops[0], Ops.size());
626 }
627
628 void DAGTypeLegalizer::SplitVecRes_VSETCC(SDNode *N, SDValue &Lo,
629                                           SDValue &Hi) {
630   MVT LoVT, HiVT;
631   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
632
633   SDValue LL, LH, RL, RH;
634   GetSplitVector(N->getOperand(0), LL, LH);
635   GetSplitVector(N->getOperand(1), RL, RH);
636
637   Lo = DAG.getNode(ISD::VSETCC, LoVT, LL, RL, N->getOperand(2));
638   Hi = DAG.getNode(ISD::VSETCC, HiVT, LH, RH, N->getOperand(2));
639 }
640
641
642 //===----------------------------------------------------------------------===//
643 //  Operand Vector Splitting
644 //===----------------------------------------------------------------------===//
645
646 /// SplitVectorOperand - This method is called when the specified operand of the
647 /// specified node is found to need vector splitting.  At this point, all of the
648 /// result types of the node are known to be legal, but other operands of the
649 /// node may need legalization as well as the specified one.
650 bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) {
651   DEBUG(cerr << "Split node operand: "; N->dump(&DAG); cerr << "\n");
652   SDValue Res = SDValue();
653
654   if (Res.getNode() == 0) {
655     switch (N->getOpcode()) {
656     default:
657 #ifndef NDEBUG
658       cerr << "SplitVectorOperand Op #" << OpNo << ": ";
659       N->dump(&DAG); cerr << "\n";
660 #endif
661       assert(0 && "Do not know how to split this operator's operand!");
662       abort();
663
664     case ISD::BIT_CONVERT:       Res = SplitVecOp_BIT_CONVERT(N); break;
665     case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break;
666     case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break;
667     case ISD::STORE:             Res = SplitVecOp_STORE(cast<StoreSDNode>(N),
668                                                         OpNo); break;
669     case ISD::VECTOR_SHUFFLE:    Res = SplitVecOp_VECTOR_SHUFFLE(N, OpNo);break;
670
671     case ISD::CTTZ:
672     case ISD::CTLZ:
673     case ISD::CTPOP:
674     case ISD::FP_TO_SINT:
675     case ISD::FP_TO_UINT:
676     case ISD::SINT_TO_FP:
677     case ISD::TRUNCATE:
678     case ISD::UINT_TO_FP: Res = SplitVecOp_UnaryOp(N); break;
679     }
680   }
681
682   // If the result is null, the sub-method took care of registering results etc.
683   if (!Res.getNode()) return false;
684
685   // If the result is N, the sub-method updated N in place.  Check to see if any
686   // operands are new, and if so, mark them.
687   if (Res.getNode() == N) {
688     // Mark N as new and remark N and its operands.  This allows us to correctly
689     // revisit N if it needs another step of promotion and allows us to visit
690     // any new operands to N.
691     ReanalyzeNode(N);
692     return true;
693   }
694
695   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
696          "Invalid operand expansion");
697
698   ReplaceValueWith(SDValue(N, 0), Res);
699   return false;
700 }
701
702 SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) {
703   // The result has a legal vector type, but the input needs splitting.
704   MVT ResVT = N->getValueType(0);
705   SDValue Lo, Hi;
706   GetSplitVector(N->getOperand(0), Lo, Hi);
707   assert(Lo.getValueType() == Hi.getValueType() &&
708          "Returns legal non-power-of-two vector type?");
709   MVT InVT = Lo.getValueType();
710
711   MVT OutVT = MVT::getVectorVT(ResVT.getVectorElementType(),
712                                InVT.getVectorNumElements());
713
714   Lo = DAG.getNode(N->getOpcode(), OutVT, Lo);
715   Hi = DAG.getNode(N->getOpcode(), OutVT, Hi);
716
717   return DAG.getNode(ISD::CONCAT_VECTORS, ResVT, Lo, Hi);
718 }
719
720 SDValue DAGTypeLegalizer::SplitVecOp_BIT_CONVERT(SDNode *N) {
721   // For example, i64 = BIT_CONVERT v4i16 on alpha.  Typically the vector will
722   // end up being split all the way down to individual components.  Convert the
723   // split pieces into integers and reassemble.
724   SDValue Lo, Hi;
725   GetSplitVector(N->getOperand(0), Lo, Hi);
726   Lo = BitConvertToInteger(Lo);
727   Hi = BitConvertToInteger(Hi);
728
729   if (TLI.isBigEndian())
730     std::swap(Lo, Hi);
731
732   return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0),
733                      JoinIntegers(Lo, Hi));
734 }
735
736 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
737   // We know that the extracted result type is legal.  For now, assume the index
738   // is a constant.
739   MVT SubVT = N->getValueType(0);
740   SDValue Idx = N->getOperand(1);
741   SDValue Lo, Hi;
742   GetSplitVector(N->getOperand(0), Lo, Hi);
743
744   uint64_t LoElts = Lo.getValueType().getVectorNumElements();
745   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
746
747   if (IdxVal < LoElts) {
748     assert(IdxVal + SubVT.getVectorNumElements() <= LoElts &&
749            "Extracted subvector crosses vector split!");
750     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SubVT, Lo, Idx);
751   } else {
752     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SubVT, Hi,
753                        DAG.getConstant(IdxVal - LoElts, Idx.getValueType()));
754   }
755 }
756
757 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
758   SDValue Vec = N->getOperand(0);
759   SDValue Idx = N->getOperand(1);
760   MVT VecVT = Vec.getValueType();
761
762   if (isa<ConstantSDNode>(Idx)) {
763     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
764     assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!");
765
766     SDValue Lo, Hi;
767     GetSplitVector(Vec, Lo, Hi);
768
769     uint64_t LoElts = Lo.getValueType().getVectorNumElements();
770
771     if (IdxVal < LoElts)
772       return DAG.UpdateNodeOperands(SDValue(N, 0), Lo, Idx);
773     else
774       return DAG.UpdateNodeOperands(SDValue(N, 0), Hi,
775                                     DAG.getConstant(IdxVal - LoElts,
776                                                     Idx.getValueType()));
777   }
778
779   // Store the vector to the stack.
780   MVT EltVT = VecVT.getVectorElementType();
781   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
782   SDValue Store = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
783
784   // Load back the required element.
785   StackPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
786   return DAG.getLoad(EltVT, Store, StackPtr, NULL, 0);
787 }
788
789 SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) {
790   assert(N->isUnindexed() && "Indexed store of vector?");
791   assert(OpNo == 1 && "Can only split the stored value");
792
793   bool isTruncating = N->isTruncatingStore();
794   SDValue Ch  = N->getChain();
795   SDValue Ptr = N->getBasePtr();
796   int SVOffset = N->getSrcValueOffset();
797   MVT MemoryVT = N->getMemoryVT();
798   unsigned Alignment = N->getAlignment();
799   bool isVol = N->isVolatile();
800   SDValue Lo, Hi;
801   GetSplitVector(N->getOperand(1), Lo, Hi);
802
803   MVT LoMemVT, HiMemVT;
804   GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
805
806   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
807
808   if (isTruncating)
809     Lo = DAG.getTruncStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
810                            LoMemVT, isVol, Alignment);
811   else
812     Lo = DAG.getStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
813                       isVol, Alignment);
814
815   // Increment the pointer to the other half.
816   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
817                     DAG.getIntPtrConstant(IncrementSize));
818
819   if (isTruncating)
820     Hi = DAG.getTruncStore(Ch, Hi, Ptr,
821                            N->getSrcValue(), SVOffset+IncrementSize,
822                            HiMemVT,
823                            isVol, MinAlign(Alignment, IncrementSize));
824   else
825     Hi = DAG.getStore(Ch, Hi, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
826                       isVol, MinAlign(Alignment, IncrementSize));
827
828   return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
829 }
830
831 SDValue DAGTypeLegalizer::SplitVecOp_VECTOR_SHUFFLE(SDNode *N, unsigned OpNo) {
832   assert(OpNo == 2 && "Shuffle source type differs from result type?");
833   SDValue Mask = N->getOperand(2);
834   unsigned MaskLength = Mask.getValueType().getVectorNumElements();
835   unsigned LargestMaskEntryPlusOne = 2 * MaskLength;
836   unsigned MinimumBitWidth = Log2_32_Ceil(LargestMaskEntryPlusOne);
837
838   // Look for a legal vector type to place the mask values in.
839   // Note that there may not be *any* legal vector-of-integer
840   // type for which the element type is legal!
841   for (MVT::SimpleValueType EltVT = MVT::FIRST_INTEGER_VALUETYPE;
842        EltVT <= MVT::LAST_INTEGER_VALUETYPE;
843        // Integer values types are consecutively numbered.  Exploit this.
844        EltVT = MVT::SimpleValueType(EltVT + 1)) {
845
846     // Is the element type big enough to hold the values?
847     if (MVT(EltVT).getSizeInBits() < MinimumBitWidth)
848       // Nope.
849       continue;
850
851     // Is the vector type legal?
852     MVT VecVT = MVT::getVectorVT(EltVT, MaskLength);
853     if (!isTypeLegal(VecVT))
854       // Nope.
855       continue;
856
857     // If the element type is not legal, find a larger legal type to use for
858     // the BUILD_VECTOR operands.  This is an ugly hack, but seems to work!
859     // FIXME: The real solution is to change VECTOR_SHUFFLE into a variadic
860     // node where the shuffle mask is a list of integer operands, #2 .. #2+n.
861     for (MVT::SimpleValueType OpVT = EltVT; OpVT <= MVT::LAST_INTEGER_VALUETYPE;
862          // Integer values types are consecutively numbered.  Exploit this.
863          OpVT = MVT::SimpleValueType(OpVT + 1)) {
864       if (!isTypeLegal(OpVT))
865         continue;
866
867       // Success!  Rebuild the vector using the legal types.
868       SmallVector<SDValue, 16> Ops(MaskLength);
869       for (unsigned i = 0; i < MaskLength; ++i) {
870         SDValue Arg = Mask.getOperand(i);
871         if (Arg.getOpcode() == ISD::UNDEF) {
872           Ops[i] = DAG.getNode(ISD::UNDEF, OpVT);
873         } else {
874           uint64_t Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
875           Ops[i] = DAG.getConstant(Idx, OpVT);
876         }
877       }
878       return DAG.UpdateNodeOperands(SDValue(N,0),
879                                     N->getOperand(0), N->getOperand(1),
880                                     DAG.getNode(ISD::BUILD_VECTOR,
881                                                 VecVT, &Ops[0], Ops.size()));
882     }
883
884     // Continuing is pointless - failure is certain.
885     break;
886   }
887   assert(false && "Failed to find an appropriate mask type!");
888   return SDValue(N, 0);
889 }