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