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