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