Add support for scalarizing/splitting vector bswap.
[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 two vectors of half the size.  For example, implementing
19 // <128 x f32> operations in terms of two <64 x f32> operations.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "LegalizeTypes.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 //  Result Vector Scalarization: <1 x ty> -> ty.
31 //===----------------------------------------------------------------------===//
32
33 void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) {
34   DEBUG(dbgs() << "Scalarize node result " << ResNo << ": ";
35         N->dump(&DAG);
36         dbgs() << "\n");
37   SDValue R = SDValue();
38
39   switch (N->getOpcode()) {
40   default:
41 #ifndef NDEBUG
42     dbgs() << "ScalarizeVectorResult #" << ResNo << ": ";
43     N->dump(&DAG);
44     dbgs() << "\n";
45 #endif
46     report_fatal_error("Do not know how to scalarize the result of this "
47                        "operator!\n");
48
49   case ISD::MERGE_VALUES:      R = ScalarizeVecRes_MERGE_VALUES(N, ResNo);break;
50   case ISD::BITCAST:           R = ScalarizeVecRes_BITCAST(N); break;
51   case ISD::BUILD_VECTOR:      R = ScalarizeVecRes_BUILD_VECTOR(N); break;
52   case ISD::CONVERT_RNDSAT:    R = ScalarizeVecRes_CONVERT_RNDSAT(N); break;
53   case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break;
54   case ISD::FP_ROUND:          R = ScalarizeVecRes_FP_ROUND(N); break;
55   case ISD::FP_ROUND_INREG:    R = ScalarizeVecRes_InregOp(N); break;
56   case ISD::FPOWI:             R = ScalarizeVecRes_FPOWI(N); break;
57   case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break;
58   case ISD::LOAD:           R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break;
59   case ISD::SCALAR_TO_VECTOR:  R = ScalarizeVecRes_SCALAR_TO_VECTOR(N); break;
60   case ISD::SIGN_EXTEND_INREG: R = ScalarizeVecRes_InregOp(N); break;
61   case ISD::VSELECT:           R = ScalarizeVecRes_VSELECT(N); break;
62   case ISD::SELECT:            R = ScalarizeVecRes_SELECT(N); break;
63   case ISD::SELECT_CC:         R = ScalarizeVecRes_SELECT_CC(N); break;
64   case ISD::SETCC:             R = ScalarizeVecRes_SETCC(N); break;
65   case ISD::UNDEF:             R = ScalarizeVecRes_UNDEF(N); break;
66   case ISD::VECTOR_SHUFFLE:    R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break;
67   case ISD::ANY_EXTEND:
68   case ISD::BSWAP:
69   case ISD::CTLZ:
70   case ISD::CTPOP:
71   case ISD::CTTZ:
72   case ISD::FABS:
73   case ISD::FCEIL:
74   case ISD::FCOS:
75   case ISD::FEXP:
76   case ISD::FEXP2:
77   case ISD::FFLOOR:
78   case ISD::FLOG:
79   case ISD::FLOG10:
80   case ISD::FLOG2:
81   case ISD::FNEARBYINT:
82   case ISD::FNEG:
83   case ISD::FP_EXTEND:
84   case ISD::FP_TO_SINT:
85   case ISD::FP_TO_UINT:
86   case ISD::FRINT:
87   case ISD::FROUND:
88   case ISD::FSIN:
89   case ISD::FSQRT:
90   case ISD::FTRUNC:
91   case ISD::SIGN_EXTEND:
92   case ISD::SINT_TO_FP:
93   case ISD::TRUNCATE:
94   case ISD::UINT_TO_FP:
95   case ISD::ZERO_EXTEND:
96     R = ScalarizeVecRes_UnaryOp(N);
97     break;
98
99   case ISD::ADD:
100   case ISD::AND:
101   case ISD::FADD:
102   case ISD::FCOPYSIGN:
103   case ISD::FDIV:
104   case ISD::FMUL:
105   case ISD::FPOW:
106   case ISD::FREM:
107   case ISD::FSUB:
108   case ISD::MUL:
109   case ISD::OR:
110   case ISD::SDIV:
111   case ISD::SREM:
112   case ISD::SUB:
113   case ISD::UDIV:
114   case ISD::UREM:
115   case ISD::XOR:
116   case ISD::SHL:
117   case ISD::SRA:
118   case ISD::SRL:
119     R = ScalarizeVecRes_BinOp(N);
120     break;
121   case ISD::FMA:
122     R = ScalarizeVecRes_TernaryOp(N);
123     break;
124   }
125
126   // If R is null, the sub-method took care of registering the result.
127   if (R.getNode())
128     SetScalarizedVector(SDValue(N, ResNo), R);
129 }
130
131 SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) {
132   SDValue LHS = GetScalarizedVector(N->getOperand(0));
133   SDValue RHS = GetScalarizedVector(N->getOperand(1));
134   return DAG.getNode(N->getOpcode(), SDLoc(N),
135                      LHS.getValueType(), LHS, RHS);
136 }
137
138 SDValue DAGTypeLegalizer::ScalarizeVecRes_TernaryOp(SDNode *N) {
139   SDValue Op0 = GetScalarizedVector(N->getOperand(0));
140   SDValue Op1 = GetScalarizedVector(N->getOperand(1));
141   SDValue Op2 = GetScalarizedVector(N->getOperand(2));
142   return DAG.getNode(N->getOpcode(), SDLoc(N),
143                      Op0.getValueType(), Op0, Op1, Op2);
144 }
145
146 SDValue DAGTypeLegalizer::ScalarizeVecRes_MERGE_VALUES(SDNode *N,
147                                                        unsigned ResNo) {
148   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
149   return GetScalarizedVector(Op);
150 }
151
152 SDValue DAGTypeLegalizer::ScalarizeVecRes_BITCAST(SDNode *N) {
153   EVT NewVT = N->getValueType(0).getVectorElementType();
154   return DAG.getNode(ISD::BITCAST, SDLoc(N),
155                      NewVT, N->getOperand(0));
156 }
157
158 SDValue DAGTypeLegalizer::ScalarizeVecRes_BUILD_VECTOR(SDNode *N) {
159   EVT EltVT = N->getValueType(0).getVectorElementType();
160   SDValue InOp = N->getOperand(0);
161   // The BUILD_VECTOR operands may be of wider element types and
162   // we may need to truncate them back to the requested return type.
163   if (EltVT.isInteger())
164     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, InOp);
165   return InOp;
166 }
167
168 SDValue DAGTypeLegalizer::ScalarizeVecRes_CONVERT_RNDSAT(SDNode *N) {
169   EVT NewVT = N->getValueType(0).getVectorElementType();
170   SDValue Op0 = GetScalarizedVector(N->getOperand(0));
171   return DAG.getConvertRndSat(NewVT, SDLoc(N),
172                               Op0, DAG.getValueType(NewVT),
173                               DAG.getValueType(Op0.getValueType()),
174                               N->getOperand(3),
175                               N->getOperand(4),
176                               cast<CvtRndSatSDNode>(N)->getCvtCode());
177 }
178
179 SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
180   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N),
181                      N->getValueType(0).getVectorElementType(),
182                      N->getOperand(0), N->getOperand(1));
183 }
184
185 SDValue DAGTypeLegalizer::ScalarizeVecRes_FP_ROUND(SDNode *N) {
186   EVT NewVT = N->getValueType(0).getVectorElementType();
187   SDValue Op = GetScalarizedVector(N->getOperand(0));
188   return DAG.getNode(ISD::FP_ROUND, SDLoc(N),
189                      NewVT, Op, N->getOperand(1));
190 }
191
192 SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) {
193   SDValue Op = GetScalarizedVector(N->getOperand(0));
194   return DAG.getNode(ISD::FPOWI, SDLoc(N),
195                      Op.getValueType(), Op, N->getOperand(1));
196 }
197
198 SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) {
199   // The value to insert may have a wider type than the vector element type,
200   // so be sure to truncate it to the element type if necessary.
201   SDValue Op = N->getOperand(1);
202   EVT EltVT = N->getValueType(0).getVectorElementType();
203   if (Op.getValueType() != EltVT)
204     // FIXME: Can this happen for floating point types?
205     Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, Op);
206   return Op;
207 }
208
209 SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) {
210   assert(N->isUnindexed() && "Indexed vector load?");
211
212   SDValue Result = DAG.getLoad(ISD::UNINDEXED,
213                                N->getExtensionType(),
214                                N->getValueType(0).getVectorElementType(),
215                                SDLoc(N),
216                                N->getChain(), N->getBasePtr(),
217                                DAG.getUNDEF(N->getBasePtr().getValueType()),
218                                N->getPointerInfo(),
219                                N->getMemoryVT().getVectorElementType(),
220                                N->isVolatile(), N->isNonTemporal(),
221                                N->isInvariant(), N->getOriginalAlignment(),
222                                N->getTBAAInfo());
223
224   // Legalized the chain result - switch anything that used the old chain to
225   // use the new one.
226   ReplaceValueWith(SDValue(N, 1), Result.getValue(1));
227   return Result;
228 }
229
230 SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) {
231   // Get the dest type - it doesn't always match the input type, e.g. int_to_fp.
232   EVT DestVT = N->getValueType(0).getVectorElementType();
233   SDValue Op = GetScalarizedVector(N->getOperand(0));
234   return DAG.getNode(N->getOpcode(), SDLoc(N), DestVT, Op);
235 }
236
237 SDValue DAGTypeLegalizer::ScalarizeVecRes_InregOp(SDNode *N) {
238   EVT EltVT = N->getValueType(0).getVectorElementType();
239   EVT ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT().getVectorElementType();
240   SDValue LHS = GetScalarizedVector(N->getOperand(0));
241   return DAG.getNode(N->getOpcode(), SDLoc(N), EltVT,
242                      LHS, DAG.getValueType(ExtVT));
243 }
244
245 SDValue DAGTypeLegalizer::ScalarizeVecRes_SCALAR_TO_VECTOR(SDNode *N) {
246   // If the operand is wider than the vector element type then it is implicitly
247   // truncated.  Make that explicit here.
248   EVT EltVT = N->getValueType(0).getVectorElementType();
249   SDValue InOp = N->getOperand(0);
250   if (InOp.getValueType() != EltVT)
251     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, InOp);
252   return InOp;
253 }
254
255 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSELECT(SDNode *N) {
256   SDValue Cond = GetScalarizedVector(N->getOperand(0));
257   SDValue LHS = GetScalarizedVector(N->getOperand(1));
258   TargetLowering::BooleanContent ScalarBool = TLI.getBooleanContents(false);
259   TargetLowering::BooleanContent VecBool = TLI.getBooleanContents(true);
260   if (ScalarBool != VecBool) {
261     EVT CondVT = Cond.getValueType();
262     switch (ScalarBool) {
263       case TargetLowering::UndefinedBooleanContent:
264         break;
265       case TargetLowering::ZeroOrOneBooleanContent:
266         assert(VecBool == TargetLowering::UndefinedBooleanContent ||
267                VecBool == TargetLowering::ZeroOrNegativeOneBooleanContent);
268         // Vector read from all ones, scalar expects a single 1 so mask.
269         Cond = DAG.getNode(ISD::AND, SDLoc(N), CondVT,
270                            Cond, DAG.getConstant(1, CondVT));
271         break;
272       case TargetLowering::ZeroOrNegativeOneBooleanContent:
273         assert(VecBool == TargetLowering::UndefinedBooleanContent ||
274                VecBool == TargetLowering::ZeroOrOneBooleanContent);
275         // Vector reads from a one, scalar from all ones so sign extend.
276         Cond = DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), CondVT,
277                            Cond, DAG.getValueType(MVT::i1));
278         break;
279     }
280   }
281
282   return DAG.getSelect(SDLoc(N),
283                        LHS.getValueType(), Cond, LHS,
284                        GetScalarizedVector(N->getOperand(2)));
285 }
286
287 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
288   SDValue LHS = GetScalarizedVector(N->getOperand(1));
289   return DAG.getSelect(SDLoc(N),
290                        LHS.getValueType(), N->getOperand(0), LHS,
291                        GetScalarizedVector(N->getOperand(2)));
292 }
293
294 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) {
295   SDValue LHS = GetScalarizedVector(N->getOperand(2));
296   return DAG.getNode(ISD::SELECT_CC, SDLoc(N), LHS.getValueType(),
297                      N->getOperand(0), N->getOperand(1),
298                      LHS, GetScalarizedVector(N->getOperand(3)),
299                      N->getOperand(4));
300 }
301
302 SDValue DAGTypeLegalizer::ScalarizeVecRes_SETCC(SDNode *N) {
303   assert(N->getValueType(0).isVector() ==
304          N->getOperand(0).getValueType().isVector() &&
305          "Scalar/Vector type mismatch");
306
307   if (N->getValueType(0).isVector()) return ScalarizeVecRes_VSETCC(N);
308
309   SDValue LHS = GetScalarizedVector(N->getOperand(0));
310   SDValue RHS = GetScalarizedVector(N->getOperand(1));
311   SDLoc DL(N);
312
313   // Turn it into a scalar SETCC.
314   return DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, N->getOperand(2));
315 }
316
317 SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) {
318   return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
319 }
320
321 SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) {
322   // Figure out if the scalar is the LHS or RHS and return it.
323   SDValue Arg = N->getOperand(2).getOperand(0);
324   if (Arg.getOpcode() == ISD::UNDEF)
325     return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
326   unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue();
327   return GetScalarizedVector(N->getOperand(Op));
328 }
329
330 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSETCC(SDNode *N) {
331   assert(N->getValueType(0).isVector() &&
332          N->getOperand(0).getValueType().isVector() &&
333          "Operand types must be vectors");
334
335   SDValue LHS = GetScalarizedVector(N->getOperand(0));
336   SDValue RHS = GetScalarizedVector(N->getOperand(1));
337   EVT NVT = N->getValueType(0).getVectorElementType();
338   SDLoc DL(N);
339
340   // Turn it into a scalar SETCC.
341   SDValue Res = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS,
342                             N->getOperand(2));
343   // Vectors may have a different boolean contents to scalars.  Promote the
344   // value appropriately.
345   ISD::NodeType ExtendCode =
346     TargetLowering::getExtendForContent(TLI.getBooleanContents(true));
347   return DAG.getNode(ExtendCode, DL, NVT, Res);
348 }
349
350
351 //===----------------------------------------------------------------------===//
352 //  Operand Vector Scalarization <1 x ty> -> ty.
353 //===----------------------------------------------------------------------===//
354
355 bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) {
356   DEBUG(dbgs() << "Scalarize node operand " << OpNo << ": ";
357         N->dump(&DAG);
358         dbgs() << "\n");
359   SDValue Res = SDValue();
360
361   if (Res.getNode() == 0) {
362     switch (N->getOpcode()) {
363     default:
364 #ifndef NDEBUG
365       dbgs() << "ScalarizeVectorOperand Op #" << OpNo << ": ";
366       N->dump(&DAG);
367       dbgs() << "\n";
368 #endif
369       llvm_unreachable("Do not know how to scalarize this operator's operand!");
370     case ISD::BITCAST:
371       Res = ScalarizeVecOp_BITCAST(N);
372       break;
373     case ISD::ANY_EXTEND:
374     case ISD::ZERO_EXTEND:
375     case ISD::SIGN_EXTEND:
376     case ISD::TRUNCATE:
377       Res = ScalarizeVecOp_UnaryOp(N);
378       break;
379     case ISD::CONCAT_VECTORS:
380       Res = ScalarizeVecOp_CONCAT_VECTORS(N);
381       break;
382     case ISD::EXTRACT_VECTOR_ELT:
383       Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N);
384       break;
385     case ISD::STORE:
386       Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo);
387       break;
388     case ISD::FP_ROUND:
389       Res = ScalarizeVecOp_FP_ROUND(N, OpNo);
390       break;
391     }
392   }
393
394   // If the result is null, the sub-method took care of registering results etc.
395   if (!Res.getNode()) return false;
396
397   // If the result is N, the sub-method updated N in place.  Tell the legalizer
398   // core about this.
399   if (Res.getNode() == N)
400     return true;
401
402   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
403          "Invalid operand expansion");
404
405   ReplaceValueWith(SDValue(N, 0), Res);
406   return false;
407 }
408
409 /// ScalarizeVecOp_BITCAST - If the value to convert is a vector that needs
410 /// to be scalarized, it must be <1 x ty>.  Convert the element instead.
411 SDValue DAGTypeLegalizer::ScalarizeVecOp_BITCAST(SDNode *N) {
412   SDValue Elt = GetScalarizedVector(N->getOperand(0));
413   return DAG.getNode(ISD::BITCAST, SDLoc(N),
414                      N->getValueType(0), Elt);
415 }
416
417 /// ScalarizeVecOp_EXTEND - If the value to extend is a vector that needs
418 /// to be scalarized, it must be <1 x ty>.  Extend the element instead.
419 SDValue DAGTypeLegalizer::ScalarizeVecOp_UnaryOp(SDNode *N) {
420   assert(N->getValueType(0).getVectorNumElements() == 1 &&
421          "Unexected vector type!");
422   SDValue Elt = GetScalarizedVector(N->getOperand(0));
423   SmallVector<SDValue, 1> Ops(1);
424   Ops[0] = DAG.getNode(N->getOpcode(), SDLoc(N),
425                        N->getValueType(0).getScalarType(), Elt);
426   // Revectorize the result so the types line up with what the uses of this
427   // expression expect.
428   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N->getValueType(0),
429                      &Ops[0], 1);
430 }
431
432 /// ScalarizeVecOp_CONCAT_VECTORS - The vectors to concatenate have length one -
433 /// use a BUILD_VECTOR instead.
434 SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) {
435   SmallVector<SDValue, 8> Ops(N->getNumOperands());
436   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
437     Ops[i] = GetScalarizedVector(N->getOperand(i));
438   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N->getValueType(0),
439                      &Ops[0], Ops.size());
440 }
441
442 /// ScalarizeVecOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to
443 /// be scalarized, it must be <1 x ty>, so just return the element, ignoring the
444 /// index.
445 SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
446   SDValue Res = GetScalarizedVector(N->getOperand(0));
447   if (Res.getValueType() != N->getValueType(0))
448     Res = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), N->getValueType(0),
449                       Res);
450   return Res;
451 }
452
453 /// ScalarizeVecOp_STORE - If the value to store is a vector that needs to be
454 /// scalarized, it must be <1 x ty>.  Just store the element.
455 SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){
456   assert(N->isUnindexed() && "Indexed store of one-element vector?");
457   assert(OpNo == 1 && "Do not know how to scalarize this operand!");
458   SDLoc dl(N);
459
460   if (N->isTruncatingStore())
461     return DAG.getTruncStore(N->getChain(), dl,
462                              GetScalarizedVector(N->getOperand(1)),
463                              N->getBasePtr(), N->getPointerInfo(),
464                              N->getMemoryVT().getVectorElementType(),
465                              N->isVolatile(), N->isNonTemporal(),
466                              N->getAlignment(), N->getTBAAInfo());
467
468   return DAG.getStore(N->getChain(), dl, GetScalarizedVector(N->getOperand(1)),
469                       N->getBasePtr(), N->getPointerInfo(),
470                       N->isVolatile(), N->isNonTemporal(),
471                       N->getOriginalAlignment(), N->getTBAAInfo());
472 }
473
474 /// ScalarizeVecOp_FP_ROUND - If the value to round is a vector that needs
475 /// to be scalarized, it must be <1 x ty>.  Convert the element instead.
476 SDValue DAGTypeLegalizer::ScalarizeVecOp_FP_ROUND(SDNode *N, unsigned OpNo) {
477   SDValue Elt = GetScalarizedVector(N->getOperand(0));
478   SDValue Res = DAG.getNode(ISD::FP_ROUND, SDLoc(N),
479                             N->getValueType(0).getVectorElementType(), Elt,
480                             N->getOperand(1));
481   return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), N->getValueType(0), Res);
482 }
483
484 //===----------------------------------------------------------------------===//
485 //  Result Vector Splitting
486 //===----------------------------------------------------------------------===//
487
488 /// SplitVectorResult - This method is called when the specified result of the
489 /// specified node is found to need vector splitting.  At this point, the node
490 /// may also have invalid operands or may have other results that need
491 /// legalization, we just know that (at least) one result needs vector
492 /// splitting.
493 void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) {
494   DEBUG(dbgs() << "Split node result: ";
495         N->dump(&DAG);
496         dbgs() << "\n");
497   SDValue Lo, Hi;
498
499   // See if the target wants to custom expand this node.
500   if (CustomLowerNode(N, N->getValueType(ResNo), true))
501     return;
502
503   switch (N->getOpcode()) {
504   default:
505 #ifndef NDEBUG
506     dbgs() << "SplitVectorResult #" << ResNo << ": ";
507     N->dump(&DAG);
508     dbgs() << "\n";
509 #endif
510     report_fatal_error("Do not know how to split the result of this "
511                        "operator!\n");
512
513   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
514   case ISD::VSELECT:
515   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
516   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
517   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
518   case ISD::BITCAST:           SplitVecRes_BITCAST(N, Lo, Hi); break;
519   case ISD::BUILD_VECTOR:      SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break;
520   case ISD::CONCAT_VECTORS:    SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break;
521   case ISD::EXTRACT_SUBVECTOR: SplitVecRes_EXTRACT_SUBVECTOR(N, Lo, Hi); break;
522   case ISD::FP_ROUND_INREG:    SplitVecRes_InregOp(N, Lo, Hi); break;
523   case ISD::FPOWI:             SplitVecRes_FPOWI(N, Lo, Hi); break;
524   case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break;
525   case ISD::SCALAR_TO_VECTOR:  SplitVecRes_SCALAR_TO_VECTOR(N, Lo, Hi); break;
526   case ISD::SIGN_EXTEND_INREG: SplitVecRes_InregOp(N, Lo, Hi); break;
527   case ISD::LOAD:
528     SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi);
529     break;
530   case ISD::SETCC:
531     SplitVecRes_SETCC(N, Lo, Hi);
532     break;
533   case ISD::VECTOR_SHUFFLE:
534     SplitVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N), Lo, Hi);
535     break;
536
537   case ISD::BSWAP:
538   case ISD::CONVERT_RNDSAT:
539   case ISD::CTLZ:
540   case ISD::CTTZ:
541   case ISD::CTLZ_ZERO_UNDEF:
542   case ISD::CTTZ_ZERO_UNDEF:
543   case ISD::CTPOP:
544   case ISD::FABS:
545   case ISD::FCEIL:
546   case ISD::FCOS:
547   case ISD::FEXP:
548   case ISD::FEXP2:
549   case ISD::FFLOOR:
550   case ISD::FLOG:
551   case ISD::FLOG10:
552   case ISD::FLOG2:
553   case ISD::FNEARBYINT:
554   case ISD::FNEG:
555   case ISD::FP_EXTEND:
556   case ISD::FP_ROUND:
557   case ISD::FP_TO_SINT:
558   case ISD::FP_TO_UINT:
559   case ISD::FRINT:
560   case ISD::FROUND:
561   case ISD::FSIN:
562   case ISD::FSQRT:
563   case ISD::FTRUNC:
564   case ISD::SINT_TO_FP:
565   case ISD::TRUNCATE:
566   case ISD::UINT_TO_FP:
567     SplitVecRes_UnaryOp(N, Lo, Hi);
568     break;
569
570   case ISD::ANY_EXTEND:
571   case ISD::SIGN_EXTEND:
572   case ISD::ZERO_EXTEND:
573     SplitVecRes_ExtendOp(N, Lo, Hi);
574     break;
575
576   case ISD::ADD:
577   case ISD::SUB:
578   case ISD::MUL:
579   case ISD::FADD:
580   case ISD::FCOPYSIGN:
581   case ISD::FSUB:
582   case ISD::FMUL:
583   case ISD::SDIV:
584   case ISD::UDIV:
585   case ISD::FDIV:
586   case ISD::FPOW:
587   case ISD::AND:
588   case ISD::OR:
589   case ISD::XOR:
590   case ISD::SHL:
591   case ISD::SRA:
592   case ISD::SRL:
593   case ISD::UREM:
594   case ISD::SREM:
595   case ISD::FREM:
596     SplitVecRes_BinOp(N, Lo, Hi);
597     break;
598   case ISD::FMA:
599     SplitVecRes_TernaryOp(N, Lo, Hi);
600     break;
601   }
602
603   // If Lo/Hi is null, the sub-method took care of registering results etc.
604   if (Lo.getNode())
605     SetSplitVector(SDValue(N, ResNo), Lo, Hi);
606 }
607
608 void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo,
609                                          SDValue &Hi) {
610   SDValue LHSLo, LHSHi;
611   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
612   SDValue RHSLo, RHSHi;
613   GetSplitVector(N->getOperand(1), RHSLo, RHSHi);
614   SDLoc dl(N);
615
616   Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo, RHSLo);
617   Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi, RHSHi);
618 }
619
620 void DAGTypeLegalizer::SplitVecRes_TernaryOp(SDNode *N, SDValue &Lo,
621                                              SDValue &Hi) {
622   SDValue Op0Lo, Op0Hi;
623   GetSplitVector(N->getOperand(0), Op0Lo, Op0Hi);
624   SDValue Op1Lo, Op1Hi;
625   GetSplitVector(N->getOperand(1), Op1Lo, Op1Hi);
626   SDValue Op2Lo, Op2Hi;
627   GetSplitVector(N->getOperand(2), Op2Lo, Op2Hi);
628   SDLoc dl(N);
629
630   Lo = DAG.getNode(N->getOpcode(), dl, Op0Lo.getValueType(),
631                    Op0Lo, Op1Lo, Op2Lo);
632   Hi = DAG.getNode(N->getOpcode(), dl, Op0Hi.getValueType(),
633                    Op0Hi, Op1Hi, Op2Hi);
634 }
635
636 void DAGTypeLegalizer::SplitVecRes_BITCAST(SDNode *N, SDValue &Lo,
637                                            SDValue &Hi) {
638   // We know the result is a vector.  The input may be either a vector or a
639   // scalar value.
640   EVT LoVT, HiVT;
641   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
642   SDLoc dl(N);
643
644   SDValue InOp = N->getOperand(0);
645   EVT InVT = InOp.getValueType();
646
647   // Handle some special cases efficiently.
648   switch (getTypeAction(InVT)) {
649   case TargetLowering::TypeLegal:
650   case TargetLowering::TypePromoteInteger:
651   case TargetLowering::TypeSoftenFloat:
652   case TargetLowering::TypeScalarizeVector:
653   case TargetLowering::TypeWidenVector:
654     break;
655   case TargetLowering::TypeExpandInteger:
656   case TargetLowering::TypeExpandFloat:
657     // A scalar to vector conversion, where the scalar needs expansion.
658     // If the vector is being split in two then we can just convert the
659     // expanded pieces.
660     if (LoVT == HiVT) {
661       GetExpandedOp(InOp, Lo, Hi);
662       if (TLI.isBigEndian())
663         std::swap(Lo, Hi);
664       Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
665       Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
666       return;
667     }
668     break;
669   case TargetLowering::TypeSplitVector:
670     // If the input is a vector that needs to be split, convert each split
671     // piece of the input now.
672     GetSplitVector(InOp, Lo, Hi);
673     Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
674     Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
675     return;
676   }
677
678   // In the general case, convert the input to an integer and split it by hand.
679   EVT LoIntVT = EVT::getIntegerVT(*DAG.getContext(), LoVT.getSizeInBits());
680   EVT HiIntVT = EVT::getIntegerVT(*DAG.getContext(), HiVT.getSizeInBits());
681   if (TLI.isBigEndian())
682     std::swap(LoIntVT, HiIntVT);
683
684   SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi);
685
686   if (TLI.isBigEndian())
687     std::swap(Lo, Hi);
688   Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
689   Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
690 }
691
692 void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo,
693                                                 SDValue &Hi) {
694   EVT LoVT, HiVT;
695   SDLoc dl(N);
696   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
697   unsigned LoNumElts = LoVT.getVectorNumElements();
698   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts);
699   Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, LoVT, &LoOps[0], LoOps.size());
700
701   SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end());
702   Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, HiVT, &HiOps[0], HiOps.size());
703 }
704
705 void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo,
706                                                   SDValue &Hi) {
707   assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS");
708   SDLoc dl(N);
709   unsigned NumSubvectors = N->getNumOperands() / 2;
710   if (NumSubvectors == 1) {
711     Lo = N->getOperand(0);
712     Hi = N->getOperand(1);
713     return;
714   }
715
716   EVT LoVT, HiVT;
717   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
718
719   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors);
720   Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, LoVT, &LoOps[0], LoOps.size());
721
722   SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end());
723   Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HiVT, &HiOps[0], HiOps.size());
724 }
725
726 void DAGTypeLegalizer::SplitVecRes_EXTRACT_SUBVECTOR(SDNode *N, SDValue &Lo,
727                                                      SDValue &Hi) {
728   SDValue Vec = N->getOperand(0);
729   SDValue Idx = N->getOperand(1);
730   SDLoc dl(N);
731
732   EVT LoVT, HiVT;
733   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
734
735   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, LoVT, Vec, Idx);
736   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
737   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HiVT, Vec,
738                    DAG.getConstant(IdxVal + LoVT.getVectorNumElements(),
739                                    TLI.getVectorIdxTy()));
740 }
741
742 void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo,
743                                          SDValue &Hi) {
744   SDLoc dl(N);
745   GetSplitVector(N->getOperand(0), Lo, Hi);
746   Lo = DAG.getNode(ISD::FPOWI, dl, Lo.getValueType(), Lo, N->getOperand(1));
747   Hi = DAG.getNode(ISD::FPOWI, dl, Hi.getValueType(), Hi, N->getOperand(1));
748 }
749
750 void DAGTypeLegalizer::SplitVecRes_InregOp(SDNode *N, SDValue &Lo,
751                                            SDValue &Hi) {
752   SDValue LHSLo, LHSHi;
753   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
754   SDLoc dl(N);
755
756   EVT LoVT, HiVT;
757   std::tie(LoVT, HiVT) =
758     DAG.GetSplitDestVTs(cast<VTSDNode>(N->getOperand(1))->getVT());
759
760   Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo,
761                    DAG.getValueType(LoVT));
762   Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi,
763                    DAG.getValueType(HiVT));
764 }
765
766 void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo,
767                                                      SDValue &Hi) {
768   SDValue Vec = N->getOperand(0);
769   SDValue Elt = N->getOperand(1);
770   SDValue Idx = N->getOperand(2);
771   SDLoc dl(N);
772   GetSplitVector(Vec, Lo, Hi);
773
774   if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
775     unsigned IdxVal = CIdx->getZExtValue();
776     unsigned LoNumElts = Lo.getValueType().getVectorNumElements();
777     if (IdxVal < LoNumElts)
778       Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
779                        Lo.getValueType(), Lo, Elt, Idx);
780     else
781       Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Hi.getValueType(), Hi, Elt,
782                        DAG.getConstant(IdxVal - LoNumElts,
783                                        TLI.getVectorIdxTy()));
784     return;
785   }
786
787   // Spill the vector to the stack.
788   EVT VecVT = Vec.getValueType();
789   EVT EltVT = VecVT.getVectorElementType();
790   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
791   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
792                                MachinePointerInfo(), false, false, 0);
793
794   // Store the new element.  This may be larger than the vector element type,
795   // so use a truncating store.
796   SDValue EltPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
797   Type *VecType = VecVT.getTypeForEVT(*DAG.getContext());
798   unsigned Alignment =
799     TLI.getDataLayout()->getPrefTypeAlignment(VecType);
800   Store = DAG.getTruncStore(Store, dl, Elt, EltPtr, MachinePointerInfo(), EltVT,
801                             false, false, 0);
802
803   // Load the Lo part from the stack slot.
804   Lo = DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, MachinePointerInfo(),
805                    false, false, false, 0);
806
807   // Increment the pointer to the other part.
808   unsigned IncrementSize = Lo.getValueType().getSizeInBits() / 8;
809   StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
810                        DAG.getConstant(IncrementSize, StackPtr.getValueType()));
811
812   // Load the Hi part from the stack slot.
813   Hi = DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr, MachinePointerInfo(),
814                    false, false, false, MinAlign(Alignment, IncrementSize));
815 }
816
817 void DAGTypeLegalizer::SplitVecRes_SCALAR_TO_VECTOR(SDNode *N, SDValue &Lo,
818                                                     SDValue &Hi) {
819   EVT LoVT, HiVT;
820   SDLoc dl(N);
821   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
822   Lo = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoVT, N->getOperand(0));
823   Hi = DAG.getUNDEF(HiVT);
824 }
825
826 void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo,
827                                         SDValue &Hi) {
828   assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!");
829   EVT LoVT, HiVT;
830   SDLoc dl(LD);
831   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(LD->getValueType(0));
832
833   ISD::LoadExtType ExtType = LD->getExtensionType();
834   SDValue Ch = LD->getChain();
835   SDValue Ptr = LD->getBasePtr();
836   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
837   EVT MemoryVT = LD->getMemoryVT();
838   unsigned Alignment = LD->getOriginalAlignment();
839   bool isVolatile = LD->isVolatile();
840   bool isNonTemporal = LD->isNonTemporal();
841   bool isInvariant = LD->isInvariant();
842   const MDNode *TBAAInfo = LD->getTBAAInfo();
843
844   EVT LoMemVT, HiMemVT;
845   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
846
847   Lo = DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, dl, Ch, Ptr, Offset,
848                    LD->getPointerInfo(), LoMemVT, isVolatile, isNonTemporal,
849                    isInvariant, Alignment, TBAAInfo);
850
851   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
852   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
853                     DAG.getConstant(IncrementSize, Ptr.getValueType()));
854   Hi = DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, dl, Ch, Ptr, Offset,
855                    LD->getPointerInfo().getWithOffset(IncrementSize),
856                    HiMemVT, isVolatile, isNonTemporal, isInvariant, Alignment,
857                    TBAAInfo);
858
859   // Build a factor node to remember that this load is independent of the
860   // other one.
861   Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
862                    Hi.getValue(1));
863
864   // Legalized the chain result - switch anything that used the old chain to
865   // use the new one.
866   ReplaceValueWith(SDValue(LD, 1), Ch);
867 }
868
869 void DAGTypeLegalizer::SplitVecRes_SETCC(SDNode *N, SDValue &Lo, SDValue &Hi) {
870   assert(N->getValueType(0).isVector() &&
871          N->getOperand(0).getValueType().isVector() &&
872          "Operand types must be vectors");
873
874   EVT LoVT, HiVT;
875   SDLoc DL(N);
876   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
877
878   // Split the input.
879   SDValue LL, LH, RL, RH;
880   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
881   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
882
883   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
884   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
885 }
886
887 void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo,
888                                            SDValue &Hi) {
889   // Get the dest types - they may not match the input types, e.g. int_to_fp.
890   EVT LoVT, HiVT;
891   SDLoc dl(N);
892   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
893
894   // If the input also splits, handle it directly for a compile time speedup.
895   // Otherwise split it by hand.
896   EVT InVT = N->getOperand(0).getValueType();
897   if (getTypeAction(InVT) == TargetLowering::TypeSplitVector)
898     GetSplitVector(N->getOperand(0), Lo, Hi);
899   else
900     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
901
902   if (N->getOpcode() == ISD::FP_ROUND) {
903     Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo, N->getOperand(1));
904     Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi, N->getOperand(1));
905   } else if (N->getOpcode() == ISD::CONVERT_RNDSAT) {
906     SDValue DTyOpLo = DAG.getValueType(LoVT);
907     SDValue DTyOpHi = DAG.getValueType(HiVT);
908     SDValue STyOpLo = DAG.getValueType(Lo.getValueType());
909     SDValue STyOpHi = DAG.getValueType(Hi.getValueType());
910     SDValue RndOp = N->getOperand(3);
911     SDValue SatOp = N->getOperand(4);
912     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
913     Lo = DAG.getConvertRndSat(LoVT, dl, Lo, DTyOpLo, STyOpLo, RndOp, SatOp,
914                               CvtCode);
915     Hi = DAG.getConvertRndSat(HiVT, dl, Hi, DTyOpHi, STyOpHi, RndOp, SatOp,
916                               CvtCode);
917   } else {
918     Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
919     Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
920   }
921 }
922
923 void DAGTypeLegalizer::SplitVecRes_ExtendOp(SDNode *N, SDValue &Lo,
924                                             SDValue &Hi) {
925   SDLoc dl(N);
926   EVT SrcVT = N->getOperand(0).getValueType();
927   EVT DestVT = N->getValueType(0);
928   EVT LoVT, HiVT;
929   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(DestVT);
930
931   // We can do better than a generic split operation if the extend is doing
932   // more than just doubling the width of the elements and the following are
933   // true:
934   //   - The number of vector elements is even,
935   //   - the source type is legal,
936   //   - the type of a split source is illegal,
937   //   - the type of an extended (by doubling element size) source is legal, and
938   //   - the type of that extended source when split is legal.
939   //
940   // This won't necessarily completely legalize the operation, but it will
941   // more effectively move in the right direction and prevent falling down
942   // to scalarization in many cases due to the input vector being split too
943   // far.
944   unsigned NumElements = SrcVT.getVectorNumElements();
945   if ((NumElements & 1) == 0 &&
946       SrcVT.getSizeInBits() * 2 < DestVT.getSizeInBits()) {
947     LLVMContext &Ctx = *DAG.getContext();
948     EVT NewSrcVT = EVT::getVectorVT(
949         Ctx, EVT::getIntegerVT(
950                  Ctx, SrcVT.getVectorElementType().getSizeInBits() * 2),
951         NumElements);
952     EVT SplitSrcVT =
953         EVT::getVectorVT(Ctx, SrcVT.getVectorElementType(), NumElements / 2);
954     EVT SplitLoVT, SplitHiVT;
955     std::tie(SplitLoVT, SplitHiVT) = DAG.GetSplitDestVTs(NewSrcVT);
956     if (TLI.isTypeLegal(SrcVT) && !TLI.isTypeLegal(SplitSrcVT) &&
957         TLI.isTypeLegal(NewSrcVT) && TLI.isTypeLegal(SplitLoVT)) {
958       DEBUG(dbgs() << "Split vector extend via incremental extend:";
959             N->dump(&DAG); dbgs() << "\n");
960       // Extend the source vector by one step.
961       SDValue NewSrc =
962           DAG.getNode(N->getOpcode(), dl, NewSrcVT, N->getOperand(0));
963       // Get the low and high halves of the new, extended one step, vector.
964       std::tie(Lo, Hi) = DAG.SplitVector(NewSrc, dl);
965       // Extend those vector halves the rest of the way.
966       Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
967       Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
968       return;
969     }
970   }
971   // Fall back to the generic unary operator splitting otherwise.
972   SplitVecRes_UnaryOp(N, Lo, Hi);
973 }
974
975 void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
976                                                   SDValue &Lo, SDValue &Hi) {
977   // The low and high parts of the original input give four input vectors.
978   SDValue Inputs[4];
979   SDLoc dl(N);
980   GetSplitVector(N->getOperand(0), Inputs[0], Inputs[1]);
981   GetSplitVector(N->getOperand(1), Inputs[2], Inputs[3]);
982   EVT NewVT = Inputs[0].getValueType();
983   unsigned NewElts = NewVT.getVectorNumElements();
984
985   // If Lo or Hi uses elements from at most two of the four input vectors, then
986   // express it as a vector shuffle of those two inputs.  Otherwise extract the
987   // input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR.
988   SmallVector<int, 16> Ops;
989   for (unsigned High = 0; High < 2; ++High) {
990     SDValue &Output = High ? Hi : Lo;
991
992     // Build a shuffle mask for the output, discovering on the fly which
993     // input vectors to use as shuffle operands (recorded in InputUsed).
994     // If building a suitable shuffle vector proves too hard, then bail
995     // out with useBuildVector set.
996     unsigned InputUsed[2] = { -1U, -1U }; // Not yet discovered.
997     unsigned FirstMaskIdx = High * NewElts;
998     bool useBuildVector = false;
999     for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
1000       // The mask element.  This indexes into the input.
1001       int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
1002
1003       // The input vector this mask element indexes into.
1004       unsigned Input = (unsigned)Idx / NewElts;
1005
1006       if (Input >= array_lengthof(Inputs)) {
1007         // The mask element does not index into any input vector.
1008         Ops.push_back(-1);
1009         continue;
1010       }
1011
1012       // Turn the index into an offset from the start of the input vector.
1013       Idx -= Input * NewElts;
1014
1015       // Find or create a shuffle vector operand to hold this input.
1016       unsigned OpNo;
1017       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
1018         if (InputUsed[OpNo] == Input) {
1019           // This input vector is already an operand.
1020           break;
1021         } else if (InputUsed[OpNo] == -1U) {
1022           // Create a new operand for this input vector.
1023           InputUsed[OpNo] = Input;
1024           break;
1025         }
1026       }
1027
1028       if (OpNo >= array_lengthof(InputUsed)) {
1029         // More than two input vectors used!  Give up on trying to create a
1030         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
1031         useBuildVector = true;
1032         break;
1033       }
1034
1035       // Add the mask index for the new shuffle vector.
1036       Ops.push_back(Idx + OpNo * NewElts);
1037     }
1038
1039     if (useBuildVector) {
1040       EVT EltVT = NewVT.getVectorElementType();
1041       SmallVector<SDValue, 16> SVOps;
1042
1043       // Extract the input elements by hand.
1044       for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
1045         // The mask element.  This indexes into the input.
1046         int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
1047
1048         // The input vector this mask element indexes into.
1049         unsigned Input = (unsigned)Idx / NewElts;
1050
1051         if (Input >= array_lengthof(Inputs)) {
1052           // The mask element is "undef" or indexes off the end of the input.
1053           SVOps.push_back(DAG.getUNDEF(EltVT));
1054           continue;
1055         }
1056
1057         // Turn the index into an offset from the start of the input vector.
1058         Idx -= Input * NewElts;
1059
1060         // Extract the vector element by hand.
1061         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
1062                                     Inputs[Input], DAG.getConstant(Idx,
1063                                                    TLI.getVectorIdxTy())));
1064       }
1065
1066       // Construct the Lo/Hi output using a BUILD_VECTOR.
1067       Output = DAG.getNode(ISD::BUILD_VECTOR,dl,NewVT, &SVOps[0], SVOps.size());
1068     } else if (InputUsed[0] == -1U) {
1069       // No input vectors were used!  The result is undefined.
1070       Output = DAG.getUNDEF(NewVT);
1071     } else {
1072       SDValue Op0 = Inputs[InputUsed[0]];
1073       // If only one input was used, use an undefined vector for the other.
1074       SDValue Op1 = InputUsed[1] == -1U ?
1075         DAG.getUNDEF(NewVT) : Inputs[InputUsed[1]];
1076       // At least one input vector was used.  Create a new shuffle vector.
1077       Output =  DAG.getVectorShuffle(NewVT, dl, Op0, Op1, &Ops[0]);
1078     }
1079
1080     Ops.clear();
1081   }
1082 }
1083
1084
1085 //===----------------------------------------------------------------------===//
1086 //  Operand Vector Splitting
1087 //===----------------------------------------------------------------------===//
1088
1089 /// SplitVectorOperand - This method is called when the specified operand of the
1090 /// specified node is found to need vector splitting.  At this point, all of the
1091 /// result types of the node are known to be legal, but other operands of the
1092 /// node may need legalization as well as the specified one.
1093 bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) {
1094   DEBUG(dbgs() << "Split node operand: ";
1095         N->dump(&DAG);
1096         dbgs() << "\n");
1097   SDValue Res = SDValue();
1098
1099   // See if the target wants to custom split this node.
1100   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
1101     return false;
1102
1103   if (Res.getNode() == 0) {
1104     switch (N->getOpcode()) {
1105     default:
1106 #ifndef NDEBUG
1107       dbgs() << "SplitVectorOperand Op #" << OpNo << ": ";
1108       N->dump(&DAG);
1109       dbgs() << "\n";
1110 #endif
1111       report_fatal_error("Do not know how to split this operator's "
1112                          "operand!\n");
1113
1114     case ISD::SETCC:             Res = SplitVecOp_VSETCC(N); break;
1115     case ISD::BITCAST:           Res = SplitVecOp_BITCAST(N); break;
1116     case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break;
1117     case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break;
1118     case ISD::CONCAT_VECTORS:    Res = SplitVecOp_CONCAT_VECTORS(N); break;
1119     case ISD::TRUNCATE:          Res = SplitVecOp_TRUNCATE(N); break;
1120     case ISD::FP_ROUND:          Res = SplitVecOp_FP_ROUND(N); break;
1121     case ISD::STORE:
1122       Res = SplitVecOp_STORE(cast<StoreSDNode>(N), OpNo);
1123       break;
1124     case ISD::VSELECT:
1125       Res = SplitVecOp_VSELECT(N, OpNo);
1126       break;
1127     case ISD::CTTZ:
1128     case ISD::CTLZ:
1129     case ISD::CTPOP:
1130     case ISD::FP_EXTEND:
1131     case ISD::FP_TO_SINT:
1132     case ISD::FP_TO_UINT:
1133     case ISD::SINT_TO_FP:
1134     case ISD::UINT_TO_FP:
1135     case ISD::FTRUNC:
1136     case ISD::SIGN_EXTEND:
1137     case ISD::ZERO_EXTEND:
1138     case ISD::ANY_EXTEND:
1139       Res = SplitVecOp_UnaryOp(N);
1140       break;
1141     }
1142   }
1143
1144   // If the result is null, the sub-method took care of registering results etc.
1145   if (!Res.getNode()) return false;
1146
1147   // If the result is N, the sub-method updated N in place.  Tell the legalizer
1148   // core about this.
1149   if (Res.getNode() == N)
1150     return true;
1151
1152   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1153          "Invalid operand expansion");
1154
1155   ReplaceValueWith(SDValue(N, 0), Res);
1156   return false;
1157 }
1158
1159 SDValue DAGTypeLegalizer::SplitVecOp_VSELECT(SDNode *N, unsigned OpNo) {
1160   // The only possibility for an illegal operand is the mask, since result type
1161   // legalization would have handled this node already otherwise.
1162   assert(OpNo == 0 && "Illegal operand must be mask");
1163
1164   SDValue Mask = N->getOperand(0);
1165   SDValue Src0 = N->getOperand(1);
1166   SDValue Src1 = N->getOperand(2);
1167   EVT Src0VT = Src0.getValueType();
1168   SDLoc DL(N);
1169   assert(Mask.getValueType().isVector() && "VSELECT without a vector mask?");
1170
1171   SDValue Lo, Hi;
1172   GetSplitVector(N->getOperand(0), Lo, Hi);
1173   assert(Lo.getValueType() == Hi.getValueType() &&
1174          "Lo and Hi have differing types");
1175
1176   EVT LoOpVT, HiOpVT;
1177   std::tie(LoOpVT, HiOpVT) = DAG.GetSplitDestVTs(Src0VT);
1178   assert(LoOpVT == HiOpVT && "Asymmetric vector split?");
1179
1180   SDValue LoOp0, HiOp0, LoOp1, HiOp1, LoMask, HiMask;
1181   std::tie(LoOp0, HiOp0) = DAG.SplitVector(Src0, DL);
1182   std::tie(LoOp1, HiOp1) = DAG.SplitVector(Src1, DL);
1183   std::tie(LoMask, HiMask) = DAG.SplitVector(Mask, DL);
1184
1185   SDValue LoSelect =
1186     DAG.getNode(ISD::VSELECT, DL, LoOpVT, LoMask, LoOp0, LoOp1);
1187   SDValue HiSelect =
1188     DAG.getNode(ISD::VSELECT, DL, HiOpVT, HiMask, HiOp0, HiOp1);
1189
1190   return DAG.getNode(ISD::CONCAT_VECTORS, DL, Src0VT, LoSelect, HiSelect);
1191 }
1192
1193 SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) {
1194   // The result has a legal vector type, but the input needs splitting.
1195   EVT ResVT = N->getValueType(0);
1196   SDValue Lo, Hi;
1197   SDLoc dl(N);
1198   GetSplitVector(N->getOperand(0), Lo, Hi);
1199   EVT InVT = Lo.getValueType();
1200
1201   EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
1202                                InVT.getVectorNumElements());
1203
1204   Lo = DAG.getNode(N->getOpcode(), dl, OutVT, Lo);
1205   Hi = DAG.getNode(N->getOpcode(), dl, OutVT, Hi);
1206
1207   return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
1208 }
1209
1210 SDValue DAGTypeLegalizer::SplitVecOp_BITCAST(SDNode *N) {
1211   // For example, i64 = BITCAST v4i16 on alpha.  Typically the vector will
1212   // end up being split all the way down to individual components.  Convert the
1213   // split pieces into integers and reassemble.
1214   SDValue Lo, Hi;
1215   GetSplitVector(N->getOperand(0), Lo, Hi);
1216   Lo = BitConvertToInteger(Lo);
1217   Hi = BitConvertToInteger(Hi);
1218
1219   if (TLI.isBigEndian())
1220     std::swap(Lo, Hi);
1221
1222   return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0),
1223                      JoinIntegers(Lo, Hi));
1224 }
1225
1226 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
1227   // We know that the extracted result type is legal.
1228   EVT SubVT = N->getValueType(0);
1229   SDValue Idx = N->getOperand(1);
1230   SDLoc dl(N);
1231   SDValue Lo, Hi;
1232   GetSplitVector(N->getOperand(0), Lo, Hi);
1233
1234   uint64_t LoElts = Lo.getValueType().getVectorNumElements();
1235   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
1236
1237   if (IdxVal < LoElts) {
1238     assert(IdxVal + SubVT.getVectorNumElements() <= LoElts &&
1239            "Extracted subvector crosses vector split!");
1240     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Lo, Idx);
1241   } else {
1242     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Hi,
1243                        DAG.getConstant(IdxVal - LoElts, Idx.getValueType()));
1244   }
1245 }
1246
1247 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
1248   SDValue Vec = N->getOperand(0);
1249   SDValue Idx = N->getOperand(1);
1250   EVT VecVT = Vec.getValueType();
1251
1252   if (isa<ConstantSDNode>(Idx)) {
1253     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
1254     assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!");
1255
1256     SDValue Lo, Hi;
1257     GetSplitVector(Vec, Lo, Hi);
1258
1259     uint64_t LoElts = Lo.getValueType().getVectorNumElements();
1260
1261     if (IdxVal < LoElts)
1262       return SDValue(DAG.UpdateNodeOperands(N, Lo, Idx), 0);
1263     return SDValue(DAG.UpdateNodeOperands(N, Hi,
1264                                   DAG.getConstant(IdxVal - LoElts,
1265                                                   Idx.getValueType())), 0);
1266   }
1267
1268   // Store the vector to the stack.
1269   EVT EltVT = VecVT.getVectorElementType();
1270   SDLoc dl(N);
1271   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1272   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1273                                MachinePointerInfo(), false, false, 0);
1274
1275   // Load back the required element.
1276   StackPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
1277   return DAG.getExtLoad(ISD::EXTLOAD, dl, N->getValueType(0), Store, StackPtr,
1278                         MachinePointerInfo(), EltVT, false, false, 0);
1279 }
1280
1281 SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) {
1282   assert(N->isUnindexed() && "Indexed store of vector?");
1283   assert(OpNo == 1 && "Can only split the stored value");
1284   SDLoc DL(N);
1285
1286   bool isTruncating = N->isTruncatingStore();
1287   SDValue Ch  = N->getChain();
1288   SDValue Ptr = N->getBasePtr();
1289   EVT MemoryVT = N->getMemoryVT();
1290   unsigned Alignment = N->getOriginalAlignment();
1291   bool isVol = N->isVolatile();
1292   bool isNT = N->isNonTemporal();
1293   const MDNode *TBAAInfo = N->getTBAAInfo();
1294   SDValue Lo, Hi;
1295   GetSplitVector(N->getOperand(1), Lo, Hi);
1296
1297   EVT LoMemVT, HiMemVT;
1298   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1299
1300   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
1301
1302   if (isTruncating)
1303     Lo = DAG.getTruncStore(Ch, DL, Lo, Ptr, N->getPointerInfo(),
1304                            LoMemVT, isVol, isNT, Alignment, TBAAInfo);
1305   else
1306     Lo = DAG.getStore(Ch, DL, Lo, Ptr, N->getPointerInfo(),
1307                       isVol, isNT, Alignment, TBAAInfo);
1308
1309   // Increment the pointer to the other half.
1310   Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
1311                     DAG.getConstant(IncrementSize, Ptr.getValueType()));
1312
1313   if (isTruncating)
1314     Hi = DAG.getTruncStore(Ch, DL, Hi, Ptr,
1315                            N->getPointerInfo().getWithOffset(IncrementSize),
1316                            HiMemVT, isVol, isNT, Alignment, TBAAInfo);
1317   else
1318     Hi = DAG.getStore(Ch, DL, Hi, Ptr,
1319                       N->getPointerInfo().getWithOffset(IncrementSize),
1320                       isVol, isNT, Alignment, TBAAInfo);
1321
1322   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
1323 }
1324
1325 SDValue DAGTypeLegalizer::SplitVecOp_CONCAT_VECTORS(SDNode *N) {
1326   SDLoc DL(N);
1327
1328   // The input operands all must have the same type, and we know the result
1329   // type is valid.  Convert this to a buildvector which extracts all the
1330   // input elements.
1331   // TODO: If the input elements are power-two vectors, we could convert this to
1332   // a new CONCAT_VECTORS node with elements that are half-wide.
1333   SmallVector<SDValue, 32> Elts;
1334   EVT EltVT = N->getValueType(0).getVectorElementType();
1335   for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1336     SDValue Op = N->getOperand(op);
1337     for (unsigned i = 0, e = Op.getValueType().getVectorNumElements();
1338          i != e; ++i) {
1339       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
1340                                  Op, DAG.getConstant(i, TLI.getVectorIdxTy())));
1341
1342     }
1343   }
1344
1345   return DAG.getNode(ISD::BUILD_VECTOR, DL, N->getValueType(0),
1346                      &Elts[0], Elts.size());
1347 }
1348
1349 SDValue DAGTypeLegalizer::SplitVecOp_TRUNCATE(SDNode *N) {
1350   // The result type is legal, but the input type is illegal.  If splitting
1351   // ends up with the result type of each half still being legal, just
1352   // do that.  If, however, that would result in an illegal result type,
1353   // we can try to get more clever with power-two vectors. Specifically,
1354   // split the input type, but also widen the result element size, then
1355   // concatenate the halves and truncate again.  For example, consider a target
1356   // where v8i8 is legal and v8i32 is not (ARM, which doesn't have 256-bit
1357   // vectors). To perform a "%res = v8i8 trunc v8i32 %in" we do:
1358   //   %inlo = v4i32 extract_subvector %in, 0
1359   //   %inhi = v4i32 extract_subvector %in, 4
1360   //   %lo16 = v4i16 trunc v4i32 %inlo
1361   //   %hi16 = v4i16 trunc v4i32 %inhi
1362   //   %in16 = v8i16 concat_vectors v4i16 %lo16, v4i16 %hi16
1363   //   %res = v8i8 trunc v8i16 %in16
1364   //
1365   // Without this transform, the original truncate would end up being
1366   // scalarized, which is pretty much always a last resort.
1367   SDValue InVec = N->getOperand(0);
1368   EVT InVT = InVec->getValueType(0);
1369   EVT OutVT = N->getValueType(0);
1370   unsigned NumElements = OutVT.getVectorNumElements();
1371   // Widening should have already made sure this is a power-two vector
1372   // if we're trying to split it at all. assert() that's true, just in case.
1373   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
1374
1375   unsigned InElementSize = InVT.getVectorElementType().getSizeInBits();
1376   unsigned OutElementSize = OutVT.getVectorElementType().getSizeInBits();
1377
1378   // If the input elements are only 1/2 the width of the result elements,
1379   // just use the normal splitting. Our trick only work if there's room
1380   // to split more than once.
1381   if (InElementSize <= OutElementSize * 2)
1382     return SplitVecOp_UnaryOp(N);
1383   SDLoc DL(N);
1384
1385   // Extract the halves of the input via extract_subvector.
1386   SDValue InLoVec, InHiVec;
1387   std::tie(InLoVec, InHiVec) = DAG.SplitVector(InVec, DL);
1388   // Truncate them to 1/2 the element size.
1389   EVT HalfElementVT = EVT::getIntegerVT(*DAG.getContext(), InElementSize/2);
1390   EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), HalfElementVT,
1391                                 NumElements/2);
1392   SDValue HalfLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, InLoVec);
1393   SDValue HalfHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, InHiVec);
1394   // Concatenate them to get the full intermediate truncation result.
1395   EVT InterVT = EVT::getVectorVT(*DAG.getContext(), HalfElementVT, NumElements);
1396   SDValue InterVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InterVT, HalfLo,
1397                                  HalfHi);
1398   // Now finish up by truncating all the way down to the original result
1399   // type. This should normally be something that ends up being legal directly,
1400   // but in theory if a target has very wide vectors and an annoyingly
1401   // restricted set of legal types, this split can chain to build things up.
1402   return DAG.getNode(ISD::TRUNCATE, DL, OutVT, InterVec);
1403 }
1404
1405 SDValue DAGTypeLegalizer::SplitVecOp_VSETCC(SDNode *N) {
1406   assert(N->getValueType(0).isVector() &&
1407          N->getOperand(0).getValueType().isVector() &&
1408          "Operand types must be vectors");
1409   // The result has a legal vector type, but the input needs splitting.
1410   SDValue Lo0, Hi0, Lo1, Hi1, LoRes, HiRes;
1411   SDLoc DL(N);
1412   GetSplitVector(N->getOperand(0), Lo0, Hi0);
1413   GetSplitVector(N->getOperand(1), Lo1, Hi1);
1414   unsigned PartElements = Lo0.getValueType().getVectorNumElements();
1415   EVT PartResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, PartElements);
1416   EVT WideResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 2*PartElements);
1417
1418   LoRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Lo0, Lo1, N->getOperand(2));
1419   HiRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Hi0, Hi1, N->getOperand(2));
1420   SDValue Con = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideResVT, LoRes, HiRes);
1421   return PromoteTargetBoolean(Con, N->getValueType(0));
1422 }
1423
1424
1425 SDValue DAGTypeLegalizer::SplitVecOp_FP_ROUND(SDNode *N) {
1426   // The result has a legal vector type, but the input needs splitting.
1427   EVT ResVT = N->getValueType(0);
1428   SDValue Lo, Hi;
1429   SDLoc DL(N);
1430   GetSplitVector(N->getOperand(0), Lo, Hi);
1431   EVT InVT = Lo.getValueType();
1432
1433   EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
1434                                InVT.getVectorNumElements());
1435
1436   Lo = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Lo, N->getOperand(1));
1437   Hi = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Hi, N->getOperand(1));
1438
1439   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
1440 }
1441
1442
1443
1444 //===----------------------------------------------------------------------===//
1445 //  Result Vector Widening
1446 //===----------------------------------------------------------------------===//
1447
1448 void DAGTypeLegalizer::WidenVectorResult(SDNode *N, unsigned ResNo) {
1449   DEBUG(dbgs() << "Widen node result " << ResNo << ": ";
1450         N->dump(&DAG);
1451         dbgs() << "\n");
1452
1453   // See if the target wants to custom widen this node.
1454   if (CustomWidenLowerNode(N, N->getValueType(ResNo)))
1455     return;
1456
1457   SDValue Res = SDValue();
1458   switch (N->getOpcode()) {
1459   default:
1460 #ifndef NDEBUG
1461     dbgs() << "WidenVectorResult #" << ResNo << ": ";
1462     N->dump(&DAG);
1463     dbgs() << "\n";
1464 #endif
1465     llvm_unreachable("Do not know how to widen the result of this operator!");
1466
1467   case ISD::MERGE_VALUES:      Res = WidenVecRes_MERGE_VALUES(N, ResNo); break;
1468   case ISD::BITCAST:           Res = WidenVecRes_BITCAST(N); break;
1469   case ISD::BUILD_VECTOR:      Res = WidenVecRes_BUILD_VECTOR(N); break;
1470   case ISD::CONCAT_VECTORS:    Res = WidenVecRes_CONCAT_VECTORS(N); break;
1471   case ISD::CONVERT_RNDSAT:    Res = WidenVecRes_CONVERT_RNDSAT(N); break;
1472   case ISD::EXTRACT_SUBVECTOR: Res = WidenVecRes_EXTRACT_SUBVECTOR(N); break;
1473   case ISD::FP_ROUND_INREG:    Res = WidenVecRes_InregOp(N); break;
1474   case ISD::INSERT_VECTOR_ELT: Res = WidenVecRes_INSERT_VECTOR_ELT(N); break;
1475   case ISD::LOAD:              Res = WidenVecRes_LOAD(N); break;
1476   case ISD::SCALAR_TO_VECTOR:  Res = WidenVecRes_SCALAR_TO_VECTOR(N); break;
1477   case ISD::SIGN_EXTEND_INREG: Res = WidenVecRes_InregOp(N); break;
1478   case ISD::VSELECT:
1479   case ISD::SELECT:            Res = WidenVecRes_SELECT(N); break;
1480   case ISD::SELECT_CC:         Res = WidenVecRes_SELECT_CC(N); break;
1481   case ISD::SETCC:             Res = WidenVecRes_SETCC(N); break;
1482   case ISD::UNDEF:             Res = WidenVecRes_UNDEF(N); break;
1483   case ISD::VECTOR_SHUFFLE:
1484     Res = WidenVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N));
1485     break;
1486
1487   case ISD::ADD:
1488   case ISD::AND:
1489   case ISD::BSWAP:
1490   case ISD::MUL:
1491   case ISD::MULHS:
1492   case ISD::MULHU:
1493   case ISD::OR:
1494   case ISD::SUB:
1495   case ISD::XOR:
1496     Res = WidenVecRes_Binary(N);
1497     break;
1498
1499   case ISD::FADD:
1500   case ISD::FCOPYSIGN:
1501   case ISD::FMUL:
1502   case ISD::FPOW:
1503   case ISD::FSUB:
1504   case ISD::FDIV:
1505   case ISD::FREM:
1506   case ISD::SDIV:
1507   case ISD::UDIV:
1508   case ISD::SREM:
1509   case ISD::UREM:
1510     Res = WidenVecRes_BinaryCanTrap(N);
1511     break;
1512
1513   case ISD::FPOWI:
1514     Res = WidenVecRes_POWI(N);
1515     break;
1516
1517   case ISD::SHL:
1518   case ISD::SRA:
1519   case ISD::SRL:
1520     Res = WidenVecRes_Shift(N);
1521     break;
1522
1523   case ISD::ANY_EXTEND:
1524   case ISD::FP_EXTEND:
1525   case ISD::FP_ROUND:
1526   case ISD::FP_TO_SINT:
1527   case ISD::FP_TO_UINT:
1528   case ISD::SIGN_EXTEND:
1529   case ISD::SINT_TO_FP:
1530   case ISD::TRUNCATE:
1531   case ISD::UINT_TO_FP:
1532   case ISD::ZERO_EXTEND:
1533     Res = WidenVecRes_Convert(N);
1534     break;
1535
1536   case ISD::CTLZ:
1537   case ISD::CTPOP:
1538   case ISD::CTTZ:
1539   case ISD::FABS:
1540   case ISD::FCEIL:
1541   case ISD::FCOS:
1542   case ISD::FEXP:
1543   case ISD::FEXP2:
1544   case ISD::FFLOOR:
1545   case ISD::FLOG:
1546   case ISD::FLOG10:
1547   case ISD::FLOG2:
1548   case ISD::FNEARBYINT:
1549   case ISD::FNEG:
1550   case ISD::FRINT:
1551   case ISD::FROUND:
1552   case ISD::FSIN:
1553   case ISD::FSQRT:
1554   case ISD::FTRUNC:
1555     Res = WidenVecRes_Unary(N);
1556     break;
1557   case ISD::FMA:
1558     Res = WidenVecRes_Ternary(N);
1559     break;
1560   }
1561
1562   // If Res is null, the sub-method took care of registering the result.
1563   if (Res.getNode())
1564     SetWidenedVector(SDValue(N, ResNo), Res);
1565 }
1566
1567 SDValue DAGTypeLegalizer::WidenVecRes_Ternary(SDNode *N) {
1568   // Ternary op widening.
1569   SDLoc dl(N);
1570   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1571   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1572   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1573   SDValue InOp3 = GetWidenedVector(N->getOperand(2));
1574   return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2, InOp3);
1575 }
1576
1577 SDValue DAGTypeLegalizer::WidenVecRes_Binary(SDNode *N) {
1578   // Binary op widening.
1579   SDLoc dl(N);
1580   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1581   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1582   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1583   return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2);
1584 }
1585
1586 SDValue DAGTypeLegalizer::WidenVecRes_BinaryCanTrap(SDNode *N) {
1587   // Binary op widening for operations that can trap.
1588   unsigned Opcode = N->getOpcode();
1589   SDLoc dl(N);
1590   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1591   EVT WidenEltVT = WidenVT.getVectorElementType();
1592   EVT VT = WidenVT;
1593   unsigned NumElts =  VT.getVectorNumElements();
1594   while (!TLI.isTypeLegal(VT) && NumElts != 1) {
1595     NumElts = NumElts / 2;
1596     VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
1597   }
1598
1599   if (NumElts != 1 && !TLI.canOpTrap(N->getOpcode(), VT)) {
1600     // Operation doesn't trap so just widen as normal.
1601     SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1602     SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1603     return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2);
1604   }
1605
1606   // No legal vector version so unroll the vector operation and then widen.
1607   if (NumElts == 1)
1608     return DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements());
1609
1610   // Since the operation can trap, apply operation on the original vector.
1611   EVT MaxVT = VT;
1612   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1613   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1614   unsigned CurNumElts = N->getValueType(0).getVectorNumElements();
1615
1616   SmallVector<SDValue, 16> ConcatOps(CurNumElts);
1617   unsigned ConcatEnd = 0;  // Current ConcatOps index.
1618   int Idx = 0;        // Current Idx into input vectors.
1619
1620   // NumElts := greatest legal vector size (at most WidenVT)
1621   // while (orig. vector has unhandled elements) {
1622   //   take munches of size NumElts from the beginning and add to ConcatOps
1623   //   NumElts := next smaller supported vector size or 1
1624   // }
1625   while (CurNumElts != 0) {
1626     while (CurNumElts >= NumElts) {
1627       SDValue EOp1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp1,
1628                                  DAG.getConstant(Idx, TLI.getVectorIdxTy()));
1629       SDValue EOp2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp2,
1630                                  DAG.getConstant(Idx, TLI.getVectorIdxTy()));
1631       ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, VT, EOp1, EOp2);
1632       Idx += NumElts;
1633       CurNumElts -= NumElts;
1634     }
1635     do {
1636       NumElts = NumElts / 2;
1637       VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
1638     } while (!TLI.isTypeLegal(VT) && NumElts != 1);
1639
1640     if (NumElts == 1) {
1641       for (unsigned i = 0; i != CurNumElts; ++i, ++Idx) {
1642         SDValue EOp1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT,
1643                                    InOp1, DAG.getConstant(Idx,
1644                                                          TLI.getVectorIdxTy()));
1645         SDValue EOp2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT,
1646                                    InOp2, DAG.getConstant(Idx,
1647                                                          TLI.getVectorIdxTy()));
1648         ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, WidenEltVT,
1649                                              EOp1, EOp2);
1650       }
1651       CurNumElts = 0;
1652     }
1653   }
1654
1655   // Check to see if we have a single operation with the widen type.
1656   if (ConcatEnd == 1) {
1657     VT = ConcatOps[0].getValueType();
1658     if (VT == WidenVT)
1659       return ConcatOps[0];
1660   }
1661
1662   // while (Some element of ConcatOps is not of type MaxVT) {
1663   //   From the end of ConcatOps, collect elements of the same type and put
1664   //   them into an op of the next larger supported type
1665   // }
1666   while (ConcatOps[ConcatEnd-1].getValueType() != MaxVT) {
1667     Idx = ConcatEnd - 1;
1668     VT = ConcatOps[Idx--].getValueType();
1669     while (Idx >= 0 && ConcatOps[Idx].getValueType() == VT)
1670       Idx--;
1671
1672     int NextSize = VT.isVector() ? VT.getVectorNumElements() : 1;
1673     EVT NextVT;
1674     do {
1675       NextSize *= 2;
1676       NextVT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NextSize);
1677     } while (!TLI.isTypeLegal(NextVT));
1678
1679     if (!VT.isVector()) {
1680       // Scalar type, create an INSERT_VECTOR_ELEMENT of type NextVT
1681       SDValue VecOp = DAG.getUNDEF(NextVT);
1682       unsigned NumToInsert = ConcatEnd - Idx - 1;
1683       for (unsigned i = 0, OpIdx = Idx+1; i < NumToInsert; i++, OpIdx++) {
1684         VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NextVT, VecOp,
1685                             ConcatOps[OpIdx], DAG.getConstant(i,
1686                                                          TLI.getVectorIdxTy()));
1687       }
1688       ConcatOps[Idx+1] = VecOp;
1689       ConcatEnd = Idx + 2;
1690     } else {
1691       // Vector type, create a CONCAT_VECTORS of type NextVT
1692       SDValue undefVec = DAG.getUNDEF(VT);
1693       unsigned OpsToConcat = NextSize/VT.getVectorNumElements();
1694       SmallVector<SDValue, 16> SubConcatOps(OpsToConcat);
1695       unsigned RealVals = ConcatEnd - Idx - 1;
1696       unsigned SubConcatEnd = 0;
1697       unsigned SubConcatIdx = Idx + 1;
1698       while (SubConcatEnd < RealVals)
1699         SubConcatOps[SubConcatEnd++] = ConcatOps[++Idx];
1700       while (SubConcatEnd < OpsToConcat)
1701         SubConcatOps[SubConcatEnd++] = undefVec;
1702       ConcatOps[SubConcatIdx] = DAG.getNode(ISD::CONCAT_VECTORS, dl,
1703                                             NextVT, &SubConcatOps[0],
1704                                             OpsToConcat);
1705       ConcatEnd = SubConcatIdx + 1;
1706     }
1707   }
1708
1709   // Check to see if we have a single operation with the widen type.
1710   if (ConcatEnd == 1) {
1711     VT = ConcatOps[0].getValueType();
1712     if (VT == WidenVT)
1713       return ConcatOps[0];
1714   }
1715
1716   // add undefs of size MaxVT until ConcatOps grows to length of WidenVT
1717   unsigned NumOps = WidenVT.getVectorNumElements()/MaxVT.getVectorNumElements();
1718   if (NumOps != ConcatEnd ) {
1719     SDValue UndefVal = DAG.getUNDEF(MaxVT);
1720     for (unsigned j = ConcatEnd; j < NumOps; ++j)
1721       ConcatOps[j] = UndefVal;
1722   }
1723   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0], NumOps);
1724 }
1725
1726 SDValue DAGTypeLegalizer::WidenVecRes_Convert(SDNode *N) {
1727   SDValue InOp = N->getOperand(0);
1728   SDLoc DL(N);
1729
1730   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1731   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1732
1733   EVT InVT = InOp.getValueType();
1734   EVT InEltVT = InVT.getVectorElementType();
1735   EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts);
1736
1737   unsigned Opcode = N->getOpcode();
1738   unsigned InVTNumElts = InVT.getVectorNumElements();
1739
1740   if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
1741     InOp = GetWidenedVector(N->getOperand(0));
1742     InVT = InOp.getValueType();
1743     InVTNumElts = InVT.getVectorNumElements();
1744     if (InVTNumElts == WidenNumElts) {
1745       if (N->getNumOperands() == 1)
1746         return DAG.getNode(Opcode, DL, WidenVT, InOp);
1747       return DAG.getNode(Opcode, DL, WidenVT, InOp, N->getOperand(1));
1748     }
1749   }
1750
1751   if (TLI.isTypeLegal(InWidenVT)) {
1752     // Because the result and the input are different vector types, widening
1753     // the result could create a legal type but widening the input might make
1754     // it an illegal type that might lead to repeatedly splitting the input
1755     // and then widening it. To avoid this, we widen the input only if
1756     // it results in a legal type.
1757     if (WidenNumElts % InVTNumElts == 0) {
1758       // Widen the input and call convert on the widened input vector.
1759       unsigned NumConcat = WidenNumElts/InVTNumElts;
1760       SmallVector<SDValue, 16> Ops(NumConcat);
1761       Ops[0] = InOp;
1762       SDValue UndefVal = DAG.getUNDEF(InVT);
1763       for (unsigned i = 1; i != NumConcat; ++i)
1764         Ops[i] = UndefVal;
1765       SDValue InVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InWidenVT,
1766                                   &Ops[0], NumConcat);
1767       if (N->getNumOperands() == 1)
1768         return DAG.getNode(Opcode, DL, WidenVT, InVec);
1769       return DAG.getNode(Opcode, DL, WidenVT, InVec, N->getOperand(1));
1770     }
1771
1772     if (InVTNumElts % WidenNumElts == 0) {
1773       SDValue InVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InWidenVT,
1774                                   InOp, DAG.getConstant(0,
1775                                                         TLI.getVectorIdxTy()));
1776       // Extract the input and convert the shorten input vector.
1777       if (N->getNumOperands() == 1)
1778         return DAG.getNode(Opcode, DL, WidenVT, InVal);
1779       return DAG.getNode(Opcode, DL, WidenVT, InVal, N->getOperand(1));
1780     }
1781   }
1782
1783   // Otherwise unroll into some nasty scalar code and rebuild the vector.
1784   SmallVector<SDValue, 16> Ops(WidenNumElts);
1785   EVT EltVT = WidenVT.getVectorElementType();
1786   unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
1787   unsigned i;
1788   for (i=0; i < MinElts; ++i) {
1789     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, InEltVT, InOp,
1790                               DAG.getConstant(i, TLI.getVectorIdxTy()));
1791     if (N->getNumOperands() == 1)
1792       Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val);
1793     else
1794       Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val, N->getOperand(1));
1795   }
1796
1797   SDValue UndefVal = DAG.getUNDEF(EltVT);
1798   for (; i < WidenNumElts; ++i)
1799     Ops[i] = UndefVal;
1800
1801   return DAG.getNode(ISD::BUILD_VECTOR, DL, WidenVT, &Ops[0], WidenNumElts);
1802 }
1803
1804 SDValue DAGTypeLegalizer::WidenVecRes_POWI(SDNode *N) {
1805   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1806   SDValue InOp = GetWidenedVector(N->getOperand(0));
1807   SDValue ShOp = N->getOperand(1);
1808   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp, ShOp);
1809 }
1810
1811 SDValue DAGTypeLegalizer::WidenVecRes_Shift(SDNode *N) {
1812   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1813   SDValue InOp = GetWidenedVector(N->getOperand(0));
1814   SDValue ShOp = N->getOperand(1);
1815
1816   EVT ShVT = ShOp.getValueType();
1817   if (getTypeAction(ShVT) == TargetLowering::TypeWidenVector) {
1818     ShOp = GetWidenedVector(ShOp);
1819     ShVT = ShOp.getValueType();
1820   }
1821   EVT ShWidenVT = EVT::getVectorVT(*DAG.getContext(),
1822                                    ShVT.getVectorElementType(),
1823                                    WidenVT.getVectorNumElements());
1824   if (ShVT != ShWidenVT)
1825     ShOp = ModifyToType(ShOp, ShWidenVT);
1826
1827   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp, ShOp);
1828 }
1829
1830 SDValue DAGTypeLegalizer::WidenVecRes_Unary(SDNode *N) {
1831   // Unary op widening.
1832   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1833   SDValue InOp = GetWidenedVector(N->getOperand(0));
1834   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp);
1835 }
1836
1837 SDValue DAGTypeLegalizer::WidenVecRes_InregOp(SDNode *N) {
1838   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1839   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
1840                                cast<VTSDNode>(N->getOperand(1))->getVT()
1841                                  .getVectorElementType(),
1842                                WidenVT.getVectorNumElements());
1843   SDValue WidenLHS = GetWidenedVector(N->getOperand(0));
1844   return DAG.getNode(N->getOpcode(), SDLoc(N),
1845                      WidenVT, WidenLHS, DAG.getValueType(ExtVT));
1846 }
1847
1848 SDValue DAGTypeLegalizer::WidenVecRes_MERGE_VALUES(SDNode *N, unsigned ResNo) {
1849   SDValue WidenVec = DisintegrateMERGE_VALUES(N, ResNo);
1850   return GetWidenedVector(WidenVec);
1851 }
1852
1853 SDValue DAGTypeLegalizer::WidenVecRes_BITCAST(SDNode *N) {
1854   SDValue InOp = N->getOperand(0);
1855   EVT InVT = InOp.getValueType();
1856   EVT VT = N->getValueType(0);
1857   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1858   SDLoc dl(N);
1859
1860   switch (getTypeAction(InVT)) {
1861   case TargetLowering::TypeLegal:
1862     break;
1863   case TargetLowering::TypePromoteInteger:
1864     // If the incoming type is a vector that is being promoted, then
1865     // we know that the elements are arranged differently and that we
1866     // must perform the conversion using a stack slot.
1867     if (InVT.isVector())
1868       break;
1869
1870     // If the InOp is promoted to the same size, convert it.  Otherwise,
1871     // fall out of the switch and widen the promoted input.
1872     InOp = GetPromotedInteger(InOp);
1873     InVT = InOp.getValueType();
1874     if (WidenVT.bitsEq(InVT))
1875       return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
1876     break;
1877   case TargetLowering::TypeSoftenFloat:
1878   case TargetLowering::TypeExpandInteger:
1879   case TargetLowering::TypeExpandFloat:
1880   case TargetLowering::TypeScalarizeVector:
1881   case TargetLowering::TypeSplitVector:
1882     break;
1883   case TargetLowering::TypeWidenVector:
1884     // If the InOp is widened to the same size, convert it.  Otherwise, fall
1885     // out of the switch and widen the widened input.
1886     InOp = GetWidenedVector(InOp);
1887     InVT = InOp.getValueType();
1888     if (WidenVT.bitsEq(InVT))
1889       // The input widens to the same size. Convert to the widen value.
1890       return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
1891     break;
1892   }
1893
1894   unsigned WidenSize = WidenVT.getSizeInBits();
1895   unsigned InSize = InVT.getSizeInBits();
1896   // x86mmx is not an acceptable vector element type, so don't try.
1897   if (WidenSize % InSize == 0 && InVT != MVT::x86mmx) {
1898     // Determine new input vector type.  The new input vector type will use
1899     // the same element type (if its a vector) or use the input type as a
1900     // vector.  It is the same size as the type to widen to.
1901     EVT NewInVT;
1902     unsigned NewNumElts = WidenSize / InSize;
1903     if (InVT.isVector()) {
1904       EVT InEltVT = InVT.getVectorElementType();
1905       NewInVT = EVT::getVectorVT(*DAG.getContext(), InEltVT,
1906                                  WidenSize / InEltVT.getSizeInBits());
1907     } else {
1908       NewInVT = EVT::getVectorVT(*DAG.getContext(), InVT, NewNumElts);
1909     }
1910
1911     if (TLI.isTypeLegal(NewInVT)) {
1912       // Because the result and the input are different vector types, widening
1913       // the result could create a legal type but widening the input might make
1914       // it an illegal type that might lead to repeatedly splitting the input
1915       // and then widening it. To avoid this, we widen the input only if
1916       // it results in a legal type.
1917       SmallVector<SDValue, 16> Ops(NewNumElts);
1918       SDValue UndefVal = DAG.getUNDEF(InVT);
1919       Ops[0] = InOp;
1920       for (unsigned i = 1; i < NewNumElts; ++i)
1921         Ops[i] = UndefVal;
1922
1923       SDValue NewVec;
1924       if (InVT.isVector())
1925         NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl,
1926                              NewInVT, &Ops[0], NewNumElts);
1927       else
1928         NewVec = DAG.getNode(ISD::BUILD_VECTOR, dl,
1929                              NewInVT, &Ops[0], NewNumElts);
1930       return DAG.getNode(ISD::BITCAST, dl, WidenVT, NewVec);
1931     }
1932   }
1933
1934   return CreateStackStoreLoad(InOp, WidenVT);
1935 }
1936
1937 SDValue DAGTypeLegalizer::WidenVecRes_BUILD_VECTOR(SDNode *N) {
1938   SDLoc dl(N);
1939   // Build a vector with undefined for the new nodes.
1940   EVT VT = N->getValueType(0);
1941
1942   // Integer BUILD_VECTOR operands may be larger than the node's vector element
1943   // type. The UNDEFs need to have the same type as the existing operands.
1944   EVT EltVT = N->getOperand(0).getValueType();
1945   unsigned NumElts = VT.getVectorNumElements();
1946
1947   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1948   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1949
1950   SmallVector<SDValue, 16> NewOps(N->op_begin(), N->op_end());
1951   assert(WidenNumElts >= NumElts && "Shrinking vector instead of widening!");
1952   NewOps.append(WidenNumElts - NumElts, DAG.getUNDEF(EltVT));
1953
1954   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &NewOps[0], NewOps.size());
1955 }
1956
1957 SDValue DAGTypeLegalizer::WidenVecRes_CONCAT_VECTORS(SDNode *N) {
1958   EVT InVT = N->getOperand(0).getValueType();
1959   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1960   SDLoc dl(N);
1961   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1962   unsigned NumInElts = InVT.getVectorNumElements();
1963   unsigned NumOperands = N->getNumOperands();
1964
1965   bool InputWidened = false; // Indicates we need to widen the input.
1966   if (getTypeAction(InVT) != TargetLowering::TypeWidenVector) {
1967     if (WidenVT.getVectorNumElements() % InVT.getVectorNumElements() == 0) {
1968       // Add undef vectors to widen to correct length.
1969       unsigned NumConcat = WidenVT.getVectorNumElements() /
1970                            InVT.getVectorNumElements();
1971       SDValue UndefVal = DAG.getUNDEF(InVT);
1972       SmallVector<SDValue, 16> Ops(NumConcat);
1973       for (unsigned i=0; i < NumOperands; ++i)
1974         Ops[i] = N->getOperand(i);
1975       for (unsigned i = NumOperands; i != NumConcat; ++i)
1976         Ops[i] = UndefVal;
1977       return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &Ops[0], NumConcat);
1978     }
1979   } else {
1980     InputWidened = true;
1981     if (WidenVT == TLI.getTypeToTransformTo(*DAG.getContext(), InVT)) {
1982       // The inputs and the result are widen to the same value.
1983       unsigned i;
1984       for (i=1; i < NumOperands; ++i)
1985         if (N->getOperand(i).getOpcode() != ISD::UNDEF)
1986           break;
1987
1988       if (i == NumOperands)
1989         // Everything but the first operand is an UNDEF so just return the
1990         // widened first operand.
1991         return GetWidenedVector(N->getOperand(0));
1992
1993       if (NumOperands == 2) {
1994         // Replace concat of two operands with a shuffle.
1995         SmallVector<int, 16> MaskOps(WidenNumElts, -1);
1996         for (unsigned i = 0; i < NumInElts; ++i) {
1997           MaskOps[i] = i;
1998           MaskOps[i + NumInElts] = i + WidenNumElts;
1999         }
2000         return DAG.getVectorShuffle(WidenVT, dl,
2001                                     GetWidenedVector(N->getOperand(0)),
2002                                     GetWidenedVector(N->getOperand(1)),
2003                                     &MaskOps[0]);
2004       }
2005     }
2006   }
2007
2008   // Fall back to use extracts and build vector.
2009   EVT EltVT = WidenVT.getVectorElementType();
2010   SmallVector<SDValue, 16> Ops(WidenNumElts);
2011   unsigned Idx = 0;
2012   for (unsigned i=0; i < NumOperands; ++i) {
2013     SDValue InOp = N->getOperand(i);
2014     if (InputWidened)
2015       InOp = GetWidenedVector(InOp);
2016     for (unsigned j=0; j < NumInElts; ++j)
2017       Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2018                                DAG.getConstant(j, TLI.getVectorIdxTy()));
2019   }
2020   SDValue UndefVal = DAG.getUNDEF(EltVT);
2021   for (; Idx < WidenNumElts; ++Idx)
2022     Ops[Idx] = UndefVal;
2023   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
2024 }
2025
2026 SDValue DAGTypeLegalizer::WidenVecRes_CONVERT_RNDSAT(SDNode *N) {
2027   SDLoc dl(N);
2028   SDValue InOp  = N->getOperand(0);
2029   SDValue RndOp = N->getOperand(3);
2030   SDValue SatOp = N->getOperand(4);
2031
2032   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2033   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2034
2035   EVT InVT = InOp.getValueType();
2036   EVT InEltVT = InVT.getVectorElementType();
2037   EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts);
2038
2039   SDValue DTyOp = DAG.getValueType(WidenVT);
2040   SDValue STyOp = DAG.getValueType(InWidenVT);
2041   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
2042
2043   unsigned InVTNumElts = InVT.getVectorNumElements();
2044   if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
2045     InOp = GetWidenedVector(InOp);
2046     InVT = InOp.getValueType();
2047     InVTNumElts = InVT.getVectorNumElements();
2048     if (InVTNumElts == WidenNumElts)
2049       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
2050                                   SatOp, CvtCode);
2051   }
2052
2053   if (TLI.isTypeLegal(InWidenVT)) {
2054     // Because the result and the input are different vector types, widening
2055     // the result could create a legal type but widening the input might make
2056     // it an illegal type that might lead to repeatedly splitting the input
2057     // and then widening it. To avoid this, we widen the input only if
2058     // it results in a legal type.
2059     if (WidenNumElts % InVTNumElts == 0) {
2060       // Widen the input and call convert on the widened input vector.
2061       unsigned NumConcat = WidenNumElts/InVTNumElts;
2062       SmallVector<SDValue, 16> Ops(NumConcat);
2063       Ops[0] = InOp;
2064       SDValue UndefVal = DAG.getUNDEF(InVT);
2065       for (unsigned i = 1; i != NumConcat; ++i)
2066         Ops[i] = UndefVal;
2067
2068       InOp = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWidenVT, &Ops[0],NumConcat);
2069       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
2070                                   SatOp, CvtCode);
2071     }
2072
2073     if (InVTNumElts % WidenNumElts == 0) {
2074       // Extract the input and convert the shorten input vector.
2075       InOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InWidenVT, InOp,
2076                          DAG.getConstant(0, TLI.getVectorIdxTy()));
2077       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
2078                                   SatOp, CvtCode);
2079     }
2080   }
2081
2082   // Otherwise unroll into some nasty scalar code and rebuild the vector.
2083   SmallVector<SDValue, 16> Ops(WidenNumElts);
2084   EVT EltVT = WidenVT.getVectorElementType();
2085   DTyOp = DAG.getValueType(EltVT);
2086   STyOp = DAG.getValueType(InEltVT);
2087
2088   unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
2089   unsigned i;
2090   for (i=0; i < MinElts; ++i) {
2091     SDValue ExtVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
2092                                  DAG.getConstant(i, TLI.getVectorIdxTy()));
2093     Ops[i] = DAG.getConvertRndSat(WidenVT, dl, ExtVal, DTyOp, STyOp, RndOp,
2094                                   SatOp, CvtCode);
2095   }
2096
2097   SDValue UndefVal = DAG.getUNDEF(EltVT);
2098   for (; i < WidenNumElts; ++i)
2099     Ops[i] = UndefVal;
2100
2101   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
2102 }
2103
2104 SDValue DAGTypeLegalizer::WidenVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
2105   EVT      VT = N->getValueType(0);
2106   EVT      WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2107   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2108   SDValue  InOp = N->getOperand(0);
2109   SDValue  Idx  = N->getOperand(1);
2110   SDLoc dl(N);
2111
2112   if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
2113     InOp = GetWidenedVector(InOp);
2114
2115   EVT InVT = InOp.getValueType();
2116
2117   // Check if we can just return the input vector after widening.
2118   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
2119   if (IdxVal == 0 && InVT == WidenVT)
2120     return InOp;
2121
2122   // Check if we can extract from the vector.
2123   unsigned InNumElts = InVT.getVectorNumElements();
2124   if (IdxVal % WidenNumElts == 0 && IdxVal + WidenNumElts < InNumElts)
2125     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, InOp, Idx);
2126
2127   // We could try widening the input to the right length but for now, extract
2128   // the original elements, fill the rest with undefs and build a vector.
2129   SmallVector<SDValue, 16> Ops(WidenNumElts);
2130   EVT EltVT = VT.getVectorElementType();
2131   unsigned NumElts = VT.getVectorNumElements();
2132   unsigned i;
2133   for (i=0; i < NumElts; ++i)
2134     Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2135                          DAG.getConstant(IdxVal+i, TLI.getVectorIdxTy()));
2136
2137   SDValue UndefVal = DAG.getUNDEF(EltVT);
2138   for (; i < WidenNumElts; ++i)
2139     Ops[i] = UndefVal;
2140   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
2141 }
2142
2143 SDValue DAGTypeLegalizer::WidenVecRes_INSERT_VECTOR_ELT(SDNode *N) {
2144   SDValue InOp = GetWidenedVector(N->getOperand(0));
2145   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N),
2146                      InOp.getValueType(), InOp,
2147                      N->getOperand(1), N->getOperand(2));
2148 }
2149
2150 SDValue DAGTypeLegalizer::WidenVecRes_LOAD(SDNode *N) {
2151   LoadSDNode *LD = cast<LoadSDNode>(N);
2152   ISD::LoadExtType ExtType = LD->getExtensionType();
2153
2154   SDValue Result;
2155   SmallVector<SDValue, 16> LdChain;  // Chain for the series of load
2156   if (ExtType != ISD::NON_EXTLOAD)
2157     Result = GenWidenVectorExtLoads(LdChain, LD, ExtType);
2158   else
2159     Result = GenWidenVectorLoads(LdChain, LD);
2160
2161   // If we generate a single load, we can use that for the chain.  Otherwise,
2162   // build a factor node to remember the multiple loads are independent and
2163   // chain to that.
2164   SDValue NewChain;
2165   if (LdChain.size() == 1)
2166     NewChain = LdChain[0];
2167   else
2168     NewChain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
2169                            &LdChain[0], LdChain.size());
2170
2171   // Modified the chain - switch anything that used the old chain to use
2172   // the new one.
2173   ReplaceValueWith(SDValue(N, 1), NewChain);
2174
2175   return Result;
2176 }
2177
2178 SDValue DAGTypeLegalizer::WidenVecRes_SCALAR_TO_VECTOR(SDNode *N) {
2179   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2180   return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N),
2181                      WidenVT, N->getOperand(0));
2182 }
2183
2184 SDValue DAGTypeLegalizer::WidenVecRes_SELECT(SDNode *N) {
2185   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2186   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2187
2188   SDValue Cond1 = N->getOperand(0);
2189   EVT CondVT = Cond1.getValueType();
2190   if (CondVT.isVector()) {
2191     EVT CondEltVT = CondVT.getVectorElementType();
2192     EVT CondWidenVT =  EVT::getVectorVT(*DAG.getContext(),
2193                                         CondEltVT, WidenNumElts);
2194     if (getTypeAction(CondVT) == TargetLowering::TypeWidenVector)
2195       Cond1 = GetWidenedVector(Cond1);
2196
2197     // If we have to split the condition there is no point in widening the
2198     // select. This would result in an cycle of widening the select ->
2199     // widening the condition operand -> splitting the condition operand ->
2200     // splitting the select -> widening the select. Instead split this select
2201     // further and widen the resulting type.
2202     if (getTypeAction(CondVT) == TargetLowering::TypeSplitVector) {
2203       SDValue SplitSelect = SplitVecOp_VSELECT(N, 0);
2204       SDValue Res = ModifyToType(SplitSelect, WidenVT);
2205       return Res;
2206     }
2207
2208     if (Cond1.getValueType() != CondWidenVT)
2209       Cond1 = ModifyToType(Cond1, CondWidenVT);
2210   }
2211
2212   SDValue InOp1 = GetWidenedVector(N->getOperand(1));
2213   SDValue InOp2 = GetWidenedVector(N->getOperand(2));
2214   assert(InOp1.getValueType() == WidenVT && InOp2.getValueType() == WidenVT);
2215   return DAG.getNode(N->getOpcode(), SDLoc(N),
2216                      WidenVT, Cond1, InOp1, InOp2);
2217 }
2218
2219 SDValue DAGTypeLegalizer::WidenVecRes_SELECT_CC(SDNode *N) {
2220   SDValue InOp1 = GetWidenedVector(N->getOperand(2));
2221   SDValue InOp2 = GetWidenedVector(N->getOperand(3));
2222   return DAG.getNode(ISD::SELECT_CC, SDLoc(N),
2223                      InOp1.getValueType(), N->getOperand(0),
2224                      N->getOperand(1), InOp1, InOp2, N->getOperand(4));
2225 }
2226
2227 SDValue DAGTypeLegalizer::WidenVecRes_SETCC(SDNode *N) {
2228   assert(N->getValueType(0).isVector() ==
2229          N->getOperand(0).getValueType().isVector() &&
2230          "Scalar/Vector type mismatch");
2231   if (N->getValueType(0).isVector()) return WidenVecRes_VSETCC(N);
2232
2233   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2234   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2235   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2236   return DAG.getNode(ISD::SETCC, SDLoc(N), WidenVT,
2237                      InOp1, InOp2, N->getOperand(2));
2238 }
2239
2240 SDValue DAGTypeLegalizer::WidenVecRes_UNDEF(SDNode *N) {
2241  EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2242  return DAG.getUNDEF(WidenVT);
2243 }
2244
2245 SDValue DAGTypeLegalizer::WidenVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N) {
2246   EVT VT = N->getValueType(0);
2247   SDLoc dl(N);
2248
2249   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2250   unsigned NumElts = VT.getVectorNumElements();
2251   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2252
2253   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2254   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2255
2256   // Adjust mask based on new input vector length.
2257   SmallVector<int, 16> NewMask;
2258   for (unsigned i = 0; i != NumElts; ++i) {
2259     int Idx = N->getMaskElt(i);
2260     if (Idx < (int)NumElts)
2261       NewMask.push_back(Idx);
2262     else
2263       NewMask.push_back(Idx - NumElts + WidenNumElts);
2264   }
2265   for (unsigned i = NumElts; i != WidenNumElts; ++i)
2266     NewMask.push_back(-1);
2267   return DAG.getVectorShuffle(WidenVT, dl, InOp1, InOp2, &NewMask[0]);
2268 }
2269
2270 SDValue DAGTypeLegalizer::WidenVecRes_VSETCC(SDNode *N) {
2271   assert(N->getValueType(0).isVector() &&
2272          N->getOperand(0).getValueType().isVector() &&
2273          "Operands must be vectors");
2274   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2275   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2276
2277   SDValue InOp1 = N->getOperand(0);
2278   EVT InVT = InOp1.getValueType();
2279   assert(InVT.isVector() && "can not widen non-vector type");
2280   EVT WidenInVT = EVT::getVectorVT(*DAG.getContext(),
2281                                    InVT.getVectorElementType(), WidenNumElts);
2282   InOp1 = GetWidenedVector(InOp1);
2283   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2284
2285   // Assume that the input and output will be widen appropriately.  If not,
2286   // we will have to unroll it at some point.
2287   assert(InOp1.getValueType() == WidenInVT &&
2288          InOp2.getValueType() == WidenInVT &&
2289          "Input not widened to expected type!");
2290   (void)WidenInVT;
2291   return DAG.getNode(ISD::SETCC, SDLoc(N),
2292                      WidenVT, InOp1, InOp2, N->getOperand(2));
2293 }
2294
2295
2296 //===----------------------------------------------------------------------===//
2297 // Widen Vector Operand
2298 //===----------------------------------------------------------------------===//
2299 bool DAGTypeLegalizer::WidenVectorOperand(SDNode *N, unsigned OpNo) {
2300   DEBUG(dbgs() << "Widen node operand " << OpNo << ": ";
2301         N->dump(&DAG);
2302         dbgs() << "\n");
2303   SDValue Res = SDValue();
2304
2305   // See if the target wants to custom widen this node.
2306   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2307     return false;
2308
2309   switch (N->getOpcode()) {
2310   default:
2311 #ifndef NDEBUG
2312     dbgs() << "WidenVectorOperand op #" << OpNo << ": ";
2313     N->dump(&DAG);
2314     dbgs() << "\n";
2315 #endif
2316     llvm_unreachable("Do not know how to widen this operator's operand!");
2317
2318   case ISD::BITCAST:            Res = WidenVecOp_BITCAST(N); break;
2319   case ISD::CONCAT_VECTORS:     Res = WidenVecOp_CONCAT_VECTORS(N); break;
2320   case ISD::EXTRACT_SUBVECTOR:  Res = WidenVecOp_EXTRACT_SUBVECTOR(N); break;
2321   case ISD::EXTRACT_VECTOR_ELT: Res = WidenVecOp_EXTRACT_VECTOR_ELT(N); break;
2322   case ISD::STORE:              Res = WidenVecOp_STORE(N); break;
2323   case ISD::SETCC:              Res = WidenVecOp_SETCC(N); break;
2324
2325   case ISD::FP_EXTEND:
2326   case ISD::FP_TO_SINT:
2327   case ISD::FP_TO_UINT:
2328   case ISD::SINT_TO_FP:
2329   case ISD::UINT_TO_FP:
2330   case ISD::TRUNCATE:
2331   case ISD::SIGN_EXTEND:
2332   case ISD::ZERO_EXTEND:
2333   case ISD::ANY_EXTEND:
2334     Res = WidenVecOp_Convert(N);
2335     break;
2336   }
2337
2338   // If Res is null, the sub-method took care of registering the result.
2339   if (!Res.getNode()) return false;
2340
2341   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2342   // core about this.
2343   if (Res.getNode() == N)
2344     return true;
2345
2346
2347   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2348          "Invalid operand expansion");
2349
2350   ReplaceValueWith(SDValue(N, 0), Res);
2351   return false;
2352 }
2353
2354 SDValue DAGTypeLegalizer::WidenVecOp_Convert(SDNode *N) {
2355   // Since the result is legal and the input is illegal, it is unlikely
2356   // that we can fix the input to a legal type so unroll the convert
2357   // into some scalar code and create a nasty build vector.
2358   EVT VT = N->getValueType(0);
2359   EVT EltVT = VT.getVectorElementType();
2360   SDLoc dl(N);
2361   unsigned NumElts = VT.getVectorNumElements();
2362   SDValue InOp = N->getOperand(0);
2363   if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
2364     InOp = GetWidenedVector(InOp);
2365   EVT InVT = InOp.getValueType();
2366   EVT InEltVT = InVT.getVectorElementType();
2367
2368   unsigned Opcode = N->getOpcode();
2369   SmallVector<SDValue, 16> Ops(NumElts);
2370   for (unsigned i=0; i < NumElts; ++i)
2371     Ops[i] = DAG.getNode(Opcode, dl, EltVT,
2372                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
2373                                      DAG.getConstant(i, TLI.getVectorIdxTy())));
2374
2375   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts);
2376 }
2377
2378 SDValue DAGTypeLegalizer::WidenVecOp_BITCAST(SDNode *N) {
2379   EVT VT = N->getValueType(0);
2380   SDValue InOp = GetWidenedVector(N->getOperand(0));
2381   EVT InWidenVT = InOp.getValueType();
2382   SDLoc dl(N);
2383
2384   // Check if we can convert between two legal vector types and extract.
2385   unsigned InWidenSize = InWidenVT.getSizeInBits();
2386   unsigned Size = VT.getSizeInBits();
2387   // x86mmx is not an acceptable vector element type, so don't try.
2388   if (InWidenSize % Size == 0 && !VT.isVector() && VT != MVT::x86mmx) {
2389     unsigned NewNumElts = InWidenSize / Size;
2390     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), VT, NewNumElts);
2391     if (TLI.isTypeLegal(NewVT)) {
2392       SDValue BitOp = DAG.getNode(ISD::BITCAST, dl, NewVT, InOp);
2393       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, BitOp,
2394                          DAG.getConstant(0, TLI.getVectorIdxTy()));
2395     }
2396   }
2397
2398   return CreateStackStoreLoad(InOp, VT);
2399 }
2400
2401 SDValue DAGTypeLegalizer::WidenVecOp_CONCAT_VECTORS(SDNode *N) {
2402   // If the input vector is not legal, it is likely that we will not find a
2403   // legal vector of the same size. Replace the concatenate vector with a
2404   // nasty build vector.
2405   EVT VT = N->getValueType(0);
2406   EVT EltVT = VT.getVectorElementType();
2407   SDLoc dl(N);
2408   unsigned NumElts = VT.getVectorNumElements();
2409   SmallVector<SDValue, 16> Ops(NumElts);
2410
2411   EVT InVT = N->getOperand(0).getValueType();
2412   unsigned NumInElts = InVT.getVectorNumElements();
2413
2414   unsigned Idx = 0;
2415   unsigned NumOperands = N->getNumOperands();
2416   for (unsigned i=0; i < NumOperands; ++i) {
2417     SDValue InOp = N->getOperand(i);
2418     if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
2419       InOp = GetWidenedVector(InOp);
2420     for (unsigned j=0; j < NumInElts; ++j)
2421       Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2422                                DAG.getConstant(j, TLI.getVectorIdxTy()));
2423   }
2424   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts);
2425 }
2426
2427 SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
2428   SDValue InOp = GetWidenedVector(N->getOperand(0));
2429   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N),
2430                      N->getValueType(0), InOp, N->getOperand(1));
2431 }
2432
2433 SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
2434   SDValue InOp = GetWidenedVector(N->getOperand(0));
2435   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N),
2436                      N->getValueType(0), InOp, N->getOperand(1));
2437 }
2438
2439 SDValue DAGTypeLegalizer::WidenVecOp_STORE(SDNode *N) {
2440   // We have to widen the value but we want only to store the original
2441   // vector type.
2442   StoreSDNode *ST = cast<StoreSDNode>(N);
2443
2444   SmallVector<SDValue, 16> StChain;
2445   if (ST->isTruncatingStore())
2446     GenWidenVectorTruncStores(StChain, ST);
2447   else
2448     GenWidenVectorStores(StChain, ST);
2449
2450   if (StChain.size() == 1)
2451     return StChain[0];
2452   else
2453     return DAG.getNode(ISD::TokenFactor, SDLoc(ST),
2454                        MVT::Other,&StChain[0],StChain.size());
2455 }
2456
2457 SDValue DAGTypeLegalizer::WidenVecOp_SETCC(SDNode *N) {
2458   SDValue InOp0 = GetWidenedVector(N->getOperand(0));
2459   SDValue InOp1 = GetWidenedVector(N->getOperand(1));
2460   SDLoc dl(N);
2461
2462   // WARNING: In this code we widen the compare instruction with garbage.
2463   // This garbage may contain denormal floats which may be slow. Is this a real
2464   // concern ? Should we zero the unused lanes if this is a float compare ?
2465
2466   // Get a new SETCC node to compare the newly widened operands.
2467   // Only some of the compared elements are legal.
2468   EVT SVT = TLI.getSetCCResultType(*DAG.getContext(), InOp0.getValueType());
2469   SDValue WideSETCC = DAG.getNode(ISD::SETCC, SDLoc(N),
2470                      SVT, InOp0, InOp1, N->getOperand(2));
2471
2472   // Extract the needed results from the result vector.
2473   EVT ResVT = EVT::getVectorVT(*DAG.getContext(),
2474                                SVT.getVectorElementType(),
2475                                N->getValueType(0).getVectorNumElements());
2476   SDValue CC = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
2477                            ResVT, WideSETCC, DAG.getConstant(0,
2478                                              TLI.getVectorIdxTy()));
2479
2480   return PromoteTargetBoolean(CC, N->getValueType(0));
2481 }
2482
2483
2484 //===----------------------------------------------------------------------===//
2485 // Vector Widening Utilities
2486 //===----------------------------------------------------------------------===//
2487
2488 // Utility function to find the type to chop up a widen vector for load/store
2489 //  TLI:       Target lowering used to determine legal types.
2490 //  Width:     Width left need to load/store.
2491 //  WidenVT:   The widen vector type to load to/store from
2492 //  Align:     If 0, don't allow use of a wider type
2493 //  WidenEx:   If Align is not 0, the amount additional we can load/store from.
2494
2495 static EVT FindMemType(SelectionDAG& DAG, const TargetLowering &TLI,
2496                        unsigned Width, EVT WidenVT,
2497                        unsigned Align = 0, unsigned WidenEx = 0) {
2498   EVT WidenEltVT = WidenVT.getVectorElementType();
2499   unsigned WidenWidth = WidenVT.getSizeInBits();
2500   unsigned WidenEltWidth = WidenEltVT.getSizeInBits();
2501   unsigned AlignInBits = Align*8;
2502
2503   // If we have one element to load/store, return it.
2504   EVT RetVT = WidenEltVT;
2505   if (Width == WidenEltWidth)
2506     return RetVT;
2507
2508   // See if there is larger legal integer than the element type to load/store
2509   unsigned VT;
2510   for (VT = (unsigned)MVT::LAST_INTEGER_VALUETYPE;
2511        VT >= (unsigned)MVT::FIRST_INTEGER_VALUETYPE; --VT) {
2512     EVT MemVT((MVT::SimpleValueType) VT);
2513     unsigned MemVTWidth = MemVT.getSizeInBits();
2514     if (MemVT.getSizeInBits() <= WidenEltWidth)
2515       break;
2516     if (TLI.isTypeLegal(MemVT) && (WidenWidth % MemVTWidth) == 0 &&
2517         isPowerOf2_32(WidenWidth / MemVTWidth) &&
2518         (MemVTWidth <= Width ||
2519          (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
2520       RetVT = MemVT;
2521       break;
2522     }
2523   }
2524
2525   // See if there is a larger vector type to load/store that has the same vector
2526   // element type and is evenly divisible with the WidenVT.
2527   for (VT = (unsigned)MVT::LAST_VECTOR_VALUETYPE;
2528        VT >= (unsigned)MVT::FIRST_VECTOR_VALUETYPE; --VT) {
2529     EVT MemVT = (MVT::SimpleValueType) VT;
2530     unsigned MemVTWidth = MemVT.getSizeInBits();
2531     if (TLI.isTypeLegal(MemVT) && WidenEltVT == MemVT.getVectorElementType() &&
2532         (WidenWidth % MemVTWidth) == 0 &&
2533         isPowerOf2_32(WidenWidth / MemVTWidth) &&
2534         (MemVTWidth <= Width ||
2535          (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
2536       if (RetVT.getSizeInBits() < MemVTWidth || MemVT == WidenVT)
2537         return MemVT;
2538     }
2539   }
2540
2541   return RetVT;
2542 }
2543
2544 // Builds a vector type from scalar loads
2545 //  VecTy: Resulting Vector type
2546 //  LDOps: Load operators to build a vector type
2547 //  [Start,End) the list of loads to use.
2548 static SDValue BuildVectorFromScalar(SelectionDAG& DAG, EVT VecTy,
2549                                      SmallVectorImpl<SDValue> &LdOps,
2550                                      unsigned Start, unsigned End) {
2551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2552   SDLoc dl(LdOps[Start]);
2553   EVT LdTy = LdOps[Start].getValueType();
2554   unsigned Width = VecTy.getSizeInBits();
2555   unsigned NumElts = Width / LdTy.getSizeInBits();
2556   EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), LdTy, NumElts);
2557
2558   unsigned Idx = 1;
2559   SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT,LdOps[Start]);
2560
2561   for (unsigned i = Start + 1; i != End; ++i) {
2562     EVT NewLdTy = LdOps[i].getValueType();
2563     if (NewLdTy != LdTy) {
2564       NumElts = Width / NewLdTy.getSizeInBits();
2565       NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewLdTy, NumElts);
2566       VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, VecOp);
2567       // Readjust position and vector position based on new load type
2568       Idx = Idx * LdTy.getSizeInBits() / NewLdTy.getSizeInBits();
2569       LdTy = NewLdTy;
2570     }
2571     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVecVT, VecOp, LdOps[i],
2572                         DAG.getConstant(Idx++, TLI.getVectorIdxTy()));
2573   }
2574   return DAG.getNode(ISD::BITCAST, dl, VecTy, VecOp);
2575 }
2576
2577 SDValue DAGTypeLegalizer::GenWidenVectorLoads(SmallVectorImpl<SDValue> &LdChain,
2578                                               LoadSDNode *LD) {
2579   // The strategy assumes that we can efficiently load powers of two widths.
2580   // The routines chops the vector into the largest vector loads with the same
2581   // element type or scalar loads and then recombines it to the widen vector
2582   // type.
2583   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
2584   unsigned WidenWidth = WidenVT.getSizeInBits();
2585   EVT LdVT    = LD->getMemoryVT();
2586   SDLoc dl(LD);
2587   assert(LdVT.isVector() && WidenVT.isVector());
2588   assert(LdVT.getVectorElementType() == WidenVT.getVectorElementType());
2589
2590   // Load information
2591   SDValue   Chain = LD->getChain();
2592   SDValue   BasePtr = LD->getBasePtr();
2593   unsigned  Align    = LD->getAlignment();
2594   bool      isVolatile = LD->isVolatile();
2595   bool      isNonTemporal = LD->isNonTemporal();
2596   bool      isInvariant = LD->isInvariant();
2597   const MDNode *TBAAInfo = LD->getTBAAInfo();
2598
2599   int LdWidth = LdVT.getSizeInBits();
2600   int WidthDiff = WidenWidth - LdWidth;          // Difference
2601   unsigned LdAlign = (isVolatile) ? 0 : Align; // Allow wider loads
2602
2603   // Find the vector type that can load from.
2604   EVT NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
2605   int NewVTWidth = NewVT.getSizeInBits();
2606   SDValue LdOp = DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerInfo(),
2607                              isVolatile, isNonTemporal, isInvariant, Align,
2608                              TBAAInfo);
2609   LdChain.push_back(LdOp.getValue(1));
2610
2611   // Check if we can load the element with one instruction
2612   if (LdWidth <= NewVTWidth) {
2613     if (!NewVT.isVector()) {
2614       unsigned NumElts = WidenWidth / NewVTWidth;
2615       EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
2616       SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT, LdOp);
2617       return DAG.getNode(ISD::BITCAST, dl, WidenVT, VecOp);
2618     }
2619     if (NewVT == WidenVT)
2620       return LdOp;
2621
2622     assert(WidenWidth % NewVTWidth == 0);
2623     unsigned NumConcat = WidenWidth / NewVTWidth;
2624     SmallVector<SDValue, 16> ConcatOps(NumConcat);
2625     SDValue UndefVal = DAG.getUNDEF(NewVT);
2626     ConcatOps[0] = LdOp;
2627     for (unsigned i = 1; i != NumConcat; ++i)
2628       ConcatOps[i] = UndefVal;
2629     return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0],
2630                        NumConcat);
2631   }
2632
2633   // Load vector by using multiple loads from largest vector to scalar
2634   SmallVector<SDValue, 16> LdOps;
2635   LdOps.push_back(LdOp);
2636
2637   LdWidth -= NewVTWidth;
2638   unsigned Offset = 0;
2639
2640   while (LdWidth > 0) {
2641     unsigned Increment = NewVTWidth / 8;
2642     Offset += Increment;
2643     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2644                           DAG.getConstant(Increment, BasePtr.getValueType()));
2645
2646     SDValue L;
2647     if (LdWidth < NewVTWidth) {
2648       // Our current type we are using is too large, find a better size
2649       NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
2650       NewVTWidth = NewVT.getSizeInBits();
2651       L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
2652                       LD->getPointerInfo().getWithOffset(Offset), isVolatile,
2653                       isNonTemporal, isInvariant, MinAlign(Align, Increment),
2654                       TBAAInfo);
2655       LdChain.push_back(L.getValue(1));
2656       if (L->getValueType(0).isVector()) {
2657         SmallVector<SDValue, 16> Loads;
2658         Loads.push_back(L);
2659         unsigned size = L->getValueSizeInBits(0);
2660         while (size < LdOp->getValueSizeInBits(0)) {
2661           Loads.push_back(DAG.getUNDEF(L->getValueType(0)));
2662           size += L->getValueSizeInBits(0);
2663         }
2664         L = DAG.getNode(ISD::CONCAT_VECTORS, dl, LdOp->getValueType(0),
2665                         &Loads[0], Loads.size());
2666       }
2667     } else {
2668       L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
2669                       LD->getPointerInfo().getWithOffset(Offset), isVolatile,
2670                       isNonTemporal, isInvariant, MinAlign(Align, Increment),
2671                       TBAAInfo);
2672       LdChain.push_back(L.getValue(1));
2673     }
2674
2675     LdOps.push_back(L);
2676
2677
2678     LdWidth -= NewVTWidth;
2679   }
2680
2681   // Build the vector from the loads operations
2682   unsigned End = LdOps.size();
2683   if (!LdOps[0].getValueType().isVector())
2684     // All the loads are scalar loads.
2685     return BuildVectorFromScalar(DAG, WidenVT, LdOps, 0, End);
2686
2687   // If the load contains vectors, build the vector using concat vector.
2688   // All of the vectors used to loads are power of 2 and the scalars load
2689   // can be combined to make a power of 2 vector.
2690   SmallVector<SDValue, 16> ConcatOps(End);
2691   int i = End - 1;
2692   int Idx = End;
2693   EVT LdTy = LdOps[i].getValueType();
2694   // First combine the scalar loads to a vector
2695   if (!LdTy.isVector())  {
2696     for (--i; i >= 0; --i) {
2697       LdTy = LdOps[i].getValueType();
2698       if (LdTy.isVector())
2699         break;
2700     }
2701     ConcatOps[--Idx] = BuildVectorFromScalar(DAG, LdTy, LdOps, i+1, End);
2702   }
2703   ConcatOps[--Idx] = LdOps[i];
2704   for (--i; i >= 0; --i) {
2705     EVT NewLdTy = LdOps[i].getValueType();
2706     if (NewLdTy != LdTy) {
2707       // Create a larger vector
2708       ConcatOps[End-1] = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewLdTy,
2709                                      &ConcatOps[Idx], End - Idx);
2710       Idx = End - 1;
2711       LdTy = NewLdTy;
2712     }
2713     ConcatOps[--Idx] = LdOps[i];
2714   }
2715
2716   if (WidenWidth == LdTy.getSizeInBits()*(End - Idx))
2717     return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
2718                        &ConcatOps[Idx], End - Idx);
2719
2720   // We need to fill the rest with undefs to build the vector
2721   unsigned NumOps = WidenWidth / LdTy.getSizeInBits();
2722   SmallVector<SDValue, 16> WidenOps(NumOps);
2723   SDValue UndefVal = DAG.getUNDEF(LdTy);
2724   {
2725     unsigned i = 0;
2726     for (; i != End-Idx; ++i)
2727       WidenOps[i] = ConcatOps[Idx+i];
2728     for (; i != NumOps; ++i)
2729       WidenOps[i] = UndefVal;
2730   }
2731   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &WidenOps[0],NumOps);
2732 }
2733
2734 SDValue
2735 DAGTypeLegalizer::GenWidenVectorExtLoads(SmallVectorImpl<SDValue> &LdChain,
2736                                          LoadSDNode *LD,
2737                                          ISD::LoadExtType ExtType) {
2738   // For extension loads, it may not be more efficient to chop up the vector
2739   // and then extended it.  Instead, we unroll the load and build a new vector.
2740   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
2741   EVT LdVT    = LD->getMemoryVT();
2742   SDLoc dl(LD);
2743   assert(LdVT.isVector() && WidenVT.isVector());
2744
2745   // Load information
2746   SDValue   Chain = LD->getChain();
2747   SDValue   BasePtr = LD->getBasePtr();
2748   unsigned  Align    = LD->getAlignment();
2749   bool      isVolatile = LD->isVolatile();
2750   bool      isNonTemporal = LD->isNonTemporal();
2751   const MDNode *TBAAInfo = LD->getTBAAInfo();
2752
2753   EVT EltVT = WidenVT.getVectorElementType();
2754   EVT LdEltVT = LdVT.getVectorElementType();
2755   unsigned NumElts = LdVT.getVectorNumElements();
2756
2757   // Load each element and widen
2758   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2759   SmallVector<SDValue, 16> Ops(WidenNumElts);
2760   unsigned Increment = LdEltVT.getSizeInBits() / 8;
2761   Ops[0] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, BasePtr,
2762                           LD->getPointerInfo(),
2763                           LdEltVT, isVolatile, isNonTemporal, Align, TBAAInfo);
2764   LdChain.push_back(Ops[0].getValue(1));
2765   unsigned i = 0, Offset = Increment;
2766   for (i=1; i < NumElts; ++i, Offset += Increment) {
2767     SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
2768                                      BasePtr,
2769                                      DAG.getConstant(Offset,
2770                                                      BasePtr.getValueType()));
2771     Ops[i] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, NewBasePtr,
2772                             LD->getPointerInfo().getWithOffset(Offset), LdEltVT,
2773                             isVolatile, isNonTemporal, Align, TBAAInfo);
2774     LdChain.push_back(Ops[i].getValue(1));
2775   }
2776
2777   // Fill the rest with undefs
2778   SDValue UndefVal = DAG.getUNDEF(EltVT);
2779   for (; i != WidenNumElts; ++i)
2780     Ops[i] = UndefVal;
2781
2782   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], Ops.size());
2783 }
2784
2785
2786 void DAGTypeLegalizer::GenWidenVectorStores(SmallVectorImpl<SDValue> &StChain,
2787                                             StoreSDNode *ST) {
2788   // The strategy assumes that we can efficiently store powers of two widths.
2789   // The routines chops the vector into the largest vector stores with the same
2790   // element type or scalar stores.
2791   SDValue  Chain = ST->getChain();
2792   SDValue  BasePtr = ST->getBasePtr();
2793   unsigned Align = ST->getAlignment();
2794   bool     isVolatile = ST->isVolatile();
2795   bool     isNonTemporal = ST->isNonTemporal();
2796   const MDNode *TBAAInfo = ST->getTBAAInfo();
2797   SDValue  ValOp = GetWidenedVector(ST->getValue());
2798   SDLoc dl(ST);
2799
2800   EVT StVT = ST->getMemoryVT();
2801   unsigned StWidth = StVT.getSizeInBits();
2802   EVT ValVT = ValOp.getValueType();
2803   unsigned ValWidth = ValVT.getSizeInBits();
2804   EVT ValEltVT = ValVT.getVectorElementType();
2805   unsigned ValEltWidth = ValEltVT.getSizeInBits();
2806   assert(StVT.getVectorElementType() == ValEltVT);
2807
2808   int Idx = 0;          // current index to store
2809   unsigned Offset = 0;  // offset from base to store
2810   while (StWidth != 0) {
2811     // Find the largest vector type we can store with
2812     EVT NewVT = FindMemType(DAG, TLI, StWidth, ValVT);
2813     unsigned NewVTWidth = NewVT.getSizeInBits();
2814     unsigned Increment = NewVTWidth / 8;
2815     if (NewVT.isVector()) {
2816       unsigned NumVTElts = NewVT.getVectorNumElements();
2817       do {
2818         SDValue EOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT, ValOp,
2819                                    DAG.getConstant(Idx, TLI.getVectorIdxTy()));
2820         StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr,
2821                                     ST->getPointerInfo().getWithOffset(Offset),
2822                                        isVolatile, isNonTemporal,
2823                                        MinAlign(Align, Offset), TBAAInfo));
2824         StWidth -= NewVTWidth;
2825         Offset += Increment;
2826         Idx += NumVTElts;
2827         BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2828                               DAG.getConstant(Increment, BasePtr.getValueType()));
2829       } while (StWidth != 0 && StWidth >= NewVTWidth);
2830     } else {
2831       // Cast the vector to the scalar type we can store
2832       unsigned NumElts = ValWidth / NewVTWidth;
2833       EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
2834       SDValue VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, ValOp);
2835       // Readjust index position based on new vector type
2836       Idx = Idx * ValEltWidth / NewVTWidth;
2837       do {
2838         SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewVT, VecOp,
2839                       DAG.getConstant(Idx++, TLI.getVectorIdxTy()));
2840         StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr,
2841                                     ST->getPointerInfo().getWithOffset(Offset),
2842                                        isVolatile, isNonTemporal,
2843                                        MinAlign(Align, Offset), TBAAInfo));
2844         StWidth -= NewVTWidth;
2845         Offset += Increment;
2846         BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2847                             DAG.getConstant(Increment, BasePtr.getValueType()));
2848       } while (StWidth != 0 && StWidth >= NewVTWidth);
2849       // Restore index back to be relative to the original widen element type
2850       Idx = Idx * NewVTWidth / ValEltWidth;
2851     }
2852   }
2853 }
2854
2855 void
2856 DAGTypeLegalizer::GenWidenVectorTruncStores(SmallVectorImpl<SDValue> &StChain,
2857                                             StoreSDNode *ST) {
2858   // For extension loads, it may not be more efficient to truncate the vector
2859   // and then store it.  Instead, we extract each element and then store it.
2860   SDValue  Chain = ST->getChain();
2861   SDValue  BasePtr = ST->getBasePtr();
2862   unsigned Align = ST->getAlignment();
2863   bool     isVolatile = ST->isVolatile();
2864   bool     isNonTemporal = ST->isNonTemporal();
2865   const MDNode *TBAAInfo = ST->getTBAAInfo();
2866   SDValue  ValOp = GetWidenedVector(ST->getValue());
2867   SDLoc dl(ST);
2868
2869   EVT StVT = ST->getMemoryVT();
2870   EVT ValVT = ValOp.getValueType();
2871
2872   // It must be true that we the widen vector type is bigger than where
2873   // we need to store.
2874   assert(StVT.isVector() && ValOp.getValueType().isVector());
2875   assert(StVT.bitsLT(ValOp.getValueType()));
2876
2877   // For truncating stores, we can not play the tricks of chopping legal
2878   // vector types and bit cast it to the right type.  Instead, we unroll
2879   // the store.
2880   EVT StEltVT  = StVT.getVectorElementType();
2881   EVT ValEltVT = ValVT.getVectorElementType();
2882   unsigned Increment = ValEltVT.getSizeInBits() / 8;
2883   unsigned NumElts = StVT.getVectorNumElements();
2884   SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
2885                             DAG.getConstant(0, TLI.getVectorIdxTy()));
2886   StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, BasePtr,
2887                                       ST->getPointerInfo(), StEltVT,
2888                                       isVolatile, isNonTemporal, Align,
2889                                       TBAAInfo));
2890   unsigned Offset = Increment;
2891   for (unsigned i=1; i < NumElts; ++i, Offset += Increment) {
2892     SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
2893                                      BasePtr, DAG.getConstant(Offset,
2894                                                        BasePtr.getValueType()));
2895     SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
2896                             DAG.getConstant(0, TLI.getVectorIdxTy()));
2897     StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, NewBasePtr,
2898                                       ST->getPointerInfo().getWithOffset(Offset),
2899                                         StEltVT, isVolatile, isNonTemporal,
2900                                         MinAlign(Align, Offset), TBAAInfo));
2901   }
2902 }
2903
2904 /// Modifies a vector input (widen or narrows) to a vector of NVT.  The
2905 /// input vector must have the same element type as NVT.
2906 SDValue DAGTypeLegalizer::ModifyToType(SDValue InOp, EVT NVT) {
2907   // Note that InOp might have been widened so it might already have
2908   // the right width or it might need be narrowed.
2909   EVT InVT = InOp.getValueType();
2910   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
2911          "input and widen element type must match");
2912   SDLoc dl(InOp);
2913
2914   // Check if InOp already has the right width.
2915   if (InVT == NVT)
2916     return InOp;
2917
2918   unsigned InNumElts = InVT.getVectorNumElements();
2919   unsigned WidenNumElts = NVT.getVectorNumElements();
2920   if (WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0) {
2921     unsigned NumConcat = WidenNumElts / InNumElts;
2922     SmallVector<SDValue, 16> Ops(NumConcat);
2923     SDValue UndefVal = DAG.getUNDEF(InVT);
2924     Ops[0] = InOp;
2925     for (unsigned i = 1; i != NumConcat; ++i)
2926       Ops[i] = UndefVal;
2927
2928     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, &Ops[0], NumConcat);
2929   }
2930
2931   if (WidenNumElts < InNumElts && InNumElts % WidenNumElts)
2932     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, InOp,
2933                        DAG.getConstant(0, TLI.getVectorIdxTy()));
2934
2935   // Fall back to extract and build.
2936   SmallVector<SDValue, 16> Ops(WidenNumElts);
2937   EVT EltVT = NVT.getVectorElementType();
2938   unsigned MinNumElts = std::min(WidenNumElts, InNumElts);
2939   unsigned Idx;
2940   for (Idx = 0; Idx < MinNumElts; ++Idx)
2941     Ops[Idx] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2942                            DAG.getConstant(Idx, TLI.getVectorIdxTy()));
2943
2944   SDValue UndefVal = DAG.getUNDEF(EltVT);
2945   for ( ; Idx < WidenNumElts; ++Idx)
2946     Ops[Idx] = UndefVal;
2947   return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &Ops[0], WidenNumElts);
2948 }