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