Change loops to derive the number of tables automatically
[oota-llvm.git] / utils / TableGen / NeonEmitter.cpp
1 //===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
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 tablegen backend is responsible for emitting arm_neon.h, which includes
11 // a declaration and definition of each function specified by the ARM NEON
12 // compiler interface.  See ARM document DUI0348B.
13 //
14 // Each NEON instruction is implemented in terms of 1 or more functions which
15 // are suffixed with the element type of the input vectors.  Functions may be
16 // implemented in terms of generic vector operations such as +, *, -, etc. or
17 // by calling a __builtin_-prefixed function which will be handled by clang's
18 // CodeGen library.
19 //
20 // Additional validation code can be generated by this file when runHeader() is
21 // called, rather than the normal run() entry point.  A complete set of tests
22 // for Neon intrinsics can be generated by calling the runTests() entry point.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "NeonEmitter.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include <string>
31
32 using namespace llvm;
33
34 /// ParseTypes - break down a string such as "fQf" into a vector of StringRefs,
35 /// which each StringRef representing a single type declared in the string.
36 /// for "fQf" we would end up with 2 StringRefs, "f", and "Qf", representing
37 /// 2xfloat and 4xfloat respectively.
38 static void ParseTypes(Record *r, std::string &s,
39                        SmallVectorImpl<StringRef> &TV) {
40   const char *data = s.data();
41   int len = 0;
42
43   for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
44     if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
45       continue;
46
47     switch (data[len]) {
48       case 'c':
49       case 's':
50       case 'i':
51       case 'l':
52       case 'h':
53       case 'f':
54         break;
55       default:
56         throw TGError(r->getLoc(),
57                       "Unexpected letter: " + std::string(data + len, 1));
58         break;
59     }
60     TV.push_back(StringRef(data, len + 1));
61     data += len + 1;
62     len = -1;
63   }
64 }
65
66 /// Widen - Convert a type code into the next wider type.  char -> short,
67 /// short -> int, etc.
68 static char Widen(const char t) {
69   switch (t) {
70     case 'c':
71       return 's';
72     case 's':
73       return 'i';
74     case 'i':
75       return 'l';
76     case 'h':
77       return 'f';
78     default: throw "unhandled type in widen!";
79   }
80   return '\0';
81 }
82
83 /// Narrow - Convert a type code into the next smaller type.  short -> char,
84 /// float -> half float, etc.
85 static char Narrow(const char t) {
86   switch (t) {
87     case 's':
88       return 'c';
89     case 'i':
90       return 's';
91     case 'l':
92       return 'i';
93     case 'f':
94       return 'h';
95     default: throw "unhandled type in narrow!";
96   }
97   return '\0';
98 }
99
100 /// For a particular StringRef, return the base type code, and whether it has
101 /// the quad-vector, polynomial, or unsigned modifiers set.
102 static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
103   unsigned off = 0;
104
105   // remember quad.
106   if (ty[off] == 'Q') {
107     quad = true;
108     ++off;
109   }
110
111   // remember poly.
112   if (ty[off] == 'P') {
113     poly = true;
114     ++off;
115   }
116
117   // remember unsigned.
118   if (ty[off] == 'U') {
119     usgn = true;
120     ++off;
121   }
122
123   // base type to get the type string for.
124   return ty[off];
125 }
126
127 /// ModType - Transform a type code and its modifiers based on a mod code. The
128 /// mod code definitions may be found at the top of arm_neon.td.
129 static char ModType(const char mod, char type, bool &quad, bool &poly,
130                     bool &usgn, bool &scal, bool &cnst, bool &pntr) {
131   switch (mod) {
132     case 't':
133       if (poly) {
134         poly = false;
135         usgn = true;
136       }
137       break;
138     case 'u':
139       usgn = true;
140       poly = false;
141       if (type == 'f')
142         type = 'i';
143       break;
144     case 'x':
145       usgn = false;
146       poly = false;
147       if (type == 'f')
148         type = 'i';
149       break;
150     case 'f':
151       if (type == 'h')
152         quad = true;
153       type = 'f';
154       usgn = false;
155       break;
156     case 'g':
157       quad = false;
158       break;
159     case 'w':
160       type = Widen(type);
161       quad = true;
162       break;
163     case 'n':
164       type = Widen(type);
165       break;
166     case 'i':
167       type = 'i';
168       scal = true;
169       break;
170     case 'l':
171       type = 'l';
172       scal = true;
173       usgn = true;
174       break;
175     case 's':
176     case 'a':
177       scal = true;
178       break;
179     case 'k':
180       quad = true;
181       break;
182     case 'c':
183       cnst = true;
184     case 'p':
185       pntr = true;
186       scal = true;
187       break;
188     case 'h':
189       type = Narrow(type);
190       if (type == 'h')
191         quad = false;
192       break;
193     case 'e':
194       type = Narrow(type);
195       usgn = true;
196       break;
197     default:
198       break;
199   }
200   return type;
201 }
202
203 /// TypeString - for a modifier and type, generate the name of the typedef for
204 /// that type.  QUc -> uint8x8_t.
205 static std::string TypeString(const char mod, StringRef typestr) {
206   bool quad = false;
207   bool poly = false;
208   bool usgn = false;
209   bool scal = false;
210   bool cnst = false;
211   bool pntr = false;
212
213   if (mod == 'v')
214     return "void";
215   if (mod == 'i')
216     return "int";
217
218   // base type to get the type string for.
219   char type = ClassifyType(typestr, quad, poly, usgn);
220
221   // Based on the modifying character, change the type and width if necessary.
222   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
223
224   SmallString<128> s;
225
226   if (usgn)
227     s.push_back('u');
228
229   switch (type) {
230     case 'c':
231       s += poly ? "poly8" : "int8";
232       if (scal)
233         break;
234       s += quad ? "x16" : "x8";
235       break;
236     case 's':
237       s += poly ? "poly16" : "int16";
238       if (scal)
239         break;
240       s += quad ? "x8" : "x4";
241       break;
242     case 'i':
243       s += "int32";
244       if (scal)
245         break;
246       s += quad ? "x4" : "x2";
247       break;
248     case 'l':
249       s += "int64";
250       if (scal)
251         break;
252       s += quad ? "x2" : "x1";
253       break;
254     case 'h':
255       s += "float16";
256       if (scal)
257         break;
258       s += quad ? "x8" : "x4";
259       break;
260     case 'f':
261       s += "float32";
262       if (scal)
263         break;
264       s += quad ? "x4" : "x2";
265       break;
266     default:
267       throw "unhandled type!";
268       break;
269   }
270
271   if (mod == '2')
272     s += "x2";
273   if (mod == '3')
274     s += "x3";
275   if (mod == '4')
276     s += "x4";
277
278   // Append _t, finishing the type string typedef type.
279   s += "_t";
280
281   if (cnst)
282     s += " const";
283
284   if (pntr)
285     s += " *";
286
287   return s.str();
288 }
289
290 /// BuiltinTypeString - for a modifier and type, generate the clang
291 /// BuiltinsARM.def prototype code for the function.  See the top of clang's
292 /// Builtins.def for a description of the type strings.
293 static std::string BuiltinTypeString(const char mod, StringRef typestr,
294                                      ClassKind ck, bool ret) {
295   bool quad = false;
296   bool poly = false;
297   bool usgn = false;
298   bool scal = false;
299   bool cnst = false;
300   bool pntr = false;
301
302   if (mod == 'v')
303     return "v"; // void
304   if (mod == 'i')
305     return "i"; // int
306
307   // base type to get the type string for.
308   char type = ClassifyType(typestr, quad, poly, usgn);
309
310   // Based on the modifying character, change the type and width if necessary.
311   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
312
313   // All pointers are void* pointers.  Change type to 'v' now.
314   if (pntr) {
315     usgn = false;
316     poly = false;
317     type = 'v';
318   }
319   // Treat half-float ('h') types as unsigned short ('s') types.
320   if (type == 'h') {
321     type = 's';
322     usgn = true;
323   }
324   usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
325
326   if (scal) {
327     SmallString<128> s;
328
329     if (usgn)
330       s.push_back('U');
331     else if (type == 'c')
332       s.push_back('S'); // make chars explicitly signed
333
334     if (type == 'l') // 64-bit long
335       s += "LLi";
336     else
337       s.push_back(type);
338
339     if (cnst)
340       s.push_back('C');
341     if (pntr)
342       s.push_back('*');
343     return s.str();
344   }
345
346   // Since the return value must be one type, return a vector type of the
347   // appropriate width which we will bitcast.  An exception is made for
348   // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
349   // fashion, storing them to a pointer arg.
350   if (ret) {
351     if (mod >= '2' && mod <= '4')
352       return "vv*"; // void result with void* first argument
353     if (mod == 'f' || (ck != ClassB && type == 'f'))
354       return quad ? "V4f" : "V2f";
355     if (ck != ClassB && type == 's')
356       return quad ? "V8s" : "V4s";
357     if (ck != ClassB && type == 'i')
358       return quad ? "V4i" : "V2i";
359     if (ck != ClassB && type == 'l')
360       return quad ? "V2LLi" : "V1LLi";
361
362     return quad ? "V16Sc" : "V8Sc";
363   }
364
365   // Non-return array types are passed as individual vectors.
366   if (mod == '2')
367     return quad ? "V16ScV16Sc" : "V8ScV8Sc";
368   if (mod == '3')
369     return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
370   if (mod == '4')
371     return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
372
373   if (mod == 'f' || (ck != ClassB && type == 'f'))
374     return quad ? "V4f" : "V2f";
375   if (ck != ClassB && type == 's')
376     return quad ? "V8s" : "V4s";
377   if (ck != ClassB && type == 'i')
378     return quad ? "V4i" : "V2i";
379   if (ck != ClassB && type == 'l')
380     return quad ? "V2LLi" : "V1LLi";
381
382   return quad ? "V16Sc" : "V8Sc";
383 }
384
385 /// MangleName - Append a type or width suffix to a base neon function name,
386 /// and insert a 'q' in the appropriate location if the operation works on
387 /// 128b rather than 64b.   E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
388 static std::string MangleName(const std::string &name, StringRef typestr,
389                               ClassKind ck) {
390   if (name == "vcvt_f32_f16")
391     return name;
392
393   bool quad = false;
394   bool poly = false;
395   bool usgn = false;
396   char type = ClassifyType(typestr, quad, poly, usgn);
397
398   std::string s = name;
399
400   switch (type) {
401   case 'c':
402     switch (ck) {
403     case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
404     case ClassI: s += "_i8"; break;
405     case ClassW: s += "_8"; break;
406     default: break;
407     }
408     break;
409   case 's':
410     switch (ck) {
411     case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
412     case ClassI: s += "_i16"; break;
413     case ClassW: s += "_16"; break;
414     default: break;
415     }
416     break;
417   case 'i':
418     switch (ck) {
419     case ClassS: s += usgn ? "_u32" : "_s32"; break;
420     case ClassI: s += "_i32"; break;
421     case ClassW: s += "_32"; break;
422     default: break;
423     }
424     break;
425   case 'l':
426     switch (ck) {
427     case ClassS: s += usgn ? "_u64" : "_s64"; break;
428     case ClassI: s += "_i64"; break;
429     case ClassW: s += "_64"; break;
430     default: break;
431     }
432     break;
433   case 'h':
434     switch (ck) {
435     case ClassS:
436     case ClassI: s += "_f16"; break;
437     case ClassW: s += "_16"; break;
438     default: break;
439     }
440     break;
441   case 'f':
442     switch (ck) {
443     case ClassS:
444     case ClassI: s += "_f32"; break;
445     case ClassW: s += "_32"; break;
446     default: break;
447     }
448     break;
449   default:
450     throw "unhandled type!";
451     break;
452   }
453   if (ck == ClassB)
454     s += "_v";
455
456   // Insert a 'q' before the first '_' character so that it ends up before
457   // _lane or _n on vector-scalar operations.
458   if (quad) {
459     size_t pos = s.find('_');
460     s = s.insert(pos, "q");
461   }
462   return s;
463 }
464
465 // Generate the string "(argtype a, argtype b, ...)"
466 static std::string GenArgs(const std::string &proto, StringRef typestr) {
467   bool define = proto.find('i') != std::string::npos;
468   char arg = 'a';
469
470   std::string s;
471   s += "(";
472
473   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
474     if (define) {
475       // Immediate macro arguments are used directly instead of being assigned
476       // to local temporaries; prepend an underscore prefix to make their
477       // names consistent with the local temporaries.
478       if (proto[i] == 'i')
479         s += "__";
480     } else {
481       s += TypeString(proto[i], typestr) + " __";
482     }
483     s.push_back(arg);
484     if ((i + 1) < e)
485       s += ", ";
486   }
487
488   s += ")";
489   return s;
490 }
491
492 // Macro arguments are not type-checked like inline function arguments, so
493 // assign them to local temporaries to get the right type checking.
494 static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
495   char arg = 'a';
496   std::string s;
497
498   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
499     // Do not create a temporary for an immediate argument.
500     // That would defeat the whole point of using a macro!
501     if (proto[i] == 'i') continue;
502
503     s += TypeString(proto[i], typestr) + " __";
504     s.push_back(arg);
505     s += " = (";
506     s.push_back(arg);
507     s += "); ";
508   }
509
510   s += "\\\n  ";
511   return s;
512 }
513
514 // Use the vmovl builtin to sign-extend or zero-extend a vector.
515 static std::string Extend(StringRef typestr, const std::string &a) {
516   std::string s;
517   s = MangleName("vmovl", typestr, ClassS);
518   s += "(" + a + ")";
519   return s;
520 }
521
522 static std::string Duplicate(unsigned nElts, StringRef typestr,
523                              const std::string &a) {
524   std::string s;
525
526   s = "(" + TypeString('d', typestr) + "){ ";
527   for (unsigned i = 0; i != nElts; ++i) {
528     s += a;
529     if ((i + 1) < nElts)
530       s += ", ";
531   }
532   s += " }";
533
534   return s;
535 }
536
537 static std::string SplatLane(unsigned nElts, const std::string &vec,
538                              const std::string &lane) {
539   std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
540   for (unsigned i = 0; i < nElts; ++i)
541     s += ", " + lane;
542   s += ")";
543   return s;
544 }
545
546 static unsigned GetNumElements(StringRef typestr, bool &quad) {
547   quad = false;
548   bool dummy = false;
549   char type = ClassifyType(typestr, quad, dummy, dummy);
550   unsigned nElts = 0;
551   switch (type) {
552   case 'c': nElts = 8; break;
553   case 's': nElts = 4; break;
554   case 'i': nElts = 2; break;
555   case 'l': nElts = 1; break;
556   case 'h': nElts = 4; break;
557   case 'f': nElts = 2; break;
558   default:
559     throw "unhandled type!";
560     break;
561   }
562   if (quad) nElts <<= 1;
563   return nElts;
564 }
565
566 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
567 static std::string GenOpString(OpKind op, const std::string &proto,
568                                StringRef typestr) {
569   bool quad;
570   unsigned nElts = GetNumElements(typestr, quad);
571
572   // If this builtin takes an immediate argument, we need to #define it rather
573   // than use a standard declaration, so that SemaChecking can range check
574   // the immediate passed by the user.
575   bool define = proto.find('i') != std::string::npos;
576
577   std::string ts = TypeString(proto[0], typestr);
578   std::string s;
579   if (!define) {
580     s = "return ";
581   }
582
583   switch(op) {
584   case OpAdd:
585     s += "__a + __b;";
586     break;
587   case OpAddl:
588     s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
589     break;
590   case OpAddw:
591     s += "__a + " + Extend(typestr, "__b") + ";";
592     break;
593   case OpSub:
594     s += "__a - __b;";
595     break;
596   case OpSubl:
597     s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
598     break;
599   case OpSubw:
600     s += "__a - " + Extend(typestr, "__b") + ";";
601     break;
602   case OpMulN:
603     s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
604     break;
605   case OpMulLane:
606     s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
607     break;
608   case OpMul:
609     s += "__a * __b;";
610     break;
611   case OpMullLane:
612     s += MangleName("vmull", typestr, ClassS) + "(__a, " +
613       SplatLane(nElts, "__b", "__c") + ");";
614     break;
615   case OpMlaN:
616     s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
617     break;
618   case OpMlaLane:
619     s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
620     break;
621   case OpMla:
622     s += "__a + (__b * __c);";
623     break;
624   case OpMlalN:
625     s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, " +
626       Duplicate(nElts, typestr, "__c") + ");";
627     break;
628   case OpMlalLane:
629     s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, " +
630       SplatLane(nElts, "__c", "__d") + ");";
631     break;
632   case OpMlal:
633     s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, __c);";
634     break;
635   case OpMlsN:
636     s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
637     break;
638   case OpMlsLane:
639     s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
640     break;
641   case OpMls:
642     s += "__a - (__b * __c);";
643     break;
644   case OpMlslN:
645     s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, " +
646       Duplicate(nElts, typestr, "__c") + ");";
647     break;
648   case OpMlslLane:
649     s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, " +
650       SplatLane(nElts, "__c", "__d") + ");";
651     break;
652   case OpMlsl:
653     s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, __c);";
654     break;
655   case OpQDMullLane:
656     s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
657       SplatLane(nElts, "__b", "__c") + ");";
658     break;
659   case OpQDMlalLane:
660     s += MangleName("vqdmlal", typestr, ClassS) + "(__a, __b, " +
661       SplatLane(nElts, "__c", "__d") + ");";
662     break;
663   case OpQDMlslLane:
664     s += MangleName("vqdmlsl", typestr, ClassS) + "(__a, __b, " +
665       SplatLane(nElts, "__c", "__d") + ");";
666     break;
667   case OpQDMulhLane:
668     s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
669       SplatLane(nElts, "__b", "__c") + ");";
670     break;
671   case OpQRDMulhLane:
672     s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
673       SplatLane(nElts, "__b", "__c") + ");";
674     break;
675   case OpEq:
676     s += "(" + ts + ")(__a == __b);";
677     break;
678   case OpGe:
679     s += "(" + ts + ")(__a >= __b);";
680     break;
681   case OpLe:
682     s += "(" + ts + ")(__a <= __b);";
683     break;
684   case OpGt:
685     s += "(" + ts + ")(__a > __b);";
686     break;
687   case OpLt:
688     s += "(" + ts + ")(__a < __b);";
689     break;
690   case OpNeg:
691     s += " -__a;";
692     break;
693   case OpNot:
694     s += " ~__a;";
695     break;
696   case OpAnd:
697     s += "__a & __b;";
698     break;
699   case OpOr:
700     s += "__a | __b;";
701     break;
702   case OpXor:
703     s += "__a ^ __b;";
704     break;
705   case OpAndNot:
706     s += "__a & ~__b;";
707     break;
708   case OpOrNot:
709     s += "__a | ~__b;";
710     break;
711   case OpCast:
712     s += "(" + ts + ")__a;";
713     break;
714   case OpConcat:
715     s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
716     s += ", (int64x1_t)__b, 0, 1);";
717     break;
718   case OpHi:
719     s += "(" + ts +
720       ")__builtin_shufflevector((int64x2_t)__a, (int64x2_t)__a, 1);";
721     break;
722   case OpLo:
723     s += "(" + ts +
724       ")__builtin_shufflevector((int64x2_t)__a, (int64x2_t)__a, 0);";
725     break;
726   case OpDup:
727     s += Duplicate(nElts, typestr, "__a") + ";";
728     break;
729   case OpDupLane:
730     s += SplatLane(nElts, "__a", "__b") + ";";
731     break;
732   case OpSelect:
733     // ((0 & 1) | (~0 & 2))
734     s += "(" + ts + ")";
735     ts = TypeString(proto[1], typestr);
736     s += "((__a & (" + ts + ")__b) | ";
737     s += "(~__a & (" + ts + ")__c));";
738     break;
739   case OpRev16:
740     s += "__builtin_shufflevector(__a, __a";
741     for (unsigned i = 2; i <= nElts; i += 2)
742       for (unsigned j = 0; j != 2; ++j)
743         s += ", " + utostr(i - j - 1);
744     s += ");";
745     break;
746   case OpRev32: {
747     unsigned WordElts = nElts >> (1 + (int)quad);
748     s += "__builtin_shufflevector(__a, __a";
749     for (unsigned i = WordElts; i <= nElts; i += WordElts)
750       for (unsigned j = 0; j != WordElts; ++j)
751         s += ", " + utostr(i - j - 1);
752     s += ");";
753     break;
754   }
755   case OpRev64: {
756     unsigned DblWordElts = nElts >> (int)quad;
757     s += "__builtin_shufflevector(__a, __a";
758     for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
759       for (unsigned j = 0; j != DblWordElts; ++j)
760         s += ", " + utostr(i - j - 1);
761     s += ");";
762     break;
763   }
764   case OpAbdl: {
765     std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
766     if (typestr[0] != 'U') {
767       // vabd results are always unsigned and must be zero-extended.
768       std::string utype = "U" + typestr.str();
769       s += "(" + TypeString(proto[0], typestr) + ")";
770       abd = "(" + TypeString('d', utype) + ")" + abd;
771       s += Extend(utype, abd) + ";";
772     } else {
773       s += Extend(typestr, abd) + ";";
774     }
775     break;
776   }
777   case OpAba:
778     s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
779     break;
780   case OpAbal: {
781     s += "__a + ";
782     std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
783     if (typestr[0] != 'U') {
784       // vabd results are always unsigned and must be zero-extended.
785       std::string utype = "U" + typestr.str();
786       s += "(" + TypeString(proto[0], typestr) + ")";
787       abd = "(" + TypeString('d', utype) + ")" + abd;
788       s += Extend(utype, abd) + ";";
789     } else {
790       s += Extend(typestr, abd) + ";";
791     }
792     break;
793   }
794   default:
795     throw "unknown OpKind!";
796     break;
797   }
798   return s;
799 }
800
801 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
802   unsigned mod = proto[0];
803   unsigned ret = 0;
804
805   if (mod == 'v' || mod == 'f')
806     mod = proto[1];
807
808   bool quad = false;
809   bool poly = false;
810   bool usgn = false;
811   bool scal = false;
812   bool cnst = false;
813   bool pntr = false;
814
815   // Base type to get the type string for.
816   char type = ClassifyType(typestr, quad, poly, usgn);
817
818   // Based on the modifying character, change the type and width if necessary.
819   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
820
821   if (usgn)
822     ret |= 0x08;
823   if (quad && proto[1] != 'g')
824     ret |= 0x10;
825
826   switch (type) {
827     case 'c':
828       ret |= poly ? 5 : 0;
829       break;
830     case 's':
831       ret |= poly ? 6 : 1;
832       break;
833     case 'i':
834       ret |= 2;
835       break;
836     case 'l':
837       ret |= 3;
838       break;
839     case 'h':
840       ret |= 7;
841       break;
842     case 'f':
843       ret |= 4;
844       break;
845     default:
846       throw "unhandled type!";
847       break;
848   }
849   return ret;
850 }
851
852 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
853 static std::string GenBuiltin(const std::string &name, const std::string &proto,
854                               StringRef typestr, ClassKind ck) {
855   std::string s;
856
857   // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
858   // sret-like argument.
859   bool sret = (proto[0] >= '2' && proto[0] <= '4');
860
861   // If this builtin takes an immediate argument, we need to #define it rather
862   // than use a standard declaration, so that SemaChecking can range check
863   // the immediate passed by the user.
864   bool define = proto.find('i') != std::string::npos;
865
866   // Check if the prototype has a scalar operand with the type of the vector
867   // elements.  If not, bitcasting the args will take care of arg checking.
868   // The actual signedness etc. will be taken care of with special enums.
869   if (proto.find('s') == std::string::npos)
870     ck = ClassB;
871
872   if (proto[0] != 'v') {
873     std::string ts = TypeString(proto[0], typestr);
874
875     if (define) {
876       if (sret)
877         s += ts + " r; ";
878       else
879         s += "(" + ts + ")";
880     } else if (sret) {
881       s += ts + " r; ";
882     } else {
883       s += "return (" + ts + ")";
884     }
885   }
886
887   bool splat = proto.find('a') != std::string::npos;
888
889   s += "__builtin_neon_";
890   if (splat) {
891     // Call the non-splat builtin: chop off the "_n" suffix from the name.
892     std::string vname(name, 0, name.size()-2);
893     s += MangleName(vname, typestr, ck);
894   } else {
895     s += MangleName(name, typestr, ck);
896   }
897   s += "(";
898
899   // Pass the address of the return variable as the first argument to sret-like
900   // builtins.
901   if (sret)
902     s += "&r, ";
903
904   char arg = 'a';
905   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
906     std::string args = std::string(&arg, 1);
907
908     // Use the local temporaries instead of the macro arguments.
909     args = "__" + args;
910
911     bool argQuad = false;
912     bool argPoly = false;
913     bool argUsgn = false;
914     bool argScalar = false;
915     bool dummy = false;
916     char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
917     argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
918                       dummy, dummy);
919
920     // Handle multiple-vector values specially, emitting each subvector as an
921     // argument to the __builtin.
922     if (proto[i] >= '2' && proto[i] <= '4') {
923       // Check if an explicit cast is needed.
924       if (argType != 'c' || argPoly || argUsgn)
925         args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
926
927       for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
928         s += args + ".val[" + utostr(vi) + "]";
929         if ((vi + 1) < ve)
930           s += ", ";
931       }
932       if ((i + 1) < e)
933         s += ", ";
934
935       continue;
936     }
937
938     if (splat && (i + 1) == e)
939       args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
940
941     // Check if an explicit cast is needed.
942     if ((splat || !argScalar) &&
943         ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
944       std::string argTypeStr = "c";
945       if (ck != ClassB)
946         argTypeStr = argType;
947       if (argQuad)
948         argTypeStr = "Q" + argTypeStr;
949       args = "(" + TypeString('d', argTypeStr) + ")" + args;
950     }
951
952     s += args;
953     if ((i + 1) < e)
954       s += ", ";
955   }
956
957   // Extra constant integer to hold type class enum for this function, e.g. s8
958   if (ck == ClassB)
959     s += ", " + utostr(GetNeonEnum(proto, typestr));
960
961   s += ");";
962
963   if (proto[0] != 'v' && sret) {
964     if (define)
965       s += " r;";
966     else
967       s += " return r;";
968   }
969   return s;
970 }
971
972 static std::string GenBuiltinDef(const std::string &name,
973                                  const std::string &proto,
974                                  StringRef typestr, ClassKind ck) {
975   std::string s("BUILTIN(__builtin_neon_");
976
977   // If all types are the same size, bitcasting the args will take care
978   // of arg checking.  The actual signedness etc. will be taken care of with
979   // special enums.
980   if (proto.find('s') == std::string::npos)
981     ck = ClassB;
982
983   s += MangleName(name, typestr, ck);
984   s += ", \"";
985
986   for (unsigned i = 0, e = proto.size(); i != e; ++i)
987     s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
988
989   // Extra constant integer to hold type class enum for this function, e.g. s8
990   if (ck == ClassB)
991     s += "i";
992
993   s += "\", \"n\")";
994   return s;
995 }
996
997 static std::string GenIntrinsic(const std::string &name,
998                                 const std::string &proto,
999                                 StringRef outTypeStr, StringRef inTypeStr,
1000                                 OpKind kind, ClassKind classKind) {
1001   assert(!proto.empty() && "");
1002   bool define = proto.find('i') != std::string::npos;
1003   std::string s;
1004
1005   // static always inline + return type
1006   if (define)
1007     s += "#define ";
1008   else
1009     s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1010
1011   // Function name with type suffix
1012   std::string mangledName = MangleName(name, outTypeStr, ClassS);
1013   if (outTypeStr != inTypeStr) {
1014     // If the input type is different (e.g., for vreinterpret), append a suffix
1015     // for the input type.  String off a "Q" (quad) prefix so that MangleName
1016     // does not insert another "q" in the name.
1017     unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1018     StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1019     mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1020   }
1021   s += mangledName;
1022
1023   // Function arguments
1024   s += GenArgs(proto, inTypeStr);
1025
1026   // Definition.
1027   if (define) {
1028     s += " __extension__ ({ \\\n  ";
1029     s += GenMacroLocals(proto, inTypeStr);
1030   } else {
1031     s += " { \\\n  ";
1032   }
1033
1034   if (kind != OpNone)
1035     s += GenOpString(kind, proto, outTypeStr);
1036   else
1037     s += GenBuiltin(name, proto, outTypeStr, classKind);
1038   if (define)
1039     s += " })";
1040   else
1041     s += " }";
1042   s += "\n";
1043   return s;
1044 }
1045
1046 /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
1047 /// is comprised of type definitions and function declarations.
1048 void NeonEmitter::run(raw_ostream &OS) {
1049   OS << 
1050     "/*===---- arm_neon.h - ARM Neon intrinsics ------------------------------"
1051     "---===\n"
1052     " *\n"
1053     " * Permission is hereby granted, free of charge, to any person obtaining "
1054     "a copy\n"
1055     " * of this software and associated documentation files (the \"Software\"),"
1056     " to deal\n"
1057     " * in the Software without restriction, including without limitation the "
1058     "rights\n"
1059     " * to use, copy, modify, merge, publish, distribute, sublicense, "
1060     "and/or sell\n"
1061     " * copies of the Software, and to permit persons to whom the Software is\n"
1062     " * furnished to do so, subject to the following conditions:\n"
1063     " *\n"
1064     " * The above copyright notice and this permission notice shall be "
1065     "included in\n"
1066     " * all copies or substantial portions of the Software.\n"
1067     " *\n"
1068     " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
1069     "EXPRESS OR\n"
1070     " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
1071     "MERCHANTABILITY,\n"
1072     " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
1073     "SHALL THE\n"
1074     " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
1075     "OTHER\n"
1076     " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
1077     "ARISING FROM,\n"
1078     " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
1079     "DEALINGS IN\n"
1080     " * THE SOFTWARE.\n"
1081     " *\n"
1082     " *===--------------------------------------------------------------------"
1083     "---===\n"
1084     " */\n\n";
1085
1086   OS << "#ifndef __ARM_NEON_H\n";
1087   OS << "#define __ARM_NEON_H\n\n";
1088
1089   OS << "#ifndef __ARM_NEON__\n";
1090   OS << "#error \"NEON support not enabled\"\n";
1091   OS << "#endif\n\n";
1092
1093   OS << "#include <stdint.h>\n\n";
1094
1095   // Emit NEON-specific scalar typedefs.
1096   OS << "typedef float float32_t;\n";
1097   OS << "typedef int8_t poly8_t;\n";
1098   OS << "typedef int16_t poly16_t;\n";
1099   OS << "typedef uint16_t float16_t;\n";
1100
1101   // Emit Neon vector typedefs.
1102   std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1103   SmallVector<StringRef, 24> TDTypeVec;
1104   ParseTypes(0, TypedefTypes, TDTypeVec);
1105
1106   // Emit vector typedefs.
1107   for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1108     bool dummy, quad = false, poly = false;
1109     (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1110     if (poly)
1111       OS << "typedef __attribute__((neon_polyvector_type(";
1112     else
1113       OS << "typedef __attribute__((neon_vector_type(";
1114
1115     unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1116     OS << utostr(nElts) << "))) ";
1117     if (nElts < 10)
1118       OS << " ";
1119
1120     OS << TypeString('s', TDTypeVec[i]);
1121     OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1122   }
1123   OS << "\n";
1124
1125   // Emit struct typedefs.
1126   for (unsigned vi = 2; vi != 5; ++vi) {
1127     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1128       std::string ts = TypeString('d', TDTypeVec[i]);
1129       std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1130       OS << "typedef struct " << vs << " {\n";
1131       OS << "  " << ts << " val";
1132       OS << "[" << utostr(vi) << "]";
1133       OS << ";\n} ";
1134       OS << vs << ";\n\n";
1135     }
1136   }
1137
1138   OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1139
1140   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1141
1142   // Emit vmovl, vmull and vabd intrinsics first so they can be used by other
1143   // intrinsics.  (Some of the saturating multiply instructions are also
1144   // used to implement the corresponding "_lane" variants, but tablegen
1145   // sorts the records into alphabetical order so that the "_lane" variants
1146   // come after the intrinsics they use.)
1147   emitIntrinsic(OS, Records.getDef("VMOVL"));
1148   emitIntrinsic(OS, Records.getDef("VMULL"));
1149   emitIntrinsic(OS, Records.getDef("VABD"));
1150
1151   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1152     Record *R = RV[i];
1153     if (R->getName() != "VMOVL" &&
1154         R->getName() != "VMULL" &&
1155         R->getName() != "VABD")
1156       emitIntrinsic(OS, R);
1157   }
1158
1159   OS << "#undef __ai\n\n";
1160   OS << "#endif /* __ARM_NEON_H */\n";
1161 }
1162
1163 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1164 /// intrinsics specified by record R.
1165 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1166   std::string name = R->getValueAsString("Name");
1167   std::string Proto = R->getValueAsString("Prototype");
1168   std::string Types = R->getValueAsString("Types");
1169
1170   SmallVector<StringRef, 16> TypeVec;
1171   ParseTypes(R, Types, TypeVec);
1172
1173   OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1174
1175   ClassKind classKind = ClassNone;
1176   if (R->getSuperClasses().size() >= 2)
1177     classKind = ClassMap[R->getSuperClasses()[1]];
1178   if (classKind == ClassNone && kind == OpNone)
1179     throw TGError(R->getLoc(), "Builtin has no class kind");
1180
1181   for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1182     if (kind == OpReinterpret) {
1183       bool outQuad = false;
1184       bool dummy = false;
1185       (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1186       for (unsigned srcti = 0, srcte = TypeVec.size();
1187            srcti != srcte; ++srcti) {
1188         bool inQuad = false;
1189         (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1190         if (srcti == ti || inQuad != outQuad)
1191           continue;
1192         OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1193                            OpCast, ClassS);
1194       }
1195     } else {
1196       OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1197                          kind, classKind);
1198     }
1199   }
1200   OS << "\n";
1201 }
1202
1203 static unsigned RangeFromType(const char mod, StringRef typestr) {
1204   // base type to get the type string for.
1205   bool quad = false, dummy = false;
1206   char type = ClassifyType(typestr, quad, dummy, dummy);
1207   type = ModType(mod, type, quad, dummy, dummy, dummy, dummy, dummy);
1208
1209   switch (type) {
1210     case 'c':
1211       return (8 << (int)quad) - 1;
1212     case 'h':
1213     case 's':
1214       return (4 << (int)quad) - 1;
1215     case 'f':
1216     case 'i':
1217       return (2 << (int)quad) - 1;
1218     case 'l':
1219       return (1 << (int)quad) - 1;
1220     default:
1221       throw "unhandled type!";
1222       break;
1223   }
1224   assert(0 && "unreachable");
1225   return 0;
1226 }
1227
1228 /// runHeader - Emit a file with sections defining:
1229 /// 1. the NEON section of BuiltinsARM.def.
1230 /// 2. the SemaChecking code for the type overload checking.
1231 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1232 void NeonEmitter::runHeader(raw_ostream &OS) {
1233   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1234
1235   StringMap<OpKind> EmittedMap;
1236
1237   // Generate BuiltinsARM.def for NEON
1238   OS << "#ifdef GET_NEON_BUILTINS\n";
1239   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1240     Record *R = RV[i];
1241     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1242     if (k != OpNone)
1243       continue;
1244
1245     std::string Proto = R->getValueAsString("Prototype");
1246
1247     // Functions with 'a' (the splat code) in the type prototype should not get
1248     // their own builtin as they use the non-splat variant.
1249     if (Proto.find('a') != std::string::npos)
1250       continue;
1251
1252     std::string Types = R->getValueAsString("Types");
1253     SmallVector<StringRef, 16> TypeVec;
1254     ParseTypes(R, Types, TypeVec);
1255
1256     if (R->getSuperClasses().size() < 2)
1257       throw TGError(R->getLoc(), "Builtin has no class kind");
1258
1259     std::string name = R->getValueAsString("Name");
1260     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1261
1262     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1263       // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1264       // that each unique BUILTIN() macro appears only once in the output
1265       // stream.
1266       std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1267       if (EmittedMap.count(bd))
1268         continue;
1269
1270       EmittedMap[bd] = OpNone;
1271       OS << bd << "\n";
1272     }
1273   }
1274   OS << "#endif\n\n";
1275
1276   // Generate the overloaded type checking code for SemaChecking.cpp
1277   OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1278   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1279     Record *R = RV[i];
1280     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1281     if (k != OpNone)
1282       continue;
1283
1284     std::string Proto = R->getValueAsString("Prototype");
1285     std::string Types = R->getValueAsString("Types");
1286     std::string name = R->getValueAsString("Name");
1287
1288     // Functions with 'a' (the splat code) in the type prototype should not get
1289     // their own builtin as they use the non-splat variant.
1290     if (Proto.find('a') != std::string::npos)
1291       continue;
1292
1293     // Functions which have a scalar argument cannot be overloaded, no need to
1294     // check them if we are emitting the type checking code.
1295     if (Proto.find('s') != std::string::npos)
1296       continue;
1297
1298     SmallVector<StringRef, 16> TypeVec;
1299     ParseTypes(R, Types, TypeVec);
1300
1301     if (R->getSuperClasses().size() < 2)
1302       throw TGError(R->getLoc(), "Builtin has no class kind");
1303
1304     int si = -1, qi = -1;
1305     unsigned mask = 0, qmask = 0;
1306     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1307       // Generate the switch case(s) for this builtin for the type validation.
1308       bool quad = false, poly = false, usgn = false;
1309       (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1310
1311       if (quad) {
1312         qi = ti;
1313         qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1314       } else {
1315         si = ti;
1316         mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1317       }
1318     }
1319     if (mask)
1320       OS << "case ARM::BI__builtin_neon_"
1321          << MangleName(name, TypeVec[si], ClassB)
1322          << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1323     if (qmask)
1324       OS << "case ARM::BI__builtin_neon_"
1325          << MangleName(name, TypeVec[qi], ClassB)
1326          << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1327   }
1328   OS << "#endif\n\n";
1329
1330   // Generate the intrinsic range checking code for shift/lane immediates.
1331   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1332   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1333     Record *R = RV[i];
1334
1335     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1336     if (k != OpNone)
1337       continue;
1338
1339     std::string name = R->getValueAsString("Name");
1340     std::string Proto = R->getValueAsString("Prototype");
1341     std::string Types = R->getValueAsString("Types");
1342
1343     // Functions with 'a' (the splat code) in the type prototype should not get
1344     // their own builtin as they use the non-splat variant.
1345     if (Proto.find('a') != std::string::npos)
1346       continue;
1347
1348     // Functions which do not have an immediate do not need to have range
1349     // checking code emitted.
1350     size_t immPos = Proto.find('i');
1351     if (immPos == std::string::npos)
1352       continue;
1353
1354     SmallVector<StringRef, 16> TypeVec;
1355     ParseTypes(R, Types, TypeVec);
1356
1357     if (R->getSuperClasses().size() < 2)
1358       throw TGError(R->getLoc(), "Builtin has no class kind");
1359
1360     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1361
1362     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1363       std::string namestr, shiftstr, rangestr;
1364
1365       // Builtins which are overloaded by type will need to have their upper
1366       // bound computed at Sema time based on the type constant.
1367       if (Proto.find('s') == std::string::npos) {
1368         ck = ClassB;
1369         if (R->getValueAsBit("isShift")) {
1370           shiftstr = ", true";
1371
1372           // Right shifts have an 'r' in the name, left shifts do not.
1373           if (name.find('r') != std::string::npos)
1374             rangestr = "l = 1; ";
1375         }
1376         rangestr += "u = RFT(TV" + shiftstr + ")";
1377       } else {
1378         // The immediate generally refers to a lane in the preceding argument.
1379         assert(immPos > 0 && "unexpected immediate operand");
1380         rangestr = "u = " + utostr(RangeFromType(Proto[immPos-1], TypeVec[ti]));
1381       }
1382       // Make sure cases appear only once by uniquing them in a string map.
1383       namestr = MangleName(name, TypeVec[ti], ck);
1384       if (EmittedMap.count(namestr))
1385         continue;
1386       EmittedMap[namestr] = OpNone;
1387
1388       // Calculate the index of the immediate that should be range checked.
1389       unsigned immidx = 0;
1390
1391       // Builtins that return a struct of multiple vectors have an extra
1392       // leading arg for the struct return.
1393       if (Proto[0] >= '2' && Proto[0] <= '4')
1394         ++immidx;
1395
1396       // Add one to the index for each argument until we reach the immediate
1397       // to be checked.  Structs of vectors are passed as multiple arguments.
1398       for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1399         switch (Proto[ii]) {
1400           default:  immidx += 1; break;
1401           case '2': immidx += 2; break;
1402           case '3': immidx += 3; break;
1403           case '4': immidx += 4; break;
1404           case 'i': ie = ii + 1; break;
1405         }
1406       }
1407       OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1408          << ": i = " << immidx << "; " << rangestr << "; break;\n";
1409     }
1410   }
1411   OS << "#endif\n\n";
1412 }
1413
1414 /// GenTest - Write out a test for the intrinsic specified by the name and
1415 /// type strings, including the embedded patterns for FileCheck to match.
1416 static std::string GenTest(const std::string &name,
1417                            const std::string &proto,
1418                            StringRef outTypeStr, StringRef inTypeStr,
1419                            bool isShift) {
1420   assert(!proto.empty() && "");
1421   std::string s;
1422
1423   // Function name with type suffix
1424   std::string mangledName = MangleName(name, outTypeStr, ClassS);
1425   if (outTypeStr != inTypeStr) {
1426     // If the input type is different (e.g., for vreinterpret), append a suffix
1427     // for the input type.  String off a "Q" (quad) prefix so that MangleName
1428     // does not insert another "q" in the name.
1429     unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1430     StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1431     mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1432   }
1433
1434   // Emit the FileCheck patterns.
1435   s += "// CHECK: test_" + mangledName + "\n";
1436   // s += "// CHECK: \n"; // FIXME: + expected instruction opcode.
1437
1438   // Emit the start of the test function.
1439   s += TypeString(proto[0], outTypeStr) + " test_" + mangledName + "(";
1440   char arg = 'a';
1441   std::string comma;
1442   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1443     // Do not create arguments for values that must be immediate constants.
1444     if (proto[i] == 'i')
1445       continue;
1446     s += comma + TypeString(proto[i], inTypeStr) + " ";
1447     s.push_back(arg);
1448     comma = ", ";
1449   }
1450   s += ") { \\\n  ";
1451
1452   if (proto[0] != 'v')
1453     s += "return ";
1454   s += mangledName + "(";
1455   arg = 'a';
1456   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1457     if (proto[i] == 'i') {
1458       // For immediate operands, test the maximum value.
1459       if (isShift)
1460         s += "1"; // FIXME
1461       else
1462         // The immediate generally refers to a lane in the preceding argument.
1463         s += utostr(RangeFromType(proto[i-1], inTypeStr));
1464     } else {
1465       s.push_back(arg);
1466     }
1467     if ((i + 1) < e)
1468       s += ", ";
1469   }
1470   s += ");\n}\n\n";
1471   return s;
1472 }
1473
1474 /// runTests - Write out a complete set of tests for all of the Neon
1475 /// intrinsics.
1476 void NeonEmitter::runTests(raw_ostream &OS) {
1477   OS <<
1478     "// RUN: %clang_cc1 -triple thumbv7-apple-darwin \\\n"
1479     "// RUN:  -target-cpu cortex-a9 -ffreestanding -S -o - %s | FileCheck %s\n"
1480     "\n"
1481     "#include <arm_neon.h>\n"
1482     "\n";
1483
1484   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1485   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1486     Record *R = RV[i];
1487     std::string name = R->getValueAsString("Name");
1488     std::string Proto = R->getValueAsString("Prototype");
1489     std::string Types = R->getValueAsString("Types");
1490     bool isShift = R->getValueAsBit("isShift");
1491
1492     SmallVector<StringRef, 16> TypeVec;
1493     ParseTypes(R, Types, TypeVec);
1494
1495     OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1496     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1497       if (kind == OpReinterpret) {
1498         bool outQuad = false;
1499         bool dummy = false;
1500         (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1501         for (unsigned srcti = 0, srcte = TypeVec.size();
1502              srcti != srcte; ++srcti) {
1503           bool inQuad = false;
1504           (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1505           if (srcti == ti || inQuad != outQuad)
1506             continue;
1507           OS << GenTest(name, Proto, TypeVec[ti], TypeVec[srcti], isShift);
1508         }
1509       } else {
1510         OS << GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift);
1511       }
1512     }
1513     OS << "\n";
1514   }
1515 }
1516