Add some additional capabilities to the neon emitter
[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 //===----------------------------------------------------------------------===//
15
16 #include "NeonEmitter.h"
17 #include "Record.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include <string>
23
24 using namespace llvm;
25
26 enum OpKind {
27   OpNone,
28   OpAdd,
29   OpSub,
30   OpMul,
31   OpMla,
32   OpMls,
33   OpEq,
34   OpGe,
35   OpLe,
36   OpGt,
37   OpLt,
38   OpNeg,
39   OpNot,
40   OpAnd,
41   OpOr,
42   OpXor,
43   OpAndNot,
44   OpOrNot,
45   OpCast
46 };
47
48 static void ParseTypes(Record *r, std::string &s,
49                        SmallVectorImpl<StringRef> &TV) {
50   const char *data = s.data();
51   int len = 0;
52   
53   for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
54     if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
55       continue;
56     
57     switch (data[len]) {
58       case 'c':
59       case 's':
60       case 'i':
61       case 'l':
62       case 'h':
63       case 'f':
64         break;
65       default:
66         throw TGError(r->getLoc(),
67                       "Unexpected letter: " + std::string(data + len, 1));
68         break;
69     }
70     TV.push_back(StringRef(data, len + 1));
71     data += len + 1;
72     len = -1;
73   }
74 }
75
76 static char Widen(const char t) {
77   switch (t) {
78     case 'c':
79       return 's';
80     case 's':
81       return 'i';
82     case 'i':
83       return 'l';
84     default: throw "unhandled type in widen!";
85   }
86   return '\0';
87 }
88
89 static char Narrow(const char t) {
90   switch (t) {
91     case 's':
92       return 'c';
93     case 'i':
94       return 's';
95     case 'l':
96       return 'i';
97     default: throw "unhandled type in widen!";
98   }
99   return '\0';
100 }
101
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 static std::string TypeString(const char mod, StringRef typestr) {
128   bool quad = false;
129   bool poly = false;
130   bool usgn = false;
131   bool scal = false;
132   bool cnst = false;
133   bool pntr = false;
134   
135   // base type to get the type string for.
136   char type = ClassifyType(typestr, quad, poly, usgn);
137   
138   // Based on the modifying character, change the type and width if necessary.
139   switch (mod) {
140     case 'v':
141       return "void";
142     case 'i':
143       return "int";
144     case 't':
145       if (poly) {
146         poly = false;
147         usgn = true;
148       }
149       break;
150     case 'x':
151       usgn = true;
152       poly = false;
153       if (type == 'f')
154         type = 'i';
155       break;
156     case 'f':
157       type = 'f';
158       usgn = false;
159       break;
160     case 'w':
161       type = Widen(type);
162       quad = true;
163       break;
164     case 'n':
165       type = Widen(type);
166       break;
167     case 'l':
168       type = 'l';
169       scal = true;
170       usgn = true;
171       break;
172     case 's':
173       scal = true;
174       break;
175     case 'k':
176       quad = true;
177       break;
178     case 'c':
179       cnst = true;
180     case 'p':
181       pntr = true;
182       scal = true;
183       break;
184     case 'h':
185       type = Narrow(type);
186       break;
187     case 'e':
188       type = Narrow(type);
189       usgn = true;
190       break;
191     default:
192       break;
193   }
194   
195   SmallString<128> s;
196   
197   if (usgn)
198     s.push_back('u');
199   
200   switch (type) {
201     case 'c':
202       s += poly ? "poly8" : "int8";
203       if (scal)
204         break;
205       s += quad ? "x16" : "x8";
206       break;
207     case 's':
208       s += poly ? "poly16" : "int16";
209       if (scal)
210         break;
211       s += quad ? "x8" : "x4";
212       break;
213     case 'i':
214       s += "int32";
215       if (scal)
216         break;
217       s += quad ? "x4" : "x2";
218       break;
219     case 'l':
220       s += "int64";
221       if (scal)
222         break;
223       s += quad ? "x2" : "x1";
224       break;
225     case 'h':
226       s += "float16";
227       if (scal)
228         break;
229       s += quad ? "x8" : "x4";
230       break;
231     case 'f':
232       s += "float32";
233       if (scal)
234         break;
235       s += quad ? "x4" : "x2";
236       break;
237     default:
238       throw "unhandled type!";
239       break;
240   }
241
242   if (mod == '2')
243     s += "x2";
244   if (mod == '3')
245     s += "x3";
246   if (mod == '4')
247     s += "x4";
248   
249   // Append _t, finishing the type string typedef type.
250   s += "_t";
251   
252   if (cnst)
253     s += " const";
254   
255   if (pntr)
256     s += " *";
257   
258   return s.str();
259 }
260
261 // Turn "vst2_lane" into "vst2q_lane_f32", etc.
262 static std::string MangleName(const std::string &name, StringRef typestr) {
263   bool quad = false;
264   bool poly = false;
265   bool usgn = false;
266   char type = ClassifyType(typestr, quad, poly, usgn);
267
268   std::string s = name;
269   
270   switch (type) {
271     case 'c':
272       s += poly ? "_p8" : usgn ? "_u8" : "_s8";
273       break;
274     case 's':
275       s += poly ? "_p16" : usgn ? "_u16" : "_s16";
276       break;
277     case 'i':
278       s += usgn ? "_u32" : "_s32";
279       break;
280     case 'l':
281       s += usgn ? "_u64" : "_s64";
282       break;
283     case 'h':
284       s += "_f16";
285       break;
286     case 'f':
287       s += "_f32";
288       break;
289     default:
290       throw "unhandled type!";
291       break;
292   }
293
294   // Insert a 'q' before the first '_' character so that it ends up before 
295   // _lane or _n on vector-scalar operations.
296   if (quad) {
297     size_t pos = s.find('_');
298     s = s.insert(pos, "q");
299   }
300   return s;
301 }
302
303 // Generate the string "(argtype a, argtype b, ...)"
304 static std::string GenArgs(const std::string &proto, StringRef typestr) {
305   char arg = 'a';
306   
307   std::string s;
308   s += "(";
309   
310   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
311     s += TypeString(proto[i], typestr);
312     s.push_back(' ');
313     s.push_back(arg);
314     if ((i + 1) < e)
315       s += ", ";
316   }
317   
318   s += ")";
319   return s;
320 }
321
322 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
323 // If structTypes is true, the NEON types are structs of vector types rather
324 // than vector types, and the call becomes "a.val + b.val"
325 static std::string GenOpString(OpKind op, const std::string &proto,
326                                StringRef typestr, bool structTypes = true) {
327   std::string s("return ");
328   std::string ts = TypeString(proto[0], typestr);
329   if (structTypes)
330     s += "(" + ts + "){";
331   
332   std::string a, b, c;
333   if (proto.size() > 1)
334     a = (structTypes && proto[1] != 'l') ? "a.val" : "a";
335   b = structTypes ? "b.val" : "b";
336   c = structTypes ? "c.val" : "c";
337   
338   switch(op) {
339   case OpAdd:
340     s += a + " + " + b;
341     break;
342   case OpSub:
343     s += a + " - " + b;
344     break;
345   case OpMul:
346     s += a + " * " + b;
347     break;
348   case OpMla:
349     s += a + " + ( " + b + " * " + c + " )";
350     break;
351   case OpMls:
352     s += a + " - ( " + b + " * " + c + " )";
353     break;
354   case OpEq:
355     s += "(__neon_" + ts + ")(" + a + " == " + b + ")";
356     break;
357   case OpGe:
358     s += "(__neon_" + ts + ")(" + a + " >= " + b + ")";
359     break;
360   case OpLe:
361     s += "(__neon_" + ts + ")(" + a + " <= " + b + ")";
362     break;
363   case OpGt:
364     s += "(__neon_" + ts + ")(" + a + " > " + b + ")";
365     break;
366   case OpLt:
367     s += "(__neon_" + ts + ")(" + a + " < " + b + ")";
368     break;
369   case OpNeg:
370     s += " -" + a;
371     break;
372   case OpNot:
373     s += " ~" + a;
374     break;
375   case OpAnd:
376     s += a + " & " + b;
377     break;
378   case OpOr:
379     s += a + " | " + b;
380     break;
381   case OpXor:
382     s += a + " ^ " + b;
383     break;
384   case OpAndNot:
385     s += a + " & ~" + b;
386     break;
387   case OpOrNot:
388     s += a + " | ~" + b;
389     break;
390   case OpCast:
391     s += "(__neon_" + ts + ")" + a;
392     break;
393   default:
394     throw "unknown OpKind!";
395     break;
396   }
397   
398   if (structTypes)
399     s += "}";
400   s += ";";
401   return s;
402 }
403
404 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
405 // If structTypes is true, the NEON types are structs of vector types rather
406 // than vector types, and the call becomes __builtin_neon_cls(a.val)
407 static std::string GenBuiltin(const std::string &name, const std::string &proto,
408                               StringRef typestr, bool structTypes = true) {
409   char arg = 'a';
410   std::string s;
411   
412   if (proto[0] != 'v') {
413     // FIXME: if return type is 2/3/4, emit unioning code.
414     s += "return ";
415     if (structTypes) {
416       s += "(";
417       s += TypeString(proto[0], typestr);
418       s += "){";
419     }
420   }    
421   
422   s += "__builtin_neon_";
423   s += name;
424   s += "(";
425   
426   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
427     s.push_back(arg);
428     if (structTypes && proto[i] != 's' && proto[i] != 'i' && proto[i] != 'l' &&
429         proto[i] != 'p' && proto[i] != 'c') {
430       s += ".val";
431     }
432     if ((i + 1) < e)
433       s += ", ";
434   }
435   
436   s += ")";
437   if (proto[0] != 'v' && structTypes)
438     s += "}";
439   s += ";";
440   return s;
441 }
442
443 void NeonEmitter::run(raw_ostream &OS) {
444   EmitSourceFileHeader("ARM NEON Header", OS);
445   
446   // FIXME: emit license into file?
447   
448   OS << "#ifndef __ARM_NEON_H\n";
449   OS << "#define __ARM_NEON_H\n\n";
450   
451   OS << "#ifndef __ARM_NEON__\n";
452   OS << "#error \"NEON support not enabled\"\n";
453   OS << "#endif\n\n";
454
455   OS << "#include <stdint.h>\n\n";
456
457   // Emit NEON-specific scalar typedefs.
458   // FIXME: probably need to do something better for polynomial types.
459   // FIXME: is this the correct thing to do for float16?
460   OS << "typedef float float32_t;\n";
461   OS << "typedef uint8_t poly8_t;\n";
462   OS << "typedef uint16_t poly16_t;\n";
463   OS << "typedef uint16_t float16_t;\n";
464   
465   // Emit Neon vector typedefs.
466   std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
467   SmallVector<StringRef, 24> TDTypeVec;
468   ParseTypes(0, TypedefTypes, TDTypeVec);
469
470   // Emit vector typedefs.
471   for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
472     bool dummy, quad = false;
473     (void) ClassifyType(TDTypeVec[i], quad, dummy, dummy);
474     OS << "typedef __attribute__(( __vector_size__(";
475     OS << (quad ? "16) )) " : "8) ))  ");
476     OS << TypeString('s', TDTypeVec[i]);
477     OS << " __neon_";
478     OS << TypeString('d', TDTypeVec[i]) << ";\n";
479   }
480   OS << "\n";
481
482   // Emit struct typedefs.
483   for (unsigned vi = 1; vi != 5; ++vi) {
484     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
485       std::string ts = TypeString('d', TDTypeVec[i]);
486       std::string vs = (vi > 1) ? TypeString('0' + vi, TDTypeVec[i]) : ts;
487       OS << "typedef struct __" << vs << " {\n";
488       OS << "  __neon_" << ts << " val";
489       if (vi > 1)
490         OS << "[" << utostr(vi) << "]";
491       OS << ";\n} " << vs << ";\n\n";
492     }
493   }
494   
495   OS << "#define __ai static __attribute__((__always_inline__))\n\n";
496
497   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
498   
499   StringMap<OpKind> OpMap;
500   OpMap["OP_NONE"] = OpNone;
501   OpMap["OP_ADD"]  = OpAdd;
502   OpMap["OP_SUB"]  = OpSub;
503   OpMap["OP_MUL"]  = OpMul;
504   OpMap["OP_MLA"]  = OpMla;
505   OpMap["OP_MLS"]  = OpMls;
506   OpMap["OP_EQ"]   = OpEq;
507   OpMap["OP_GE"]   = OpGe;
508   OpMap["OP_LE"]   = OpLe;
509   OpMap["OP_GT"]   = OpGt;
510   OpMap["OP_LT"]   = OpLt;
511   OpMap["OP_NEG"]  = OpNeg;
512   OpMap["OP_NOT"]  = OpNot;
513   OpMap["OP_AND"]  = OpAnd;
514   OpMap["OP_OR"]   = OpOr;
515   OpMap["OP_XOR"]  = OpXor;
516   OpMap["OP_ANDN"] = OpAndNot;
517   OpMap["OP_ORN"]  = OpOrNot;
518   OpMap["OP_CAST"] = OpCast;
519   
520   // Unique the return+pattern types, and assign them.
521   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
522     Record *R = RV[i];
523     std::string name = LowercaseString(R->getName());
524     std::string Proto = R->getValueAsString("Prototype");
525     std::string Types = R->getValueAsString("Types");
526     
527     SmallVector<StringRef, 16> TypeVec;
528     ParseTypes(R, Types, TypeVec);
529     
530     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
531     
532     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
533       assert(!Proto.empty() && "");
534       
535       // static always inline + return type
536       OS << "__ai " << TypeString(Proto[0], TypeVec[ti]);
537       
538       // Function name with type suffix
539       OS << " " << MangleName(name, TypeVec[ti]);
540       
541       // Function arguments
542       OS << GenArgs(Proto, TypeVec[ti]);
543       
544       // Definition.
545       OS << " { ";
546       
547       if (k != OpNone)
548         OS << GenOpString(k, Proto, TypeVec[ti]);
549       else
550         OS << GenBuiltin(name, Proto, TypeVec[ti]);
551
552       OS << " }\n";
553     }
554     OS << "\n";
555   }
556
557   // TODO: 
558   // Unique the return+pattern types, and assign them to each record
559   // Emit a #define for each unique "type" of intrinsic declaring all variants.
560   // Emit a #define for each intrinsic mapping it to a particular type.
561   
562   OS << "#endif /* __ARM_NEON_H */\n";
563 }