blob: b952f78d4b94ec063ccb017866e6ff90b9547292 [file] [log] [blame]
Peter Collingbourne51d77772011-10-06 13:03:08 +00001//===- 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
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +000026#include "llvm/ADT/DenseMap.h"
Peter Collingbourne51d77772011-10-06 13:03:08 +000027#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/StringExtras.h"
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +000030#include "llvm/ADT/StringMap.h"
David Blaikie7530c032012-01-17 06:56:22 +000031#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +000032#include "llvm/TableGen/Error.h"
33#include "llvm/TableGen/Record.h"
34#include "llvm/TableGen/TableGenBackend.h"
Peter Collingbourne51d77772011-10-06 13:03:08 +000035#include <string>
Peter Collingbourne51d77772011-10-06 13:03:08 +000036using namespace llvm;
37
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +000038enum OpKind {
39 OpNone,
40 OpUnavailable,
41 OpAdd,
42 OpAddl,
43 OpAddw,
44 OpSub,
45 OpSubl,
46 OpSubw,
47 OpMul,
48 OpMla,
49 OpMlal,
50 OpMls,
51 OpMlsl,
52 OpMulN,
53 OpMlaN,
54 OpMlsN,
55 OpMlalN,
56 OpMlslN,
57 OpMulLane,
58 OpMullLane,
59 OpMlaLane,
60 OpMlsLane,
61 OpMlalLane,
62 OpMlslLane,
63 OpQDMullLane,
64 OpQDMlalLane,
65 OpQDMlslLane,
66 OpQDMulhLane,
67 OpQRDMulhLane,
68 OpEq,
69 OpGe,
70 OpLe,
71 OpGt,
72 OpLt,
73 OpNeg,
74 OpNot,
75 OpAnd,
76 OpOr,
77 OpXor,
78 OpAndNot,
79 OpOrNot,
80 OpCast,
81 OpConcat,
82 OpDup,
83 OpDupLane,
84 OpHi,
85 OpLo,
86 OpSelect,
87 OpRev16,
88 OpRev32,
89 OpRev64,
90 OpReinterpret,
91 OpAbdl,
92 OpAba,
93 OpAbal
94};
95
96enum ClassKind {
97 ClassNone,
98 ClassI, // generic integer instruction, e.g., "i8" suffix
99 ClassS, // signed/unsigned/poly, e.g., "s8", "u8" or "p8" suffix
100 ClassW, // width-specific instruction, e.g., "8" suffix
Michael Gottesman21e4e942013-04-16 21:18:42 +0000101 ClassB, // bitcast arguments with enum argument to specify type
102 ClassL, // Logical instructions which are op instructions
103 // but we need to not emit any suffix for in our
104 // tests.
105 ClassNoTest // Instructions which we do not test since they are
106 // not TRUE instructions.
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +0000107};
108
109/// NeonTypeFlags - Flags to identify the types for overloaded Neon
110/// builtins. These must be kept in sync with the flags in
111/// include/clang/Basic/TargetBuiltins.h.
112namespace {
113class NeonTypeFlags {
114 enum {
115 EltTypeMask = 0xf,
116 UnsignedFlag = 0x10,
117 QuadFlag = 0x20
118 };
119 uint32_t Flags;
120
121public:
122 enum EltType {
123 Int8,
124 Int16,
125 Int32,
126 Int64,
127 Poly8,
128 Poly16,
129 Float16,
130 Float32
131 };
132
133 NeonTypeFlags(unsigned F) : Flags(F) {}
134 NeonTypeFlags(EltType ET, bool IsUnsigned, bool IsQuad) : Flags(ET) {
135 if (IsUnsigned)
136 Flags |= UnsignedFlag;
137 if (IsQuad)
138 Flags |= QuadFlag;
139 }
140
141 uint32_t getFlags() const { return Flags; }
142};
143} // end anonymous namespace
144
145namespace {
146class NeonEmitter {
147 RecordKeeper &Records;
148 StringMap<OpKind> OpMap;
149 DenseMap<Record*, ClassKind> ClassMap;
150
151public:
152 NeonEmitter(RecordKeeper &R) : Records(R) {
153 OpMap["OP_NONE"] = OpNone;
154 OpMap["OP_UNAVAILABLE"] = OpUnavailable;
155 OpMap["OP_ADD"] = OpAdd;
156 OpMap["OP_ADDL"] = OpAddl;
157 OpMap["OP_ADDW"] = OpAddw;
158 OpMap["OP_SUB"] = OpSub;
159 OpMap["OP_SUBL"] = OpSubl;
160 OpMap["OP_SUBW"] = OpSubw;
161 OpMap["OP_MUL"] = OpMul;
162 OpMap["OP_MLA"] = OpMla;
163 OpMap["OP_MLAL"] = OpMlal;
164 OpMap["OP_MLS"] = OpMls;
165 OpMap["OP_MLSL"] = OpMlsl;
166 OpMap["OP_MUL_N"] = OpMulN;
167 OpMap["OP_MLA_N"] = OpMlaN;
168 OpMap["OP_MLS_N"] = OpMlsN;
169 OpMap["OP_MLAL_N"] = OpMlalN;
170 OpMap["OP_MLSL_N"] = OpMlslN;
171 OpMap["OP_MUL_LN"]= OpMulLane;
172 OpMap["OP_MULL_LN"] = OpMullLane;
173 OpMap["OP_MLA_LN"]= OpMlaLane;
174 OpMap["OP_MLS_LN"]= OpMlsLane;
175 OpMap["OP_MLAL_LN"] = OpMlalLane;
176 OpMap["OP_MLSL_LN"] = OpMlslLane;
177 OpMap["OP_QDMULL_LN"] = OpQDMullLane;
178 OpMap["OP_QDMLAL_LN"] = OpQDMlalLane;
179 OpMap["OP_QDMLSL_LN"] = OpQDMlslLane;
180 OpMap["OP_QDMULH_LN"] = OpQDMulhLane;
181 OpMap["OP_QRDMULH_LN"] = OpQRDMulhLane;
182 OpMap["OP_EQ"] = OpEq;
183 OpMap["OP_GE"] = OpGe;
184 OpMap["OP_LE"] = OpLe;
185 OpMap["OP_GT"] = OpGt;
186 OpMap["OP_LT"] = OpLt;
187 OpMap["OP_NEG"] = OpNeg;
188 OpMap["OP_NOT"] = OpNot;
189 OpMap["OP_AND"] = OpAnd;
190 OpMap["OP_OR"] = OpOr;
191 OpMap["OP_XOR"] = OpXor;
192 OpMap["OP_ANDN"] = OpAndNot;
193 OpMap["OP_ORN"] = OpOrNot;
194 OpMap["OP_CAST"] = OpCast;
195 OpMap["OP_CONC"] = OpConcat;
196 OpMap["OP_HI"] = OpHi;
197 OpMap["OP_LO"] = OpLo;
198 OpMap["OP_DUP"] = OpDup;
199 OpMap["OP_DUP_LN"] = OpDupLane;
200 OpMap["OP_SEL"] = OpSelect;
201 OpMap["OP_REV16"] = OpRev16;
202 OpMap["OP_REV32"] = OpRev32;
203 OpMap["OP_REV64"] = OpRev64;
204 OpMap["OP_REINT"] = OpReinterpret;
205 OpMap["OP_ABDL"] = OpAbdl;
206 OpMap["OP_ABA"] = OpAba;
207 OpMap["OP_ABAL"] = OpAbal;
208
209 Record *SI = R.getClass("SInst");
210 Record *II = R.getClass("IInst");
211 Record *WI = R.getClass("WInst");
Michael Gottesman21e4e942013-04-16 21:18:42 +0000212 Record *SOpI = R.getClass("SOpInst");
213 Record *IOpI = R.getClass("IOpInst");
214 Record *WOpI = R.getClass("WOpInst");
215 Record *LOpI = R.getClass("LOpInst");
216 Record *NoTestOpI = R.getClass("NoTestOpInst");
217
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +0000218 ClassMap[SI] = ClassS;
219 ClassMap[II] = ClassI;
220 ClassMap[WI] = ClassW;
Michael Gottesman21e4e942013-04-16 21:18:42 +0000221 ClassMap[SOpI] = ClassS;
222 ClassMap[IOpI] = ClassI;
223 ClassMap[WOpI] = ClassW;
224 ClassMap[LOpI] = ClassL;
225 ClassMap[NoTestOpI] = ClassNoTest;
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +0000226 }
227
228 // run - Emit arm_neon.h.inc
229 void run(raw_ostream &o);
230
231 // runHeader - Emit all the __builtin prototypes used in arm_neon.h
232 void runHeader(raw_ostream &o);
233
234 // runTests - Emit tests for all the Neon intrinsics.
235 void runTests(raw_ostream &o);
236
237private:
238 void emitIntrinsic(raw_ostream &OS, Record *R);
239};
240} // end anonymous namespace
241
Peter Collingbourne51d77772011-10-06 13:03:08 +0000242/// ParseTypes - break down a string such as "fQf" into a vector of StringRefs,
243/// which each StringRef representing a single type declared in the string.
244/// for "fQf" we would end up with 2 StringRefs, "f", and "Qf", representing
245/// 2xfloat and 4xfloat respectively.
246static void ParseTypes(Record *r, std::string &s,
247 SmallVectorImpl<StringRef> &TV) {
248 const char *data = s.data();
249 int len = 0;
250
251 for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
252 if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
253 continue;
254
255 switch (data[len]) {
256 case 'c':
257 case 's':
258 case 'i':
259 case 'l':
260 case 'h':
261 case 'f':
262 break;
263 default:
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +0000264 PrintFatalError(r->getLoc(),
Peter Collingbourne51d77772011-10-06 13:03:08 +0000265 "Unexpected letter: " + std::string(data + len, 1));
Peter Collingbourne51d77772011-10-06 13:03:08 +0000266 }
267 TV.push_back(StringRef(data, len + 1));
268 data += len + 1;
269 len = -1;
270 }
271}
272
273/// Widen - Convert a type code into the next wider type. char -> short,
274/// short -> int, etc.
275static char Widen(const char t) {
276 switch (t) {
277 case 'c':
278 return 's';
279 case 's':
280 return 'i';
281 case 'i':
282 return 'l';
283 case 'h':
284 return 'f';
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +0000285 default:
286 PrintFatalError("unhandled type in widen!");
Peter Collingbourne51d77772011-10-06 13:03:08 +0000287 }
Peter Collingbourne51d77772011-10-06 13:03:08 +0000288}
289
290/// Narrow - Convert a type code into the next smaller type. short -> char,
291/// float -> half float, etc.
292static char Narrow(const char t) {
293 switch (t) {
294 case 's':
295 return 'c';
296 case 'i':
297 return 's';
298 case 'l':
299 return 'i';
300 case 'f':
301 return 'h';
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +0000302 default:
303 PrintFatalError("unhandled type in narrow!");
Peter Collingbourne51d77772011-10-06 13:03:08 +0000304 }
Peter Collingbourne51d77772011-10-06 13:03:08 +0000305}
306
307/// For a particular StringRef, return the base type code, and whether it has
308/// the quad-vector, polynomial, or unsigned modifiers set.
309static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
310 unsigned off = 0;
311
312 // remember quad.
313 if (ty[off] == 'Q') {
314 quad = true;
315 ++off;
316 }
317
318 // remember poly.
319 if (ty[off] == 'P') {
320 poly = true;
321 ++off;
322 }
323
324 // remember unsigned.
325 if (ty[off] == 'U') {
326 usgn = true;
327 ++off;
328 }
329
330 // base type to get the type string for.
331 return ty[off];
332}
333
334/// ModType - Transform a type code and its modifiers based on a mod code. The
335/// mod code definitions may be found at the top of arm_neon.td.
336static char ModType(const char mod, char type, bool &quad, bool &poly,
337 bool &usgn, bool &scal, bool &cnst, bool &pntr) {
338 switch (mod) {
339 case 't':
340 if (poly) {
341 poly = false;
342 usgn = true;
343 }
344 break;
345 case 'u':
346 usgn = true;
347 poly = false;
348 if (type == 'f')
349 type = 'i';
350 break;
351 case 'x':
352 usgn = false;
353 poly = false;
354 if (type == 'f')
355 type = 'i';
356 break;
357 case 'f':
358 if (type == 'h')
359 quad = true;
360 type = 'f';
361 usgn = false;
362 break;
363 case 'g':
364 quad = false;
365 break;
366 case 'w':
367 type = Widen(type);
368 quad = true;
369 break;
370 case 'n':
371 type = Widen(type);
372 break;
373 case 'i':
374 type = 'i';
375 scal = true;
376 break;
377 case 'l':
378 type = 'l';
379 scal = true;
380 usgn = true;
381 break;
382 case 's':
383 case 'a':
384 scal = true;
385 break;
386 case 'k':
387 quad = true;
388 break;
389 case 'c':
390 cnst = true;
391 case 'p':
392 pntr = true;
393 scal = true;
394 break;
395 case 'h':
396 type = Narrow(type);
397 if (type == 'h')
398 quad = false;
399 break;
400 case 'e':
401 type = Narrow(type);
402 usgn = true;
403 break;
404 default:
405 break;
406 }
407 return type;
408}
409
410/// TypeString - for a modifier and type, generate the name of the typedef for
411/// that type. QUc -> uint8x8_t.
412static std::string TypeString(const char mod, StringRef typestr) {
413 bool quad = false;
414 bool poly = false;
415 bool usgn = false;
416 bool scal = false;
417 bool cnst = false;
418 bool pntr = false;
419
420 if (mod == 'v')
421 return "void";
422 if (mod == 'i')
423 return "int";
424
425 // base type to get the type string for.
426 char type = ClassifyType(typestr, quad, poly, usgn);
427
428 // Based on the modifying character, change the type and width if necessary.
429 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
430
431 SmallString<128> s;
432
433 if (usgn)
434 s.push_back('u');
435
436 switch (type) {
437 case 'c':
438 s += poly ? "poly8" : "int8";
439 if (scal)
440 break;
441 s += quad ? "x16" : "x8";
442 break;
443 case 's':
444 s += poly ? "poly16" : "int16";
445 if (scal)
446 break;
447 s += quad ? "x8" : "x4";
448 break;
449 case 'i':
450 s += "int32";
451 if (scal)
452 break;
453 s += quad ? "x4" : "x2";
454 break;
455 case 'l':
456 s += "int64";
457 if (scal)
458 break;
459 s += quad ? "x2" : "x1";
460 break;
461 case 'h':
462 s += "float16";
463 if (scal)
464 break;
465 s += quad ? "x8" : "x4";
466 break;
467 case 'f':
468 s += "float32";
469 if (scal)
470 break;
471 s += quad ? "x4" : "x2";
472 break;
473 default:
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +0000474 PrintFatalError("unhandled type!");
Peter Collingbourne51d77772011-10-06 13:03:08 +0000475 }
476
477 if (mod == '2')
478 s += "x2";
479 if (mod == '3')
480 s += "x3";
481 if (mod == '4')
482 s += "x4";
483
484 // Append _t, finishing the type string typedef type.
485 s += "_t";
486
487 if (cnst)
488 s += " const";
489
490 if (pntr)
491 s += " *";
492
493 return s.str();
494}
495
496/// BuiltinTypeString - for a modifier and type, generate the clang
497/// BuiltinsARM.def prototype code for the function. See the top of clang's
498/// Builtins.def for a description of the type strings.
499static std::string BuiltinTypeString(const char mod, StringRef typestr,
500 ClassKind ck, bool ret) {
501 bool quad = false;
502 bool poly = false;
503 bool usgn = false;
504 bool scal = false;
505 bool cnst = false;
506 bool pntr = false;
507
508 if (mod == 'v')
509 return "v"; // void
510 if (mod == 'i')
511 return "i"; // int
512
513 // base type to get the type string for.
514 char type = ClassifyType(typestr, quad, poly, usgn);
515
516 // Based on the modifying character, change the type and width if necessary.
517 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
518
519 // All pointers are void* pointers. Change type to 'v' now.
520 if (pntr) {
521 usgn = false;
522 poly = false;
523 type = 'v';
524 }
525 // Treat half-float ('h') types as unsigned short ('s') types.
526 if (type == 'h') {
527 type = 's';
528 usgn = true;
529 }
530 usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
531
532 if (scal) {
533 SmallString<128> s;
534
535 if (usgn)
536 s.push_back('U');
537 else if (type == 'c')
538 s.push_back('S'); // make chars explicitly signed
539
540 if (type == 'l') // 64-bit long
541 s += "LLi";
542 else
543 s.push_back(type);
544
545 if (cnst)
546 s.push_back('C');
547 if (pntr)
548 s.push_back('*');
549 return s.str();
550 }
551
552 // Since the return value must be one type, return a vector type of the
553 // appropriate width which we will bitcast. An exception is made for
554 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
555 // fashion, storing them to a pointer arg.
556 if (ret) {
557 if (mod >= '2' && mod <= '4')
558 return "vv*"; // void result with void* first argument
559 if (mod == 'f' || (ck != ClassB && type == 'f'))
560 return quad ? "V4f" : "V2f";
561 if (ck != ClassB && type == 's')
562 return quad ? "V8s" : "V4s";
563 if (ck != ClassB && type == 'i')
564 return quad ? "V4i" : "V2i";
565 if (ck != ClassB && type == 'l')
566 return quad ? "V2LLi" : "V1LLi";
567
568 return quad ? "V16Sc" : "V8Sc";
569 }
570
571 // Non-return array types are passed as individual vectors.
572 if (mod == '2')
573 return quad ? "V16ScV16Sc" : "V8ScV8Sc";
574 if (mod == '3')
575 return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
576 if (mod == '4')
577 return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
578
579 if (mod == 'f' || (ck != ClassB && type == 'f'))
580 return quad ? "V4f" : "V2f";
581 if (ck != ClassB && type == 's')
582 return quad ? "V8s" : "V4s";
583 if (ck != ClassB && type == 'i')
584 return quad ? "V4i" : "V2i";
585 if (ck != ClassB && type == 'l')
586 return quad ? "V2LLi" : "V1LLi";
587
588 return quad ? "V16Sc" : "V8Sc";
589}
590
591/// MangleName - Append a type or width suffix to a base neon function name,
592/// and insert a 'q' in the appropriate location if the operation works on
593/// 128b rather than 64b. E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
594static std::string MangleName(const std::string &name, StringRef typestr,
595 ClassKind ck) {
596 if (name == "vcvt_f32_f16")
597 return name;
598
599 bool quad = false;
600 bool poly = false;
601 bool usgn = false;
602 char type = ClassifyType(typestr, quad, poly, usgn);
603
604 std::string s = name;
605
606 switch (type) {
607 case 'c':
608 switch (ck) {
609 case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
610 case ClassI: s += "_i8"; break;
611 case ClassW: s += "_8"; break;
612 default: break;
613 }
614 break;
615 case 's':
616 switch (ck) {
617 case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
618 case ClassI: s += "_i16"; break;
619 case ClassW: s += "_16"; break;
620 default: break;
621 }
622 break;
623 case 'i':
624 switch (ck) {
625 case ClassS: s += usgn ? "_u32" : "_s32"; break;
626 case ClassI: s += "_i32"; break;
627 case ClassW: s += "_32"; break;
628 default: break;
629 }
630 break;
631 case 'l':
632 switch (ck) {
633 case ClassS: s += usgn ? "_u64" : "_s64"; break;
634 case ClassI: s += "_i64"; break;
635 case ClassW: s += "_64"; break;
636 default: break;
637 }
638 break;
639 case 'h':
640 switch (ck) {
641 case ClassS:
642 case ClassI: s += "_f16"; break;
643 case ClassW: s += "_16"; break;
644 default: break;
645 }
646 break;
647 case 'f':
648 switch (ck) {
649 case ClassS:
650 case ClassI: s += "_f32"; break;
651 case ClassW: s += "_32"; break;
652 default: break;
653 }
654 break;
655 default:
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +0000656 PrintFatalError("unhandled type!");
Peter Collingbourne51d77772011-10-06 13:03:08 +0000657 }
658 if (ck == ClassB)
659 s += "_v";
660
661 // Insert a 'q' before the first '_' character so that it ends up before
662 // _lane or _n on vector-scalar operations.
663 if (quad) {
664 size_t pos = s.find('_');
665 s = s.insert(pos, "q");
666 }
667 return s;
668}
669
670/// UseMacro - Examine the prototype string to determine if the intrinsic
671/// should be defined as a preprocessor macro instead of an inline function.
672static bool UseMacro(const std::string &proto) {
673 // If this builtin takes an immediate argument, we need to #define it rather
674 // than use a standard declaration, so that SemaChecking can range check
675 // the immediate passed by the user.
676 if (proto.find('i') != std::string::npos)
677 return true;
678
679 // Pointer arguments need to use macros to avoid hiding aligned attributes
680 // from the pointer type.
681 if (proto.find('p') != std::string::npos ||
682 proto.find('c') != std::string::npos)
683 return true;
684
685 return false;
686}
687
688/// MacroArgUsedDirectly - Return true if argument i for an intrinsic that is
689/// defined as a macro should be accessed directly instead of being first
690/// assigned to a local temporary.
691static bool MacroArgUsedDirectly(const std::string &proto, unsigned i) {
692 // True for constant ints (i), pointers (p) and const pointers (c).
693 return (proto[i] == 'i' || proto[i] == 'p' || proto[i] == 'c');
694}
695
696// Generate the string "(argtype a, argtype b, ...)"
697static std::string GenArgs(const std::string &proto, StringRef typestr) {
698 bool define = UseMacro(proto);
699 char arg = 'a';
700
701 std::string s;
702 s += "(";
703
704 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
705 if (define) {
706 // Some macro arguments are used directly instead of being assigned
707 // to local temporaries; prepend an underscore prefix to make their
708 // names consistent with the local temporaries.
709 if (MacroArgUsedDirectly(proto, i))
710 s += "__";
711 } else {
712 s += TypeString(proto[i], typestr) + " __";
713 }
714 s.push_back(arg);
715 if ((i + 1) < e)
716 s += ", ";
717 }
718
719 s += ")";
720 return s;
721}
722
723// Macro arguments are not type-checked like inline function arguments, so
724// assign them to local temporaries to get the right type checking.
725static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
726 char arg = 'a';
727 std::string s;
728 bool generatedLocal = false;
729
730 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
731 // Do not create a temporary for an immediate argument.
732 // That would defeat the whole point of using a macro!
Peter Collingbourne51d77772011-10-06 13:03:08 +0000733 if (MacroArgUsedDirectly(proto, i))
734 continue;
735 generatedLocal = true;
736
737 s += TypeString(proto[i], typestr) + " __";
738 s.push_back(arg);
739 s += " = (";
740 s.push_back(arg);
741 s += "); ";
742 }
743
744 if (generatedLocal)
745 s += "\\\n ";
746 return s;
747}
748
749// Use the vmovl builtin to sign-extend or zero-extend a vector.
750static std::string Extend(StringRef typestr, const std::string &a) {
751 std::string s;
752 s = MangleName("vmovl", typestr, ClassS);
753 s += "(" + a + ")";
754 return s;
755}
756
757static std::string Duplicate(unsigned nElts, StringRef typestr,
758 const std::string &a) {
759 std::string s;
760
761 s = "(" + TypeString('d', typestr) + "){ ";
762 for (unsigned i = 0; i != nElts; ++i) {
763 s += a;
764 if ((i + 1) < nElts)
765 s += ", ";
766 }
767 s += " }";
768
769 return s;
770}
771
772static std::string SplatLane(unsigned nElts, const std::string &vec,
773 const std::string &lane) {
774 std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
775 for (unsigned i = 0; i < nElts; ++i)
776 s += ", " + lane;
777 s += ")";
778 return s;
779}
780
781static unsigned GetNumElements(StringRef typestr, bool &quad) {
782 quad = false;
783 bool dummy = false;
784 char type = ClassifyType(typestr, quad, dummy, dummy);
785 unsigned nElts = 0;
786 switch (type) {
787 case 'c': nElts = 8; break;
788 case 's': nElts = 4; break;
789 case 'i': nElts = 2; break;
790 case 'l': nElts = 1; break;
791 case 'h': nElts = 4; break;
792 case 'f': nElts = 2; break;
793 default:
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +0000794 PrintFatalError("unhandled type!");
Peter Collingbourne51d77772011-10-06 13:03:08 +0000795 }
796 if (quad) nElts <<= 1;
797 return nElts;
798}
799
800// Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
801static std::string GenOpString(OpKind op, const std::string &proto,
802 StringRef typestr) {
803 bool quad;
804 unsigned nElts = GetNumElements(typestr, quad);
805 bool define = UseMacro(proto);
806
807 std::string ts = TypeString(proto[0], typestr);
808 std::string s;
809 if (!define) {
810 s = "return ";
811 }
812
813 switch(op) {
814 case OpAdd:
815 s += "__a + __b;";
816 break;
817 case OpAddl:
818 s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
819 break;
820 case OpAddw:
821 s += "__a + " + Extend(typestr, "__b") + ";";
822 break;
823 case OpSub:
824 s += "__a - __b;";
825 break;
826 case OpSubl:
827 s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
828 break;
829 case OpSubw:
830 s += "__a - " + Extend(typestr, "__b") + ";";
831 break;
832 case OpMulN:
833 s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
834 break;
835 case OpMulLane:
836 s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
837 break;
838 case OpMul:
839 s += "__a * __b;";
840 break;
841 case OpMullLane:
842 s += MangleName("vmull", typestr, ClassS) + "(__a, " +
843 SplatLane(nElts, "__b", "__c") + ");";
844 break;
845 case OpMlaN:
846 s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
847 break;
848 case OpMlaLane:
849 s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
850 break;
851 case OpMla:
852 s += "__a + (__b * __c);";
853 break;
854 case OpMlalN:
855 s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, " +
856 Duplicate(nElts, typestr, "__c") + ");";
857 break;
858 case OpMlalLane:
859 s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, " +
860 SplatLane(nElts, "__c", "__d") + ");";
861 break;
862 case OpMlal:
863 s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, __c);";
864 break;
865 case OpMlsN:
866 s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
867 break;
868 case OpMlsLane:
869 s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
870 break;
871 case OpMls:
872 s += "__a - (__b * __c);";
873 break;
874 case OpMlslN:
875 s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, " +
876 Duplicate(nElts, typestr, "__c") + ");";
877 break;
878 case OpMlslLane:
879 s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, " +
880 SplatLane(nElts, "__c", "__d") + ");";
881 break;
882 case OpMlsl:
883 s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, __c);";
884 break;
885 case OpQDMullLane:
886 s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
887 SplatLane(nElts, "__b", "__c") + ");";
888 break;
889 case OpQDMlalLane:
890 s += MangleName("vqdmlal", typestr, ClassS) + "(__a, __b, " +
891 SplatLane(nElts, "__c", "__d") + ");";
892 break;
893 case OpQDMlslLane:
894 s += MangleName("vqdmlsl", typestr, ClassS) + "(__a, __b, " +
895 SplatLane(nElts, "__c", "__d") + ");";
896 break;
897 case OpQDMulhLane:
898 s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
899 SplatLane(nElts, "__b", "__c") + ");";
900 break;
901 case OpQRDMulhLane:
902 s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
903 SplatLane(nElts, "__b", "__c") + ");";
904 break;
905 case OpEq:
906 s += "(" + ts + ")(__a == __b);";
907 break;
908 case OpGe:
909 s += "(" + ts + ")(__a >= __b);";
910 break;
911 case OpLe:
912 s += "(" + ts + ")(__a <= __b);";
913 break;
914 case OpGt:
915 s += "(" + ts + ")(__a > __b);";
916 break;
917 case OpLt:
918 s += "(" + ts + ")(__a < __b);";
919 break;
920 case OpNeg:
921 s += " -__a;";
922 break;
923 case OpNot:
924 s += " ~__a;";
925 break;
926 case OpAnd:
927 s += "__a & __b;";
928 break;
929 case OpOr:
930 s += "__a | __b;";
931 break;
932 case OpXor:
933 s += "__a ^ __b;";
934 break;
935 case OpAndNot:
936 s += "__a & ~__b;";
937 break;
938 case OpOrNot:
939 s += "__a | ~__b;";
940 break;
941 case OpCast:
942 s += "(" + ts + ")__a;";
943 break;
944 case OpConcat:
945 s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
946 s += ", (int64x1_t)__b, 0, 1);";
947 break;
948 case OpHi:
949 s += "(" + ts +
950 ")__builtin_shufflevector((int64x2_t)__a, (int64x2_t)__a, 1);";
951 break;
952 case OpLo:
953 s += "(" + ts +
954 ")__builtin_shufflevector((int64x2_t)__a, (int64x2_t)__a, 0);";
955 break;
956 case OpDup:
957 s += Duplicate(nElts, typestr, "__a") + ";";
958 break;
959 case OpDupLane:
960 s += SplatLane(nElts, "__a", "__b") + ";";
961 break;
962 case OpSelect:
963 // ((0 & 1) | (~0 & 2))
964 s += "(" + ts + ")";
965 ts = TypeString(proto[1], typestr);
966 s += "((__a & (" + ts + ")__b) | ";
967 s += "(~__a & (" + ts + ")__c));";
968 break;
969 case OpRev16:
970 s += "__builtin_shufflevector(__a, __a";
971 for (unsigned i = 2; i <= nElts; i += 2)
972 for (unsigned j = 0; j != 2; ++j)
973 s += ", " + utostr(i - j - 1);
974 s += ");";
975 break;
976 case OpRev32: {
977 unsigned WordElts = nElts >> (1 + (int)quad);
978 s += "__builtin_shufflevector(__a, __a";
979 for (unsigned i = WordElts; i <= nElts; i += WordElts)
980 for (unsigned j = 0; j != WordElts; ++j)
981 s += ", " + utostr(i - j - 1);
982 s += ");";
983 break;
984 }
985 case OpRev64: {
986 unsigned DblWordElts = nElts >> (int)quad;
987 s += "__builtin_shufflevector(__a, __a";
988 for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
989 for (unsigned j = 0; j != DblWordElts; ++j)
990 s += ", " + utostr(i - j - 1);
991 s += ");";
992 break;
993 }
994 case OpAbdl: {
995 std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
996 if (typestr[0] != 'U') {
997 // vabd results are always unsigned and must be zero-extended.
998 std::string utype = "U" + typestr.str();
999 s += "(" + TypeString(proto[0], typestr) + ")";
1000 abd = "(" + TypeString('d', utype) + ")" + abd;
1001 s += Extend(utype, abd) + ";";
1002 } else {
1003 s += Extend(typestr, abd) + ";";
1004 }
1005 break;
1006 }
1007 case OpAba:
1008 s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
1009 break;
1010 case OpAbal: {
1011 s += "__a + ";
1012 std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
1013 if (typestr[0] != 'U') {
1014 // vabd results are always unsigned and must be zero-extended.
1015 std::string utype = "U" + typestr.str();
1016 s += "(" + TypeString(proto[0], typestr) + ")";
1017 abd = "(" + TypeString('d', utype) + ")" + abd;
1018 s += Extend(utype, abd) + ";";
1019 } else {
1020 s += Extend(typestr, abd) + ";";
1021 }
1022 break;
1023 }
1024 default:
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +00001025 PrintFatalError("unknown OpKind!");
Peter Collingbourne51d77772011-10-06 13:03:08 +00001026 }
1027 return s;
1028}
1029
1030static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
1031 unsigned mod = proto[0];
Peter Collingbourne51d77772011-10-06 13:03:08 +00001032
1033 if (mod == 'v' || mod == 'f')
1034 mod = proto[1];
1035
1036 bool quad = false;
1037 bool poly = false;
1038 bool usgn = false;
1039 bool scal = false;
1040 bool cnst = false;
1041 bool pntr = false;
1042
1043 // Base type to get the type string for.
1044 char type = ClassifyType(typestr, quad, poly, usgn);
1045
1046 // Based on the modifying character, change the type and width if necessary.
1047 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
1048
Bob Wilsonda95f732011-11-08 01:16:11 +00001049 NeonTypeFlags::EltType ET;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001050 switch (type) {
1051 case 'c':
Bob Wilsonda95f732011-11-08 01:16:11 +00001052 ET = poly ? NeonTypeFlags::Poly8 : NeonTypeFlags::Int8;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001053 break;
1054 case 's':
Bob Wilsonda95f732011-11-08 01:16:11 +00001055 ET = poly ? NeonTypeFlags::Poly16 : NeonTypeFlags::Int16;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001056 break;
1057 case 'i':
Bob Wilsonda95f732011-11-08 01:16:11 +00001058 ET = NeonTypeFlags::Int32;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001059 break;
1060 case 'l':
Bob Wilsonda95f732011-11-08 01:16:11 +00001061 ET = NeonTypeFlags::Int64;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001062 break;
1063 case 'h':
Bob Wilsonda95f732011-11-08 01:16:11 +00001064 ET = NeonTypeFlags::Float16;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001065 break;
1066 case 'f':
Bob Wilsonda95f732011-11-08 01:16:11 +00001067 ET = NeonTypeFlags::Float32;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001068 break;
1069 default:
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +00001070 PrintFatalError("unhandled type!");
Peter Collingbourne51d77772011-10-06 13:03:08 +00001071 }
Bob Wilsonda95f732011-11-08 01:16:11 +00001072 NeonTypeFlags Flags(ET, usgn, quad && proto[1] != 'g');
1073 return Flags.getFlags();
Peter Collingbourne51d77772011-10-06 13:03:08 +00001074}
1075
1076// Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
1077static std::string GenBuiltin(const std::string &name, const std::string &proto,
1078 StringRef typestr, ClassKind ck) {
1079 std::string s;
1080
1081 // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
1082 // sret-like argument.
1083 bool sret = (proto[0] >= '2' && proto[0] <= '4');
1084
1085 bool define = UseMacro(proto);
1086
1087 // Check if the prototype has a scalar operand with the type of the vector
1088 // elements. If not, bitcasting the args will take care of arg checking.
1089 // The actual signedness etc. will be taken care of with special enums.
1090 if (proto.find('s') == std::string::npos)
1091 ck = ClassB;
1092
1093 if (proto[0] != 'v') {
1094 std::string ts = TypeString(proto[0], typestr);
1095
1096 if (define) {
1097 if (sret)
1098 s += ts + " r; ";
1099 else
1100 s += "(" + ts + ")";
1101 } else if (sret) {
1102 s += ts + " r; ";
1103 } else {
1104 s += "return (" + ts + ")";
1105 }
1106 }
1107
1108 bool splat = proto.find('a') != std::string::npos;
1109
1110 s += "__builtin_neon_";
1111 if (splat) {
1112 // Call the non-splat builtin: chop off the "_n" suffix from the name.
1113 std::string vname(name, 0, name.size()-2);
1114 s += MangleName(vname, typestr, ck);
1115 } else {
1116 s += MangleName(name, typestr, ck);
1117 }
1118 s += "(";
1119
1120 // Pass the address of the return variable as the first argument to sret-like
1121 // builtins.
1122 if (sret)
1123 s += "&r, ";
1124
1125 char arg = 'a';
1126 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1127 std::string args = std::string(&arg, 1);
1128
1129 // Use the local temporaries instead of the macro arguments.
1130 args = "__" + args;
1131
1132 bool argQuad = false;
1133 bool argPoly = false;
1134 bool argUsgn = false;
1135 bool argScalar = false;
1136 bool dummy = false;
1137 char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
1138 argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
1139 dummy, dummy);
1140
1141 // Handle multiple-vector values specially, emitting each subvector as an
1142 // argument to the __builtin.
1143 if (proto[i] >= '2' && proto[i] <= '4') {
1144 // Check if an explicit cast is needed.
1145 if (argType != 'c' || argPoly || argUsgn)
1146 args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
1147
1148 for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
1149 s += args + ".val[" + utostr(vi) + "]";
1150 if ((vi + 1) < ve)
1151 s += ", ";
1152 }
1153 if ((i + 1) < e)
1154 s += ", ";
1155
1156 continue;
1157 }
1158
1159 if (splat && (i + 1) == e)
1160 args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
1161
1162 // Check if an explicit cast is needed.
1163 if ((splat || !argScalar) &&
1164 ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
1165 std::string argTypeStr = "c";
1166 if (ck != ClassB)
1167 argTypeStr = argType;
1168 if (argQuad)
1169 argTypeStr = "Q" + argTypeStr;
1170 args = "(" + TypeString('d', argTypeStr) + ")" + args;
1171 }
1172
1173 s += args;
1174 if ((i + 1) < e)
1175 s += ", ";
1176 }
1177
1178 // Extra constant integer to hold type class enum for this function, e.g. s8
1179 if (ck == ClassB)
1180 s += ", " + utostr(GetNeonEnum(proto, typestr));
1181
1182 s += ");";
1183
1184 if (proto[0] != 'v' && sret) {
1185 if (define)
1186 s += " r;";
1187 else
1188 s += " return r;";
1189 }
1190 return s;
1191}
1192
1193static std::string GenBuiltinDef(const std::string &name,
1194 const std::string &proto,
1195 StringRef typestr, ClassKind ck) {
1196 std::string s("BUILTIN(__builtin_neon_");
1197
1198 // If all types are the same size, bitcasting the args will take care
1199 // of arg checking. The actual signedness etc. will be taken care of with
1200 // special enums.
1201 if (proto.find('s') == std::string::npos)
1202 ck = ClassB;
1203
1204 s += MangleName(name, typestr, ck);
1205 s += ", \"";
1206
1207 for (unsigned i = 0, e = proto.size(); i != e; ++i)
1208 s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
1209
1210 // Extra constant integer to hold type class enum for this function, e.g. s8
1211 if (ck == ClassB)
1212 s += "i";
1213
1214 s += "\", \"n\")";
1215 return s;
1216}
1217
1218static std::string GenIntrinsic(const std::string &name,
1219 const std::string &proto,
1220 StringRef outTypeStr, StringRef inTypeStr,
1221 OpKind kind, ClassKind classKind) {
1222 assert(!proto.empty() && "");
Jim Grosbach667381b2012-05-09 18:17:30 +00001223 bool define = UseMacro(proto) && kind != OpUnavailable;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001224 std::string s;
1225
1226 // static always inline + return type
1227 if (define)
1228 s += "#define ";
1229 else
1230 s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1231
1232 // Function name with type suffix
1233 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1234 if (outTypeStr != inTypeStr) {
1235 // If the input type is different (e.g., for vreinterpret), append a suffix
1236 // for the input type. String off a "Q" (quad) prefix so that MangleName
1237 // does not insert another "q" in the name.
1238 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1239 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1240 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1241 }
1242 s += mangledName;
1243
1244 // Function arguments
1245 s += GenArgs(proto, inTypeStr);
1246
1247 // Definition.
1248 if (define) {
1249 s += " __extension__ ({ \\\n ";
1250 s += GenMacroLocals(proto, inTypeStr);
Jim Grosbach667381b2012-05-09 18:17:30 +00001251 } else if (kind == OpUnavailable) {
1252 s += " __attribute__((unavailable));\n";
1253 return s;
1254 } else
Jim Grosbach66981c72012-08-03 17:30:46 +00001255 s += " {\n ";
Peter Collingbourne51d77772011-10-06 13:03:08 +00001256
1257 if (kind != OpNone)
1258 s += GenOpString(kind, proto, outTypeStr);
1259 else
1260 s += GenBuiltin(name, proto, outTypeStr, classKind);
1261 if (define)
1262 s += " })";
1263 else
1264 s += " }";
1265 s += "\n";
1266 return s;
1267}
1268
1269/// run - Read the records in arm_neon.td and output arm_neon.h. arm_neon.h
1270/// is comprised of type definitions and function declarations.
1271void NeonEmitter::run(raw_ostream &OS) {
1272 OS <<
1273 "/*===---- arm_neon.h - ARM Neon intrinsics ------------------------------"
1274 "---===\n"
1275 " *\n"
1276 " * Permission is hereby granted, free of charge, to any person obtaining "
1277 "a copy\n"
1278 " * of this software and associated documentation files (the \"Software\"),"
1279 " to deal\n"
1280 " * in the Software without restriction, including without limitation the "
1281 "rights\n"
1282 " * to use, copy, modify, merge, publish, distribute, sublicense, "
1283 "and/or sell\n"
1284 " * copies of the Software, and to permit persons to whom the Software is\n"
1285 " * furnished to do so, subject to the following conditions:\n"
1286 " *\n"
1287 " * The above copyright notice and this permission notice shall be "
1288 "included in\n"
1289 " * all copies or substantial portions of the Software.\n"
1290 " *\n"
1291 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
1292 "EXPRESS OR\n"
1293 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
1294 "MERCHANTABILITY,\n"
1295 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
1296 "SHALL THE\n"
1297 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
1298 "OTHER\n"
1299 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
1300 "ARISING FROM,\n"
1301 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
1302 "DEALINGS IN\n"
1303 " * THE SOFTWARE.\n"
1304 " *\n"
1305 " *===--------------------------------------------------------------------"
1306 "---===\n"
1307 " */\n\n";
1308
1309 OS << "#ifndef __ARM_NEON_H\n";
1310 OS << "#define __ARM_NEON_H\n\n";
1311
1312 OS << "#ifndef __ARM_NEON__\n";
1313 OS << "#error \"NEON support not enabled\"\n";
1314 OS << "#endif\n\n";
1315
1316 OS << "#include <stdint.h>\n\n";
1317
1318 // Emit NEON-specific scalar typedefs.
1319 OS << "typedef float float32_t;\n";
1320 OS << "typedef int8_t poly8_t;\n";
1321 OS << "typedef int16_t poly16_t;\n";
1322 OS << "typedef uint16_t float16_t;\n";
1323
1324 // Emit Neon vector typedefs.
1325 std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1326 SmallVector<StringRef, 24> TDTypeVec;
1327 ParseTypes(0, TypedefTypes, TDTypeVec);
1328
1329 // Emit vector typedefs.
1330 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1331 bool dummy, quad = false, poly = false;
1332 (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1333 if (poly)
1334 OS << "typedef __attribute__((neon_polyvector_type(";
1335 else
1336 OS << "typedef __attribute__((neon_vector_type(";
1337
1338 unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1339 OS << utostr(nElts) << "))) ";
1340 if (nElts < 10)
1341 OS << " ";
1342
1343 OS << TypeString('s', TDTypeVec[i]);
1344 OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1345 }
1346 OS << "\n";
1347
1348 // Emit struct typedefs.
1349 for (unsigned vi = 2; vi != 5; ++vi) {
1350 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1351 std::string ts = TypeString('d', TDTypeVec[i]);
1352 std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1353 OS << "typedef struct " << vs << " {\n";
1354 OS << " " << ts << " val";
1355 OS << "[" << utostr(vi) << "]";
1356 OS << ";\n} ";
1357 OS << vs << ";\n\n";
1358 }
1359 }
1360
Bob Wilson1e8058f2013-04-12 20:17:20 +00001361 OS<<"#define __ai static inline __attribute__((__always_inline__, __nodebug__))\n\n";
Peter Collingbourne51d77772011-10-06 13:03:08 +00001362
1363 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1364
1365 // Emit vmovl, vmull and vabd intrinsics first so they can be used by other
1366 // intrinsics. (Some of the saturating multiply instructions are also
1367 // used to implement the corresponding "_lane" variants, but tablegen
1368 // sorts the records into alphabetical order so that the "_lane" variants
1369 // come after the intrinsics they use.)
1370 emitIntrinsic(OS, Records.getDef("VMOVL"));
1371 emitIntrinsic(OS, Records.getDef("VMULL"));
1372 emitIntrinsic(OS, Records.getDef("VABD"));
1373
1374 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1375 Record *R = RV[i];
1376 if (R->getName() != "VMOVL" &&
1377 R->getName() != "VMULL" &&
1378 R->getName() != "VABD")
1379 emitIntrinsic(OS, R);
1380 }
1381
1382 OS << "#undef __ai\n\n";
1383 OS << "#endif /* __ARM_NEON_H */\n";
1384}
1385
1386/// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1387/// intrinsics specified by record R.
1388void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1389 std::string name = R->getValueAsString("Name");
1390 std::string Proto = R->getValueAsString("Prototype");
1391 std::string Types = R->getValueAsString("Types");
1392
1393 SmallVector<StringRef, 16> TypeVec;
1394 ParseTypes(R, Types, TypeVec);
1395
1396 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1397
1398 ClassKind classKind = ClassNone;
1399 if (R->getSuperClasses().size() >= 2)
1400 classKind = ClassMap[R->getSuperClasses()[1]];
1401 if (classKind == ClassNone && kind == OpNone)
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +00001402 PrintFatalError(R->getLoc(), "Builtin has no class kind");
Peter Collingbourne51d77772011-10-06 13:03:08 +00001403
1404 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1405 if (kind == OpReinterpret) {
1406 bool outQuad = false;
1407 bool dummy = false;
1408 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1409 for (unsigned srcti = 0, srcte = TypeVec.size();
1410 srcti != srcte; ++srcti) {
1411 bool inQuad = false;
1412 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1413 if (srcti == ti || inQuad != outQuad)
1414 continue;
1415 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1416 OpCast, ClassS);
1417 }
1418 } else {
1419 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1420 kind, classKind);
1421 }
1422 }
1423 OS << "\n";
1424}
1425
1426static unsigned RangeFromType(const char mod, StringRef typestr) {
1427 // base type to get the type string for.
1428 bool quad = false, dummy = false;
1429 char type = ClassifyType(typestr, quad, dummy, dummy);
1430 type = ModType(mod, type, quad, dummy, dummy, dummy, dummy, dummy);
1431
1432 switch (type) {
1433 case 'c':
1434 return (8 << (int)quad) - 1;
1435 case 'h':
1436 case 's':
1437 return (4 << (int)quad) - 1;
1438 case 'f':
1439 case 'i':
1440 return (2 << (int)quad) - 1;
1441 case 'l':
1442 return (1 << (int)quad) - 1;
1443 default:
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +00001444 PrintFatalError("unhandled type!");
Peter Collingbourne51d77772011-10-06 13:03:08 +00001445 }
Peter Collingbourne51d77772011-10-06 13:03:08 +00001446}
1447
1448/// runHeader - Emit a file with sections defining:
1449/// 1. the NEON section of BuiltinsARM.def.
1450/// 2. the SemaChecking code for the type overload checking.
Jim Grosbach667381b2012-05-09 18:17:30 +00001451/// 3. the SemaChecking code for validation of intrinsic immediate arguments.
Peter Collingbourne51d77772011-10-06 13:03:08 +00001452void NeonEmitter::runHeader(raw_ostream &OS) {
1453 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1454
1455 StringMap<OpKind> EmittedMap;
1456
1457 // Generate BuiltinsARM.def for NEON
1458 OS << "#ifdef GET_NEON_BUILTINS\n";
1459 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1460 Record *R = RV[i];
1461 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1462 if (k != OpNone)
1463 continue;
1464
1465 std::string Proto = R->getValueAsString("Prototype");
1466
1467 // Functions with 'a' (the splat code) in the type prototype should not get
1468 // their own builtin as they use the non-splat variant.
1469 if (Proto.find('a') != std::string::npos)
1470 continue;
1471
1472 std::string Types = R->getValueAsString("Types");
1473 SmallVector<StringRef, 16> TypeVec;
1474 ParseTypes(R, Types, TypeVec);
1475
1476 if (R->getSuperClasses().size() < 2)
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +00001477 PrintFatalError(R->getLoc(), "Builtin has no class kind");
Peter Collingbourne51d77772011-10-06 13:03:08 +00001478
1479 std::string name = R->getValueAsString("Name");
1480 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1481
1482 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1483 // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1484 // that each unique BUILTIN() macro appears only once in the output
1485 // stream.
1486 std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1487 if (EmittedMap.count(bd))
1488 continue;
1489
1490 EmittedMap[bd] = OpNone;
1491 OS << bd << "\n";
1492 }
1493 }
1494 OS << "#endif\n\n";
1495
1496 // Generate the overloaded type checking code for SemaChecking.cpp
1497 OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1498 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1499 Record *R = RV[i];
1500 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1501 if (k != OpNone)
1502 continue;
1503
1504 std::string Proto = R->getValueAsString("Prototype");
1505 std::string Types = R->getValueAsString("Types");
1506 std::string name = R->getValueAsString("Name");
1507
1508 // Functions with 'a' (the splat code) in the type prototype should not get
1509 // their own builtin as they use the non-splat variant.
1510 if (Proto.find('a') != std::string::npos)
1511 continue;
1512
1513 // Functions which have a scalar argument cannot be overloaded, no need to
1514 // check them if we are emitting the type checking code.
1515 if (Proto.find('s') != std::string::npos)
1516 continue;
1517
1518 SmallVector<StringRef, 16> TypeVec;
1519 ParseTypes(R, Types, TypeVec);
1520
1521 if (R->getSuperClasses().size() < 2)
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +00001522 PrintFatalError(R->getLoc(), "Builtin has no class kind");
Peter Collingbourne51d77772011-10-06 13:03:08 +00001523
1524 int si = -1, qi = -1;
Richard Smithf8ee6bc2012-08-14 01:28:02 +00001525 uint64_t mask = 0, qmask = 0;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001526 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1527 // Generate the switch case(s) for this builtin for the type validation.
1528 bool quad = false, poly = false, usgn = false;
1529 (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1530
1531 if (quad) {
1532 qi = ti;
Richard Smithf8ee6bc2012-08-14 01:28:02 +00001533 qmask |= 1ULL << GetNeonEnum(Proto, TypeVec[ti]);
Peter Collingbourne51d77772011-10-06 13:03:08 +00001534 } else {
1535 si = ti;
Richard Smithf8ee6bc2012-08-14 01:28:02 +00001536 mask |= 1ULL << GetNeonEnum(Proto, TypeVec[ti]);
Peter Collingbourne51d77772011-10-06 13:03:08 +00001537 }
1538 }
Bob Wilson46482552011-11-16 21:32:23 +00001539
1540 // Check if the builtin function has a pointer or const pointer argument.
1541 int PtrArgNum = -1;
1542 bool HasConstPtr = false;
1543 for (unsigned arg = 1, arge = Proto.size(); arg != arge; ++arg) {
1544 char ArgType = Proto[arg];
1545 if (ArgType == 'c') {
1546 HasConstPtr = true;
1547 PtrArgNum = arg - 1;
1548 break;
1549 }
1550 if (ArgType == 'p') {
1551 PtrArgNum = arg - 1;
1552 break;
1553 }
1554 }
1555 // For sret builtins, adjust the pointer argument index.
1556 if (PtrArgNum >= 0 && (Proto[0] >= '2' && Proto[0] <= '4'))
1557 PtrArgNum += 1;
1558
Bob Wilson9082cdd2011-12-20 06:16:48 +00001559 // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
1560 // and vst1_lane intrinsics. Using a pointer to the vector element
1561 // type with one of those operations causes codegen to select an aligned
1562 // load/store instruction. If you want an unaligned operation,
1563 // the pointer argument needs to have less alignment than element type,
1564 // so just accept any pointer type.
1565 if (name == "vld1_lane" || name == "vld1_dup" || name == "vst1_lane") {
1566 PtrArgNum = -1;
1567 HasConstPtr = false;
1568 }
1569
Bob Wilson6f9f03e2011-11-08 05:04:11 +00001570 if (mask) {
Peter Collingbourne51d77772011-10-06 13:03:08 +00001571 OS << "case ARM::BI__builtin_neon_"
1572 << MangleName(name, TypeVec[si], ClassB)
Richard Smithb27660a2012-08-14 03:55:16 +00001573 << ": mask = " << "0x" << utohexstr(mask) << "ULL";
Bob Wilson46482552011-11-16 21:32:23 +00001574 if (PtrArgNum >= 0)
1575 OS << "; PtrArgNum = " << PtrArgNum;
Bob Wilson6f9f03e2011-11-08 05:04:11 +00001576 if (HasConstPtr)
1577 OS << "; HasConstPtr = true";
1578 OS << "; break;\n";
1579 }
1580 if (qmask) {
Peter Collingbourne51d77772011-10-06 13:03:08 +00001581 OS << "case ARM::BI__builtin_neon_"
1582 << MangleName(name, TypeVec[qi], ClassB)
Richard Smithb27660a2012-08-14 03:55:16 +00001583 << ": mask = " << "0x" << utohexstr(qmask) << "ULL";
Bob Wilson46482552011-11-16 21:32:23 +00001584 if (PtrArgNum >= 0)
1585 OS << "; PtrArgNum = " << PtrArgNum;
Bob Wilson6f9f03e2011-11-08 05:04:11 +00001586 if (HasConstPtr)
1587 OS << "; HasConstPtr = true";
1588 OS << "; break;\n";
1589 }
Peter Collingbourne51d77772011-10-06 13:03:08 +00001590 }
1591 OS << "#endif\n\n";
1592
1593 // Generate the intrinsic range checking code for shift/lane immediates.
1594 OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1595 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1596 Record *R = RV[i];
1597
1598 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1599 if (k != OpNone)
1600 continue;
1601
1602 std::string name = R->getValueAsString("Name");
1603 std::string Proto = R->getValueAsString("Prototype");
1604 std::string Types = R->getValueAsString("Types");
1605
1606 // Functions with 'a' (the splat code) in the type prototype should not get
1607 // their own builtin as they use the non-splat variant.
1608 if (Proto.find('a') != std::string::npos)
1609 continue;
1610
1611 // Functions which do not have an immediate do not need to have range
1612 // checking code emitted.
1613 size_t immPos = Proto.find('i');
1614 if (immPos == std::string::npos)
1615 continue;
1616
1617 SmallVector<StringRef, 16> TypeVec;
1618 ParseTypes(R, Types, TypeVec);
1619
1620 if (R->getSuperClasses().size() < 2)
Joerg Sonnenberger38859ee2012-10-25 16:37:08 +00001621 PrintFatalError(R->getLoc(), "Builtin has no class kind");
Peter Collingbourne51d77772011-10-06 13:03:08 +00001622
1623 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1624
1625 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1626 std::string namestr, shiftstr, rangestr;
1627
1628 if (R->getValueAsBit("isVCVT_N")) {
1629 // VCVT between floating- and fixed-point values takes an immediate
1630 // in the range 1 to 32.
1631 ck = ClassB;
1632 rangestr = "l = 1; u = 31"; // upper bound = l + u
1633 } else if (Proto.find('s') == std::string::npos) {
1634 // Builtins which are overloaded by type will need to have their upper
1635 // bound computed at Sema time based on the type constant.
1636 ck = ClassB;
1637 if (R->getValueAsBit("isShift")) {
1638 shiftstr = ", true";
1639
1640 // Right shifts have an 'r' in the name, left shifts do not.
1641 if (name.find('r') != std::string::npos)
1642 rangestr = "l = 1; ";
1643 }
1644 rangestr += "u = RFT(TV" + shiftstr + ")";
1645 } else {
1646 // The immediate generally refers to a lane in the preceding argument.
1647 assert(immPos > 0 && "unexpected immediate operand");
1648 rangestr = "u = " + utostr(RangeFromType(Proto[immPos-1], TypeVec[ti]));
1649 }
1650 // Make sure cases appear only once by uniquing them in a string map.
1651 namestr = MangleName(name, TypeVec[ti], ck);
1652 if (EmittedMap.count(namestr))
1653 continue;
1654 EmittedMap[namestr] = OpNone;
1655
1656 // Calculate the index of the immediate that should be range checked.
1657 unsigned immidx = 0;
1658
1659 // Builtins that return a struct of multiple vectors have an extra
1660 // leading arg for the struct return.
1661 if (Proto[0] >= '2' && Proto[0] <= '4')
1662 ++immidx;
1663
1664 // Add one to the index for each argument until we reach the immediate
1665 // to be checked. Structs of vectors are passed as multiple arguments.
1666 for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1667 switch (Proto[ii]) {
1668 default: immidx += 1; break;
1669 case '2': immidx += 2; break;
1670 case '3': immidx += 3; break;
1671 case '4': immidx += 4; break;
1672 case 'i': ie = ii + 1; break;
1673 }
1674 }
1675 OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1676 << ": i = " << immidx << "; " << rangestr << "; break;\n";
1677 }
1678 }
1679 OS << "#endif\n\n";
1680}
1681
1682/// GenTest - Write out a test for the intrinsic specified by the name and
1683/// type strings, including the embedded patterns for FileCheck to match.
1684static std::string GenTest(const std::string &name,
1685 const std::string &proto,
1686 StringRef outTypeStr, StringRef inTypeStr,
1687 bool isShift) {
1688 assert(!proto.empty() && "");
1689 std::string s;
1690
1691 // Function name with type suffix
1692 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1693 if (outTypeStr != inTypeStr) {
1694 // If the input type is different (e.g., for vreinterpret), append a suffix
1695 // for the input type. String off a "Q" (quad) prefix so that MangleName
1696 // does not insert another "q" in the name.
1697 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1698 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1699 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1700 }
1701
1702 // Emit the FileCheck patterns.
1703 s += "// CHECK: test_" + mangledName + "\n";
1704 // s += "// CHECK: \n"; // FIXME: + expected instruction opcode.
1705
1706 // Emit the start of the test function.
1707 s += TypeString(proto[0], outTypeStr) + " test_" + mangledName + "(";
1708 char arg = 'a';
1709 std::string comma;
1710 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1711 // Do not create arguments for values that must be immediate constants.
1712 if (proto[i] == 'i')
1713 continue;
1714 s += comma + TypeString(proto[i], inTypeStr) + " ";
1715 s.push_back(arg);
1716 comma = ", ";
1717 }
Jim Grosbachb4a54252012-05-30 18:18:29 +00001718 s += ") {\n ";
Peter Collingbourne51d77772011-10-06 13:03:08 +00001719
1720 if (proto[0] != 'v')
1721 s += "return ";
1722 s += mangledName + "(";
1723 arg = 'a';
1724 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1725 if (proto[i] == 'i') {
1726 // For immediate operands, test the maximum value.
1727 if (isShift)
1728 s += "1"; // FIXME
1729 else
1730 // The immediate generally refers to a lane in the preceding argument.
1731 s += utostr(RangeFromType(proto[i-1], inTypeStr));
1732 } else {
1733 s.push_back(arg);
1734 }
1735 if ((i + 1) < e)
1736 s += ", ";
1737 }
1738 s += ");\n}\n\n";
1739 return s;
1740}
1741
1742/// runTests - Write out a complete set of tests for all of the Neon
1743/// intrinsics.
1744void NeonEmitter::runTests(raw_ostream &OS) {
1745 OS <<
1746 "// RUN: %clang_cc1 -triple thumbv7-apple-darwin \\\n"
1747 "// RUN: -target-cpu cortex-a9 -ffreestanding -S -o - %s | FileCheck %s\n"
1748 "\n"
1749 "#include <arm_neon.h>\n"
1750 "\n";
1751
1752 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1753 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1754 Record *R = RV[i];
1755 std::string name = R->getValueAsString("Name");
1756 std::string Proto = R->getValueAsString("Prototype");
1757 std::string Types = R->getValueAsString("Types");
1758 bool isShift = R->getValueAsBit("isShift");
1759
1760 SmallVector<StringRef, 16> TypeVec;
1761 ParseTypes(R, Types, TypeVec);
1762
1763 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
Jim Grosbach667381b2012-05-09 18:17:30 +00001764 if (kind == OpUnavailable)
1765 continue;
Peter Collingbourne51d77772011-10-06 13:03:08 +00001766 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1767 if (kind == OpReinterpret) {
1768 bool outQuad = false;
1769 bool dummy = false;
1770 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1771 for (unsigned srcti = 0, srcte = TypeVec.size();
1772 srcti != srcte; ++srcti) {
1773 bool inQuad = false;
1774 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1775 if (srcti == ti || inQuad != outQuad)
1776 continue;
1777 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[srcti], isShift);
1778 }
1779 } else {
1780 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift);
1781 }
1782 }
1783 OS << "\n";
1784 }
1785}
1786
Jakob Stoklund Olesen3cc509b2012-06-13 05:12:41 +00001787namespace clang {
1788void EmitNeon(RecordKeeper &Records, raw_ostream &OS) {
1789 NeonEmitter(Records).run(OS);
1790}
1791void EmitNeonSema(RecordKeeper &Records, raw_ostream &OS) {
1792 NeonEmitter(Records).runHeader(OS);
1793}
1794void EmitNeonTest(RecordKeeper &Records, raw_ostream &OS) {
1795 NeonEmitter(Records).runTests(OS);
1796}
1797} // End namespace clang