blob: 37fd7f9462f5ab7c2396e20fc47f134b43b770c0 [file] [log] [blame]
Peter Collingbournebee583f2011-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
James Molloydee4ab02014-06-17 13:11:27 +000021// called, rather than the normal run() entry point.
22//
23// See also the documentation in include/clang/Basic/arm_neon.td.
Peter Collingbournebee583f2011-10-06 13:03:08 +000024//
25//===----------------------------------------------------------------------===//
26
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000027#include "llvm/ADT/DenseMap.h"
Craig Topperbccb7732015-04-24 06:53:50 +000028#include "llvm/ADT/STLExtras.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000029#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000032#include "llvm/ADT/StringMap.h"
David Blaikie8a40f702012-01-17 06:56:22 +000033#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000034#include "llvm/TableGen/Error.h"
35#include "llvm/TableGen/Record.h"
James Molloydee4ab02014-06-17 13:11:27 +000036#include "llvm/TableGen/SetTheory.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000037#include "llvm/TableGen/TableGenBackend.h"
James Molloydee4ab02014-06-17 13:11:27 +000038#include <algorithm>
David Blaikie4c96a5e2015-08-06 18:29:32 +000039#include <deque>
Chandler Carruth575bc3ba2015-01-14 11:23:58 +000040#include <map>
41#include <sstream>
42#include <string>
43#include <vector>
Peter Collingbournebee583f2011-10-06 13:03:08 +000044using namespace llvm;
45
James Molloydee4ab02014-06-17 13:11:27 +000046namespace {
47
48// While globals are generally bad, this one allows us to perform assertions
49// liberally and somehow still trace them back to the def they indirectly
50// came from.
51static Record *CurrentRecord = nullptr;
52static void assert_with_loc(bool Assertion, const std::string &Str) {
53 if (!Assertion) {
54 if (CurrentRecord)
55 PrintFatalError(CurrentRecord->getLoc(), Str);
56 else
57 PrintFatalError(Str);
58 }
59}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000060
61enum ClassKind {
62 ClassNone,
James Molloydee4ab02014-06-17 13:11:27 +000063 ClassI, // generic integer instruction, e.g., "i8" suffix
64 ClassS, // signed/unsigned/poly, e.g., "s8", "u8" or "p8" suffix
65 ClassW, // width-specific instruction, e.g., "8" suffix
66 ClassB, // bitcast arguments with enum argument to specify type
67 ClassL, // Logical instructions which are op instructions
68 // but we need to not emit any suffix for in our
69 // tests.
70 ClassNoTest // Instructions which we do not test since they are
71 // not TRUE instructions.
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000072};
73
74/// NeonTypeFlags - Flags to identify the types for overloaded Neon
75/// builtins. These must be kept in sync with the flags in
76/// include/clang/Basic/TargetBuiltins.h.
James Molloydee4ab02014-06-17 13:11:27 +000077namespace NeonTypeFlags {
78enum { EltTypeMask = 0xf, UnsignedFlag = 0x10, QuadFlag = 0x20 };
79
80enum EltType {
81 Int8,
82 Int16,
83 Int32,
84 Int64,
85 Poly8,
86 Poly16,
87 Poly64,
88 Poly128,
89 Float16,
90 Float32,
91 Float64
92};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000093}
James Molloydee4ab02014-06-17 13:11:27 +000094
95class Intrinsic;
96class NeonEmitter;
97class Type;
98class Variable;
99
100//===----------------------------------------------------------------------===//
101// TypeSpec
102//===----------------------------------------------------------------------===//
103
104/// A TypeSpec is just a simple wrapper around a string, but gets its own type
105/// for strong typing purposes.
106///
107/// A TypeSpec can be used to create a type.
108class TypeSpec : public std::string {
109public:
110 static std::vector<TypeSpec> fromTypeSpecs(StringRef Str) {
111 std::vector<TypeSpec> Ret;
112 TypeSpec Acc;
113 for (char I : Str.str()) {
114 if (islower(I)) {
115 Acc.push_back(I);
116 Ret.push_back(TypeSpec(Acc));
117 Acc.clear();
118 } else {
119 Acc.push_back(I);
120 }
121 }
122 return Ret;
123 }
124};
125
126//===----------------------------------------------------------------------===//
127// Type
128//===----------------------------------------------------------------------===//
129
130/// A Type. Not much more to say here.
131class Type {
132private:
133 TypeSpec TS;
134
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000135 bool Float, Signed, Immediate, Void, Poly, Constant, Pointer;
James Molloydee4ab02014-06-17 13:11:27 +0000136 // ScalarForMangling and NoManglingQ are really not suited to live here as
137 // they are not related to the type. But they live in the TypeSpec (not the
138 // prototype), so this is really the only place to store them.
139 bool ScalarForMangling, NoManglingQ;
140 unsigned Bitwidth, ElementBitwidth, NumVectors;
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000141
142public:
James Molloydee4ab02014-06-17 13:11:27 +0000143 Type()
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000144 : Float(false), Signed(false), Immediate(false), Void(true), Poly(false),
145 Constant(false), Pointer(false), ScalarForMangling(false),
146 NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000147
James Molloydee4ab02014-06-17 13:11:27 +0000148 Type(TypeSpec TS, char CharMod)
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000149 : TS(TS), Float(false), Signed(false), Immediate(false), Void(false),
150 Poly(false), Constant(false), Pointer(false), ScalarForMangling(false),
James Molloydee4ab02014-06-17 13:11:27 +0000151 NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {
152 applyModifier(CharMod);
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000153 }
154
James Molloydee4ab02014-06-17 13:11:27 +0000155 /// Returns a type representing "void".
156 static Type getVoid() { return Type(); }
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000157
James Molloydee4ab02014-06-17 13:11:27 +0000158 bool operator==(const Type &Other) const { return str() == Other.str(); }
159 bool operator!=(const Type &Other) const { return !operator==(Other); }
160
161 //
162 // Query functions
163 //
164 bool isScalarForMangling() const { return ScalarForMangling; }
165 bool noManglingQ() const { return NoManglingQ; }
166
167 bool isPointer() const { return Pointer; }
168 bool isFloating() const { return Float; }
169 bool isInteger() const { return !Float && !Poly; }
170 bool isSigned() const { return Signed; }
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000171 bool isImmediate() const { return Immediate; }
James Molloydee4ab02014-06-17 13:11:27 +0000172 bool isScalar() const { return NumVectors == 0; }
173 bool isVector() const { return NumVectors > 0; }
174 bool isFloat() const { return Float && ElementBitwidth == 32; }
175 bool isDouble() const { return Float && ElementBitwidth == 64; }
176 bool isHalf() const { return Float && ElementBitwidth == 16; }
177 bool isPoly() const { return Poly; }
178 bool isChar() const { return ElementBitwidth == 8; }
179 bool isShort() const { return !Float && ElementBitwidth == 16; }
180 bool isInt() const { return !Float && ElementBitwidth == 32; }
181 bool isLong() const { return !Float && ElementBitwidth == 64; }
182 bool isVoid() const { return Void; }
183 unsigned getNumElements() const { return Bitwidth / ElementBitwidth; }
184 unsigned getSizeInBits() const { return Bitwidth; }
185 unsigned getElementSizeInBits() const { return ElementBitwidth; }
186 unsigned getNumVectors() const { return NumVectors; }
187
188 //
189 // Mutator functions
190 //
191 void makeUnsigned() { Signed = false; }
192 void makeSigned() { Signed = true; }
193 void makeInteger(unsigned ElemWidth, bool Sign) {
194 Float = false;
195 Poly = false;
196 Signed = Sign;
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000197 Immediate = false;
198 ElementBitwidth = ElemWidth;
199 }
200 void makeImmediate(unsigned ElemWidth) {
201 Float = false;
202 Poly = false;
203 Signed = true;
204 Immediate = true;
James Molloydee4ab02014-06-17 13:11:27 +0000205 ElementBitwidth = ElemWidth;
206 }
207 void makeScalar() {
208 Bitwidth = ElementBitwidth;
209 NumVectors = 0;
210 }
211 void makeOneVector() {
212 assert(isVector());
213 NumVectors = 1;
214 }
215 void doubleLanes() {
216 assert_with_loc(Bitwidth != 128, "Can't get bigger than 128!");
217 Bitwidth = 128;
218 }
219 void halveLanes() {
220 assert_with_loc(Bitwidth != 64, "Can't get smaller than 64!");
221 Bitwidth = 64;
222 }
223
224 /// Return the C string representation of a type, which is the typename
225 /// defined in stdint.h or arm_neon.h.
226 std::string str() const;
227
228 /// Return the string representation of a type, which is an encoded
229 /// string for passing to the BUILTIN() macro in Builtins.def.
230 std::string builtin_str() const;
231
232 /// Return the value in NeonTypeFlags for this type.
233 unsigned getNeonEnum() const;
234
235 /// Parse a type from a stdint.h or arm_neon.h typedef name,
236 /// for example uint32x2_t or int64_t.
237 static Type fromTypedefName(StringRef Name);
238
239private:
240 /// Creates the type based on the typespec string in TS.
241 /// Sets "Quad" to true if the "Q" or "H" modifiers were
242 /// seen. This is needed by applyModifier as some modifiers
243 /// only take effect if the type size was changed by "Q" or "H".
244 void applyTypespec(bool &Quad);
245 /// Applies a prototype modifier to the type.
246 void applyModifier(char Mod);
247};
248
249//===----------------------------------------------------------------------===//
250// Variable
251//===----------------------------------------------------------------------===//
252
253/// A variable is a simple class that just has a type and a name.
254class Variable {
255 Type T;
256 std::string N;
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000257
258public:
James Molloydee4ab02014-06-17 13:11:27 +0000259 Variable() : T(Type::getVoid()), N("") {}
260 Variable(Type T, std::string N) : T(T), N(N) {}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000261
James Molloydee4ab02014-06-17 13:11:27 +0000262 Type getType() const { return T; }
263 std::string getName() const { return "__" + N; }
264};
265
266//===----------------------------------------------------------------------===//
267// Intrinsic
268//===----------------------------------------------------------------------===//
269
270/// The main grunt class. This represents an instantiation of an intrinsic with
271/// a particular typespec and prototype.
272class Intrinsic {
James Molloyb452f782014-06-27 11:53:35 +0000273 friend class DagEmitter;
274
James Molloydee4ab02014-06-17 13:11:27 +0000275 /// The Record this intrinsic was created from.
276 Record *R;
277 /// The unmangled name and prototype.
278 std::string Name, Proto;
279 /// The input and output typespecs. InTS == OutTS except when
280 /// CartesianProductOfTypes is 1 - this is the case for vreinterpret.
281 TypeSpec OutTS, InTS;
282 /// The base class kind. Most intrinsics use ClassS, which has full type
283 /// info for integers (s32/u32). Some use ClassI, which doesn't care about
284 /// signedness (i32), while some (ClassB) have no type at all, only a width
285 /// (32).
286 ClassKind CK;
287 /// The list of DAGs for the body. May be empty, in which case we should
288 /// emit a builtin call.
289 ListInit *Body;
290 /// The architectural #ifdef guard.
291 std::string Guard;
292 /// Set if the Unvailable bit is 1. This means we don't generate a body,
293 /// just an "unavailable" attribute on a declaration.
294 bool IsUnavailable;
James Molloyb452f782014-06-27 11:53:35 +0000295 /// Is this intrinsic safe for big-endian? or does it need its arguments
296 /// reversing?
297 bool BigEndianSafe;
James Molloydee4ab02014-06-17 13:11:27 +0000298
299 /// The types of return value [0] and parameters [1..].
300 std::vector<Type> Types;
301 /// The local variables defined.
302 std::map<std::string, Variable> Variables;
303 /// NeededEarly - set if any other intrinsic depends on this intrinsic.
304 bool NeededEarly;
305 /// UseMacro - set if we should implement using a macro or unset for a
306 /// function.
307 bool UseMacro;
308 /// The set of intrinsics that this intrinsic uses/requires.
309 std::set<Intrinsic *> Dependencies;
310 /// The "base type", which is Type('d', OutTS). InBaseType is only
311 /// different if CartesianProductOfTypes = 1 (for vreinterpret).
312 Type BaseType, InBaseType;
313 /// The return variable.
314 Variable RetVar;
315 /// A postfix to apply to every variable. Defaults to "".
316 std::string VariablePostfix;
317
318 NeonEmitter &Emitter;
319 std::stringstream OS;
320
321public:
322 Intrinsic(Record *R, StringRef Name, StringRef Proto, TypeSpec OutTS,
323 TypeSpec InTS, ClassKind CK, ListInit *Body, NeonEmitter &Emitter,
James Molloyb452f782014-06-27 11:53:35 +0000324 StringRef Guard, bool IsUnavailable, bool BigEndianSafe)
James Molloydee4ab02014-06-17 13:11:27 +0000325 : R(R), Name(Name.str()), Proto(Proto.str()), OutTS(OutTS), InTS(InTS),
326 CK(CK), Body(Body), Guard(Guard.str()), IsUnavailable(IsUnavailable),
James Molloyb452f782014-06-27 11:53:35 +0000327 BigEndianSafe(BigEndianSafe), NeededEarly(false), UseMacro(false),
328 BaseType(OutTS, 'd'), InBaseType(InTS, 'd'), Emitter(Emitter) {
James Molloydee4ab02014-06-17 13:11:27 +0000329 // If this builtin takes an immediate argument, we need to #define it rather
330 // than use a standard declaration, so that SemaChecking can range check
331 // the immediate passed by the user.
332 if (Proto.find('i') != std::string::npos)
333 UseMacro = true;
334
335 // Pointer arguments need to use macros to avoid hiding aligned attributes
336 // from the pointer type.
337 if (Proto.find('p') != std::string::npos ||
338 Proto.find('c') != std::string::npos)
339 UseMacro = true;
340
341 // It is not permitted to pass or return an __fp16 by value, so intrinsics
342 // taking a scalar float16_t must be implemented as macros.
343 if (OutTS.find('h') != std::string::npos &&
344 Proto.find('s') != std::string::npos)
345 UseMacro = true;
346
347 // Modify the TypeSpec per-argument to get a concrete Type, and create
348 // known variables for each.
349 // Types[0] is the return value.
Benjamin Kramer3204b152015-05-29 19:42:19 +0000350 Types.emplace_back(OutTS, Proto[0]);
James Molloydee4ab02014-06-17 13:11:27 +0000351 for (unsigned I = 1; I < Proto.size(); ++I)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000352 Types.emplace_back(InTS, Proto[I]);
James Molloydee4ab02014-06-17 13:11:27 +0000353 }
354
355 /// Get the Record that this intrinsic is based off.
356 Record *getRecord() const { return R; }
357 /// Get the set of Intrinsics that this intrinsic calls.
358 /// this is the set of immediate dependencies, NOT the
359 /// transitive closure.
360 const std::set<Intrinsic *> &getDependencies() const { return Dependencies; }
361 /// Get the architectural guard string (#ifdef).
362 std::string getGuard() const { return Guard; }
363 /// Get the non-mangled name.
364 std::string getName() const { return Name; }
365
366 /// Return true if the intrinsic takes an immediate operand.
367 bool hasImmediate() const {
368 return Proto.find('i') != std::string::npos;
369 }
370 /// Return the parameter index of the immediate operand.
371 unsigned getImmediateIdx() const {
372 assert(hasImmediate());
373 unsigned Idx = Proto.find('i');
374 assert(Idx > 0 && "Can't return an immediate!");
375 return Idx - 1;
376 }
377
378 /// Return true if the intrinsic takes an splat operand.
379 bool hasSplat() const { return Proto.find('a') != std::string::npos; }
380 /// Return the parameter index of the splat operand.
381 unsigned getSplatIdx() const {
382 assert(hasSplat());
383 unsigned Idx = Proto.find('a');
384 assert(Idx > 0 && "Can't return a splat!");
385 return Idx - 1;
386 }
387
388 unsigned getNumParams() const { return Proto.size() - 1; }
389 Type getReturnType() const { return Types[0]; }
390 Type getParamType(unsigned I) const { return Types[I + 1]; }
391 Type getBaseType() const { return BaseType; }
392 /// Return the raw prototype string.
393 std::string getProto() const { return Proto; }
394
395 /// Return true if the prototype has a scalar argument.
396 /// This does not return true for the "splat" code ('a').
David Blaikie4c96a5e2015-08-06 18:29:32 +0000397 bool protoHasScalar() const;
James Molloydee4ab02014-06-17 13:11:27 +0000398
399 /// Return the index that parameter PIndex will sit at
400 /// in a generated function call. This is often just PIndex,
401 /// but may not be as things such as multiple-vector operands
402 /// and sret parameters need to be taken into accont.
403 unsigned getGeneratedParamIdx(unsigned PIndex) {
404 unsigned Idx = 0;
405 if (getReturnType().getNumVectors() > 1)
406 // Multiple vectors are passed as sret.
407 ++Idx;
408
409 for (unsigned I = 0; I < PIndex; ++I)
410 Idx += std::max(1U, getParamType(I).getNumVectors());
411
412 return Idx;
413 }
414
415 bool hasBody() const { return Body && Body->getValues().size() > 0; }
416
417 void setNeededEarly() { NeededEarly = true; }
418
419 bool operator<(const Intrinsic &Other) const {
420 // Sort lexicographically on a two-tuple (Guard, Name)
421 if (Guard != Other.Guard)
422 return Guard < Other.Guard;
423 return Name < Other.Name;
424 }
425
426 ClassKind getClassKind(bool UseClassBIfScalar = false) {
427 if (UseClassBIfScalar && !protoHasScalar())
428 return ClassB;
429 return CK;
430 }
431
432 /// Return the name, mangled with type information.
433 /// If ForceClassS is true, use ClassS (u32/s32) instead
434 /// of the intrinsic's own type class.
David Blaikie4c96a5e2015-08-06 18:29:32 +0000435 std::string getMangledName(bool ForceClassS = false) const;
James Molloydee4ab02014-06-17 13:11:27 +0000436 /// Return the type code for a builtin function call.
David Blaikie4c96a5e2015-08-06 18:29:32 +0000437 std::string getInstTypeCode(Type T, ClassKind CK) const;
James Molloydee4ab02014-06-17 13:11:27 +0000438 /// Return the type string for a BUILTIN() macro in Builtins.def.
439 std::string getBuiltinTypeStr();
440
441 /// Generate the intrinsic, returning code.
442 std::string generate();
443 /// Perform type checking and populate the dependency graph, but
444 /// don't generate code yet.
445 void indexBody();
446
447private:
David Blaikie4c96a5e2015-08-06 18:29:32 +0000448 std::string mangleName(std::string Name, ClassKind CK) const;
James Molloydee4ab02014-06-17 13:11:27 +0000449
450 void initVariables();
451 std::string replaceParamsIn(std::string S);
452
453 void emitBodyAsBuiltinCall();
James Molloydee4ab02014-06-17 13:11:27 +0000454
James Molloyb452f782014-06-27 11:53:35 +0000455 void generateImpl(bool ReverseArguments,
456 StringRef NamePrefix, StringRef CallPrefix);
James Molloydee4ab02014-06-17 13:11:27 +0000457 void emitReturn();
James Molloyb452f782014-06-27 11:53:35 +0000458 void emitBody(StringRef CallPrefix);
James Molloydee4ab02014-06-17 13:11:27 +0000459 void emitShadowedArgs();
James Molloyb452f782014-06-27 11:53:35 +0000460 void emitArgumentReversal();
461 void emitReturnReversal();
462 void emitReverseVariable(Variable &Dest, Variable &Src);
James Molloydee4ab02014-06-17 13:11:27 +0000463 void emitNewLine();
464 void emitClosingBrace();
465 void emitOpeningBrace();
James Molloyb452f782014-06-27 11:53:35 +0000466 void emitPrototype(StringRef NamePrefix);
467
468 class DagEmitter {
469 Intrinsic &Intr;
470 StringRef CallPrefix;
471
472 public:
473 DagEmitter(Intrinsic &Intr, StringRef CallPrefix) :
474 Intr(Intr), CallPrefix(CallPrefix) {
475 }
476 std::pair<Type, std::string> emitDagArg(Init *Arg, std::string ArgName);
477 std::pair<Type, std::string> emitDagSaveTemp(DagInit *DI);
478 std::pair<Type, std::string> emitDagSplat(DagInit *DI);
479 std::pair<Type, std::string> emitDagDup(DagInit *DI);
480 std::pair<Type, std::string> emitDagShuffle(DagInit *DI);
481 std::pair<Type, std::string> emitDagCast(DagInit *DI, bool IsBitCast);
482 std::pair<Type, std::string> emitDagCall(DagInit *DI);
483 std::pair<Type, std::string> emitDagNameReplace(DagInit *DI);
484 std::pair<Type, std::string> emitDagLiteral(DagInit *DI);
485 std::pair<Type, std::string> emitDagOp(DagInit *DI);
486 std::pair<Type, std::string> emitDag(DagInit *DI);
487 };
488
James Molloydee4ab02014-06-17 13:11:27 +0000489};
490
491//===----------------------------------------------------------------------===//
492// NeonEmitter
493//===----------------------------------------------------------------------===//
494
495class NeonEmitter {
496 RecordKeeper &Records;
497 DenseMap<Record *, ClassKind> ClassMap;
David Blaikie4c96a5e2015-08-06 18:29:32 +0000498 std::map<std::string, std::deque<Intrinsic>> IntrinsicMap;
James Molloydee4ab02014-06-17 13:11:27 +0000499 unsigned UniqueNumber;
500
501 void createIntrinsic(Record *R, SmallVectorImpl<Intrinsic *> &Out);
502 void genBuiltinsDef(raw_ostream &OS, SmallVectorImpl<Intrinsic *> &Defs);
503 void genOverloadTypeCheckCode(raw_ostream &OS,
504 SmallVectorImpl<Intrinsic *> &Defs);
505 void genIntrinsicRangeCheckCode(raw_ostream &OS,
506 SmallVectorImpl<Intrinsic *> &Defs);
507
508public:
509 /// Called by Intrinsic - this attempts to get an intrinsic that takes
510 /// the given types as arguments.
David Blaikie4c96a5e2015-08-06 18:29:32 +0000511 Intrinsic &getIntrinsic(StringRef Name, ArrayRef<Type> Types);
James Molloydee4ab02014-06-17 13:11:27 +0000512
513 /// Called by Intrinsic - returns a globally-unique number.
514 unsigned getUniqueNumber() { return UniqueNumber++; }
515
516 NeonEmitter(RecordKeeper &R) : Records(R), UniqueNumber(0) {
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000517 Record *SI = R.getClass("SInst");
518 Record *II = R.getClass("IInst");
519 Record *WI = R.getClass("WInst");
Michael Gottesmanfc89cc22013-04-16 21:18:42 +0000520 Record *SOpI = R.getClass("SOpInst");
521 Record *IOpI = R.getClass("IOpInst");
522 Record *WOpI = R.getClass("WOpInst");
523 Record *LOpI = R.getClass("LOpInst");
524 Record *NoTestOpI = R.getClass("NoTestOpInst");
525
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000526 ClassMap[SI] = ClassS;
527 ClassMap[II] = ClassI;
528 ClassMap[WI] = ClassW;
Michael Gottesmanfc89cc22013-04-16 21:18:42 +0000529 ClassMap[SOpI] = ClassS;
530 ClassMap[IOpI] = ClassI;
531 ClassMap[WOpI] = ClassW;
532 ClassMap[LOpI] = ClassL;
533 ClassMap[NoTestOpI] = ClassNoTest;
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000534 }
535
536 // run - Emit arm_neon.h.inc
537 void run(raw_ostream &o);
538
539 // runHeader - Emit all the __builtin prototypes used in arm_neon.h
540 void runHeader(raw_ostream &o);
541
542 // runTests - Emit tests for all the Neon intrinsics.
543 void runTests(raw_ostream &o);
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000544};
James Molloydee4ab02014-06-17 13:11:27 +0000545
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000546} // end anonymous namespace
547
James Molloydee4ab02014-06-17 13:11:27 +0000548//===----------------------------------------------------------------------===//
549// Type implementation
550//===----------------------------------------------------------------------===//
Peter Collingbournebee583f2011-10-06 13:03:08 +0000551
James Molloydee4ab02014-06-17 13:11:27 +0000552std::string Type::str() const {
553 if (Void)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000554 return "void";
James Molloydee4ab02014-06-17 13:11:27 +0000555 std::string S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000556
James Molloydee4ab02014-06-17 13:11:27 +0000557 if (!Signed && isInteger())
558 S += "u";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000559
James Molloydee4ab02014-06-17 13:11:27 +0000560 if (Poly)
561 S += "poly";
562 else if (Float)
563 S += "float";
564 else
565 S += "int";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000566
James Molloydee4ab02014-06-17 13:11:27 +0000567 S += utostr(ElementBitwidth);
568 if (isVector())
569 S += "x" + utostr(getNumElements());
570 if (NumVectors > 1)
571 S += "x" + utostr(NumVectors);
572 S += "_t";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000573
James Molloydee4ab02014-06-17 13:11:27 +0000574 if (Constant)
575 S += " const";
576 if (Pointer)
577 S += " *";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000578
James Molloydee4ab02014-06-17 13:11:27 +0000579 return S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000580}
581
James Molloydee4ab02014-06-17 13:11:27 +0000582std::string Type::builtin_str() const {
583 std::string S;
584 if (isVoid())
585 return "v";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000586
James Molloydee4ab02014-06-17 13:11:27 +0000587 if (Pointer)
588 // All pointers are void pointers.
589 S += "v";
590 else if (isInteger())
591 switch (ElementBitwidth) {
592 case 8: S += "c"; break;
593 case 16: S += "s"; break;
594 case 32: S += "i"; break;
595 case 64: S += "Wi"; break;
596 case 128: S += "LLLi"; break;
Craig Topper0039f3f2014-06-18 03:57:25 +0000597 default: llvm_unreachable("Unhandled case!");
James Molloydee4ab02014-06-17 13:11:27 +0000598 }
599 else
600 switch (ElementBitwidth) {
601 case 16: S += "h"; break;
602 case 32: S += "f"; break;
603 case 64: S += "d"; break;
Craig Topper0039f3f2014-06-18 03:57:25 +0000604 default: llvm_unreachable("Unhandled case!");
James Molloydee4ab02014-06-17 13:11:27 +0000605 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000606
James Molloydee4ab02014-06-17 13:11:27 +0000607 if (isChar() && !Pointer)
608 // Make chars explicitly signed.
609 S = "S" + S;
610 else if (isInteger() && !Pointer && !Signed)
611 S = "U" + S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000612
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000613 // Constant indices are "int", but have the "constant expression" modifier.
614 if (isImmediate()) {
615 assert(isInteger() && isSigned());
616 S = "I" + S;
617 }
618
James Molloydee4ab02014-06-17 13:11:27 +0000619 if (isScalar()) {
620 if (Constant) S += "C";
621 if (Pointer) S += "*";
622 return S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000623 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000624
James Molloydee4ab02014-06-17 13:11:27 +0000625 std::string Ret;
626 for (unsigned I = 0; I < NumVectors; ++I)
627 Ret += "V" + utostr(getNumElements()) + S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000628
James Molloydee4ab02014-06-17 13:11:27 +0000629 return Ret;
630}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000631
James Molloydee4ab02014-06-17 13:11:27 +0000632unsigned Type::getNeonEnum() const {
633 unsigned Addend;
634 switch (ElementBitwidth) {
635 case 8: Addend = 0; break;
636 case 16: Addend = 1; break;
637 case 32: Addend = 2; break;
638 case 64: Addend = 3; break;
639 case 128: Addend = 4; break;
Craig Topperc7193c42014-06-18 03:13:41 +0000640 default: llvm_unreachable("Unhandled element bitwidth!");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000641 }
642
James Molloydee4ab02014-06-17 13:11:27 +0000643 unsigned Base = (unsigned)NeonTypeFlags::Int8 + Addend;
644 if (Poly) {
645 // Adjustment needed because Poly32 doesn't exist.
646 if (Addend >= 2)
647 --Addend;
648 Base = (unsigned)NeonTypeFlags::Poly8 + Addend;
649 }
650 if (Float) {
651 assert(Addend != 0 && "Float8 doesn't exist!");
652 Base = (unsigned)NeonTypeFlags::Float16 + (Addend - 1);
653 }
654
655 if (Bitwidth == 128)
656 Base |= (unsigned)NeonTypeFlags::QuadFlag;
657 if (isInteger() && !Signed)
658 Base |= (unsigned)NeonTypeFlags::UnsignedFlag;
659
660 return Base;
661}
662
663Type Type::fromTypedefName(StringRef Name) {
664 Type T;
665 T.Void = false;
666 T.Float = false;
667 T.Poly = false;
668
669 if (Name.front() == 'u') {
670 T.Signed = false;
671 Name = Name.drop_front();
672 } else {
673 T.Signed = true;
674 }
675
676 if (Name.startswith("float")) {
677 T.Float = true;
678 Name = Name.drop_front(5);
679 } else if (Name.startswith("poly")) {
680 T.Poly = true;
681 Name = Name.drop_front(4);
682 } else {
683 assert(Name.startswith("int"));
684 Name = Name.drop_front(3);
685 }
686
687 unsigned I = 0;
688 for (I = 0; I < Name.size(); ++I) {
689 if (!isdigit(Name[I]))
690 break;
691 }
692 Name.substr(0, I).getAsInteger(10, T.ElementBitwidth);
693 Name = Name.drop_front(I);
694
695 T.Bitwidth = T.ElementBitwidth;
696 T.NumVectors = 1;
697
698 if (Name.front() == 'x') {
699 Name = Name.drop_front();
700 unsigned I = 0;
701 for (I = 0; I < Name.size(); ++I) {
702 if (!isdigit(Name[I]))
703 break;
704 }
705 unsigned NumLanes;
706 Name.substr(0, I).getAsInteger(10, NumLanes);
707 Name = Name.drop_front(I);
708 T.Bitwidth = T.ElementBitwidth * NumLanes;
709 } else {
710 // Was scalar.
711 T.NumVectors = 0;
712 }
713 if (Name.front() == 'x') {
714 Name = Name.drop_front();
715 unsigned I = 0;
716 for (I = 0; I < Name.size(); ++I) {
717 if (!isdigit(Name[I]))
718 break;
719 }
720 Name.substr(0, I).getAsInteger(10, T.NumVectors);
721 Name = Name.drop_front(I);
722 }
723
724 assert(Name.startswith("_t") && "Malformed typedef!");
725 return T;
726}
727
728void Type::applyTypespec(bool &Quad) {
729 std::string S = TS;
730 ScalarForMangling = false;
731 Void = false;
732 Poly = Float = false;
733 ElementBitwidth = ~0U;
734 Signed = true;
735 NumVectors = 1;
736
737 for (char I : S) {
738 switch (I) {
739 case 'S':
740 ScalarForMangling = true;
741 break;
742 case 'H':
743 NoManglingQ = true;
744 Quad = true;
745 break;
746 case 'Q':
747 Quad = true;
748 break;
749 case 'P':
750 Poly = true;
751 break;
752 case 'U':
753 Signed = false;
754 break;
755 case 'c':
756 ElementBitwidth = 8;
757 break;
758 case 'h':
759 Float = true;
760 // Fall through
761 case 's':
762 ElementBitwidth = 16;
763 break;
764 case 'f':
765 Float = true;
766 // Fall through
767 case 'i':
768 ElementBitwidth = 32;
769 break;
770 case 'd':
771 Float = true;
772 // Fall through
773 case 'l':
774 ElementBitwidth = 64;
775 break;
776 case 'k':
777 ElementBitwidth = 128;
778 // Poly doesn't have a 128x1 type.
779 if (Poly)
780 NumVectors = 0;
781 break;
782 default:
Craig Topper0039f3f2014-06-18 03:57:25 +0000783 llvm_unreachable("Unhandled type code!");
James Molloydee4ab02014-06-17 13:11:27 +0000784 }
785 }
786 assert(ElementBitwidth != ~0U && "Bad element bitwidth!");
787
788 Bitwidth = Quad ? 128 : 64;
789}
790
791void Type::applyModifier(char Mod) {
792 bool AppliedQuad = false;
793 applyTypespec(AppliedQuad);
794
795 switch (Mod) {
796 case 'v':
797 Void = true;
798 break;
799 case 't':
800 if (Poly) {
801 Poly = false;
802 Signed = false;
803 }
804 break;
805 case 'b':
806 Signed = false;
807 Float = false;
808 Poly = false;
809 NumVectors = 0;
810 Bitwidth = ElementBitwidth;
811 break;
812 case '$':
813 Signed = true;
814 Float = false;
815 Poly = false;
816 NumVectors = 0;
817 Bitwidth = ElementBitwidth;
818 break;
819 case 'u':
820 Signed = false;
821 Poly = false;
822 Float = false;
823 break;
824 case 'x':
825 Signed = true;
826 assert(!Poly && "'u' can't be used with poly types!");
827 Float = false;
828 break;
829 case 'o':
830 Bitwidth = ElementBitwidth = 64;
831 NumVectors = 0;
832 Float = true;
833 break;
834 case 'y':
835 Bitwidth = ElementBitwidth = 32;
836 NumVectors = 0;
837 Float = true;
838 break;
839 case 'f':
840 // Special case - if we're half-precision, a floating
841 // point argument needs to be 128-bits (double size).
842 if (isHalf())
843 Bitwidth = 128;
844 Float = true;
845 ElementBitwidth = 32;
846 break;
847 case 'F':
848 Float = true;
849 ElementBitwidth = 64;
850 break;
851 case 'g':
852 if (AppliedQuad)
853 Bitwidth /= 2;
854 break;
855 case 'j':
856 if (!AppliedQuad)
857 Bitwidth *= 2;
858 break;
859 case 'w':
860 ElementBitwidth *= 2;
861 Bitwidth *= 2;
862 break;
863 case 'n':
864 ElementBitwidth *= 2;
865 break;
866 case 'i':
867 Float = false;
868 Poly = false;
869 ElementBitwidth = Bitwidth = 32;
870 NumVectors = 0;
871 Signed = true;
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000872 Immediate = true;
James Molloydee4ab02014-06-17 13:11:27 +0000873 break;
874 case 'l':
875 Float = false;
876 Poly = false;
877 ElementBitwidth = Bitwidth = 64;
878 NumVectors = 0;
879 Signed = false;
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000880 Immediate = true;
James Molloydee4ab02014-06-17 13:11:27 +0000881 break;
882 case 'z':
883 ElementBitwidth /= 2;
884 Bitwidth = ElementBitwidth;
885 NumVectors = 0;
886 break;
887 case 'r':
888 ElementBitwidth *= 2;
889 Bitwidth = ElementBitwidth;
890 NumVectors = 0;
891 break;
892 case 's':
893 case 'a':
894 Bitwidth = ElementBitwidth;
895 NumVectors = 0;
896 break;
897 case 'k':
898 Bitwidth *= 2;
899 break;
900 case 'c':
901 Constant = true;
902 // Fall through
903 case 'p':
904 Pointer = true;
905 Bitwidth = ElementBitwidth;
906 NumVectors = 0;
907 break;
908 case 'h':
909 ElementBitwidth /= 2;
910 break;
911 case 'q':
912 ElementBitwidth /= 2;
913 Bitwidth *= 2;
914 break;
915 case 'e':
916 ElementBitwidth /= 2;
917 Signed = false;
918 break;
919 case 'm':
920 ElementBitwidth /= 2;
921 Bitwidth /= 2;
922 break;
923 case 'd':
924 break;
925 case '2':
926 NumVectors = 2;
927 break;
928 case '3':
929 NumVectors = 3;
930 break;
931 case '4':
932 NumVectors = 4;
933 break;
934 case 'B':
935 NumVectors = 2;
936 if (!AppliedQuad)
937 Bitwidth *= 2;
938 break;
939 case 'C':
940 NumVectors = 3;
941 if (!AppliedQuad)
942 Bitwidth *= 2;
943 break;
944 case 'D':
945 NumVectors = 4;
946 if (!AppliedQuad)
947 Bitwidth *= 2;
948 break;
949 default:
Craig Topper0039f3f2014-06-18 03:57:25 +0000950 llvm_unreachable("Unhandled character!");
James Molloydee4ab02014-06-17 13:11:27 +0000951 }
952}
953
954//===----------------------------------------------------------------------===//
955// Intrinsic implementation
956//===----------------------------------------------------------------------===//
957
David Blaikie4c96a5e2015-08-06 18:29:32 +0000958std::string Intrinsic::getInstTypeCode(Type T, ClassKind CK) const {
James Molloydee4ab02014-06-17 13:11:27 +0000959 char typeCode = '\0';
960 bool printNumber = true;
961
962 if (CK == ClassB)
963 return "";
964
965 if (T.isPoly())
966 typeCode = 'p';
967 else if (T.isInteger())
968 typeCode = T.isSigned() ? 's' : 'u';
969 else
970 typeCode = 'f';
971
972 if (CK == ClassI) {
973 switch (typeCode) {
974 default:
975 break;
976 case 's':
977 case 'u':
978 case 'p':
979 typeCode = 'i';
980 break;
981 }
982 }
983 if (CK == ClassB) {
984 typeCode = '\0';
985 }
986
987 std::string S;
988 if (typeCode != '\0')
989 S.push_back(typeCode);
990 if (printNumber)
991 S += utostr(T.getElementSizeInBits());
992
993 return S;
994}
995
Ahmed Bougacha22a16962015-08-21 23:24:18 +0000996static bool isFloatingPointProtoModifier(char Mod) {
997 return Mod == 'F' || Mod == 'f';
998}
999
James Molloydee4ab02014-06-17 13:11:27 +00001000std::string Intrinsic::getBuiltinTypeStr() {
1001 ClassKind LocalCK = getClassKind(true);
1002 std::string S;
1003
1004 Type RetT = getReturnType();
1005 if ((LocalCK == ClassI || LocalCK == ClassW) && RetT.isScalar() &&
1006 !RetT.isFloating())
1007 RetT.makeInteger(RetT.getElementSizeInBits(), false);
1008
Peter Collingbournebee583f2011-10-06 13:03:08 +00001009 // Since the return value must be one type, return a vector type of the
1010 // appropriate width which we will bitcast. An exception is made for
1011 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
1012 // fashion, storing them to a pointer arg.
James Molloydee4ab02014-06-17 13:11:27 +00001013 if (RetT.getNumVectors() > 1) {
1014 S += "vv*"; // void result with void* first argument
1015 } else {
1016 if (RetT.isPoly())
1017 RetT.makeInteger(RetT.getElementSizeInBits(), false);
1018 if (!RetT.isScalar() && !RetT.isSigned())
1019 RetT.makeSigned();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001020
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001021 bool ForcedVectorFloatingType = isFloatingPointProtoModifier(Proto[0]);
James Molloydee4ab02014-06-17 13:11:27 +00001022 if (LocalCK == ClassB && !RetT.isScalar() && !ForcedVectorFloatingType)
1023 // Cast to vector of 8-bit elements.
1024 RetT.makeInteger(8, true);
1025
1026 S += RetT.builtin_str();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001027 }
1028
James Molloydee4ab02014-06-17 13:11:27 +00001029 for (unsigned I = 0; I < getNumParams(); ++I) {
1030 Type T = getParamType(I);
1031 if (T.isPoly())
1032 T.makeInteger(T.getElementSizeInBits(), false);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001033
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001034 bool ForcedFloatingType = isFloatingPointProtoModifier(Proto[I + 1]);
James Molloydee4ab02014-06-17 13:11:27 +00001035 if (LocalCK == ClassB && !T.isScalar() && !ForcedFloatingType)
1036 T.makeInteger(8, true);
1037 // Halves always get converted to 8-bit elements.
1038 if (T.isHalf() && T.isVector() && !T.isScalarForMangling())
1039 T.makeInteger(8, true);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001040
James Molloydee4ab02014-06-17 13:11:27 +00001041 if (LocalCK == ClassI)
1042 T.makeSigned();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001043
James Molloydee4ab02014-06-17 13:11:27 +00001044 if (hasImmediate() && getImmediateIdx() == I)
Ahmed Bougacha94df7302015-06-04 01:43:41 +00001045 T.makeImmediate(32);
Michael Gottesman095c58f2013-04-16 22:07:30 +00001046
James Molloydee4ab02014-06-17 13:11:27 +00001047 S += T.builtin_str();
Michael Gottesman095c58f2013-04-16 22:07:30 +00001048 }
James Molloydee4ab02014-06-17 13:11:27 +00001049
1050 // Extra constant integer to hold type class enum for this function, e.g. s8
1051 if (LocalCK == ClassB)
1052 S += "i";
1053
1054 return S;
Michael Gottesman095c58f2013-04-16 22:07:30 +00001055}
1056
David Blaikie4c96a5e2015-08-06 18:29:32 +00001057std::string Intrinsic::getMangledName(bool ForceClassS) const {
James Molloydee4ab02014-06-17 13:11:27 +00001058 // Check if the prototype has a scalar operand with the type of the vector
1059 // elements. If not, bitcasting the args will take care of arg checking.
1060 // The actual signedness etc. will be taken care of with special enums.
1061 ClassKind LocalCK = CK;
1062 if (!protoHasScalar())
1063 LocalCK = ClassB;
1064
1065 return mangleName(Name, ForceClassS ? ClassS : LocalCK);
Kevin Qinc076d062013-08-29 07:55:15 +00001066}
1067
David Blaikie4c96a5e2015-08-06 18:29:32 +00001068std::string Intrinsic::mangleName(std::string Name, ClassKind LocalCK) const {
James Molloydee4ab02014-06-17 13:11:27 +00001069 std::string typeCode = getInstTypeCode(BaseType, LocalCK);
1070 std::string S = Name;
Hao Liu5e4ce1a2013-11-18 06:33:43 +00001071
James Molloydee4ab02014-06-17 13:11:27 +00001072 if (Name == "vcvt_f32_f16" || Name == "vcvt_f32_f64" ||
1073 Name == "vcvt_f64_f32")
1074 return Name;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001075
Michael Gottesman095c58f2013-04-16 22:07:30 +00001076 if (typeCode.size() > 0) {
James Molloydee4ab02014-06-17 13:11:27 +00001077 // If the name ends with _xN (N = 2,3,4), insert the typeCode before _xN.
1078 if (Name.size() >= 3 && isdigit(Name.back()) &&
1079 Name[Name.length() - 2] == 'x' && Name[Name.length() - 3] == '_')
1080 S.insert(S.length() - 3, "_" + typeCode);
Hao Liu5e4ce1a2013-11-18 06:33:43 +00001081 else
James Molloydee4ab02014-06-17 13:11:27 +00001082 S += "_" + typeCode;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001083 }
Michael Gottesman095c58f2013-04-16 22:07:30 +00001084
James Molloydee4ab02014-06-17 13:11:27 +00001085 if (BaseType != InBaseType) {
1086 // A reinterpret - out the input base type at the end.
1087 S += "_" + getInstTypeCode(InBaseType, LocalCK);
1088 }
1089
1090 if (LocalCK == ClassB)
1091 S += "_v";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001092
1093 // Insert a 'q' before the first '_' character so that it ends up before
1094 // _lane or _n on vector-scalar operations.
James Molloydee4ab02014-06-17 13:11:27 +00001095 if (BaseType.getSizeInBits() == 128 && !BaseType.noManglingQ()) {
1096 size_t Pos = S.find('_');
1097 S.insert(Pos, "q");
Kevin Qinc076d062013-08-29 07:55:15 +00001098 }
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001099
James Molloydee4ab02014-06-17 13:11:27 +00001100 char Suffix = '\0';
1101 if (BaseType.isScalarForMangling()) {
1102 switch (BaseType.getElementSizeInBits()) {
1103 case 8: Suffix = 'b'; break;
1104 case 16: Suffix = 'h'; break;
1105 case 32: Suffix = 's'; break;
1106 case 64: Suffix = 'd'; break;
Craig Topper0039f3f2014-06-18 03:57:25 +00001107 default: llvm_unreachable("Bad suffix!");
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001108 }
1109 }
James Molloydee4ab02014-06-17 13:11:27 +00001110 if (Suffix != '\0') {
1111 size_t Pos = S.find('_');
1112 S.insert(Pos, &Suffix, 1);
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001113 }
James Molloydee4ab02014-06-17 13:11:27 +00001114
1115 return S;
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001116}
1117
James Molloydee4ab02014-06-17 13:11:27 +00001118std::string Intrinsic::replaceParamsIn(std::string S) {
1119 while (S.find('$') != std::string::npos) {
1120 size_t Pos = S.find('$');
1121 size_t End = Pos + 1;
1122 while (isalpha(S[End]))
1123 ++End;
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001124
James Molloydee4ab02014-06-17 13:11:27 +00001125 std::string VarName = S.substr(Pos + 1, End - Pos - 1);
1126 assert_with_loc(Variables.find(VarName) != Variables.end(),
1127 "Variable not defined!");
1128 S.replace(Pos, End - Pos, Variables.find(VarName)->second.getName());
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001129 }
1130
James Molloydee4ab02014-06-17 13:11:27 +00001131 return S;
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001132}
1133
James Molloydee4ab02014-06-17 13:11:27 +00001134void Intrinsic::initVariables() {
1135 Variables.clear();
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001136
James Molloydee4ab02014-06-17 13:11:27 +00001137 // Modify the TypeSpec per-argument to get a concrete Type, and create
1138 // known variables for each.
1139 for (unsigned I = 1; I < Proto.size(); ++I) {
1140 char NameC = '0' + (I - 1);
1141 std::string Name = "p";
1142 Name.push_back(NameC);
1143
1144 Variables[Name] = Variable(Types[I], Name + VariablePostfix);
1145 }
1146 RetVar = Variable(Types[0], "ret" + VariablePostfix);
1147}
1148
James Molloyb452f782014-06-27 11:53:35 +00001149void Intrinsic::emitPrototype(StringRef NamePrefix) {
James Molloydee4ab02014-06-17 13:11:27 +00001150 if (UseMacro)
1151 OS << "#define ";
1152 else
1153 OS << "__ai " << Types[0].str() << " ";
1154
James Molloyb452f782014-06-27 11:53:35 +00001155 OS << NamePrefix.str() << mangleName(Name, ClassS) << "(";
James Molloydee4ab02014-06-17 13:11:27 +00001156
1157 for (unsigned I = 0; I < getNumParams(); ++I) {
1158 if (I != 0)
1159 OS << ", ";
1160
1161 char NameC = '0' + I;
1162 std::string Name = "p";
1163 Name.push_back(NameC);
1164 assert(Variables.find(Name) != Variables.end());
1165 Variable &V = Variables[Name];
1166
1167 if (!UseMacro)
1168 OS << V.getType().str() << " ";
1169 OS << V.getName();
1170 }
1171
1172 OS << ")";
1173}
1174
1175void Intrinsic::emitOpeningBrace() {
1176 if (UseMacro)
1177 OS << " __extension__ ({";
1178 else
1179 OS << " {";
1180 emitNewLine();
1181}
1182
1183void Intrinsic::emitClosingBrace() {
1184 if (UseMacro)
1185 OS << "})";
1186 else
1187 OS << "}";
1188}
1189
1190void Intrinsic::emitNewLine() {
1191 if (UseMacro)
1192 OS << " \\\n";
1193 else
1194 OS << "\n";
1195}
1196
James Molloyb452f782014-06-27 11:53:35 +00001197void Intrinsic::emitReverseVariable(Variable &Dest, Variable &Src) {
1198 if (Dest.getType().getNumVectors() > 1) {
1199 emitNewLine();
1200
1201 for (unsigned K = 0; K < Dest.getType().getNumVectors(); ++K) {
1202 OS << " " << Dest.getName() << ".val[" << utostr(K) << "] = "
1203 << "__builtin_shufflevector("
1204 << Src.getName() << ".val[" << utostr(K) << "], "
1205 << Src.getName() << ".val[" << utostr(K) << "]";
1206 for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1207 OS << ", " << utostr(J);
1208 OS << ");";
1209 emitNewLine();
1210 }
1211 } else {
1212 OS << " " << Dest.getName()
1213 << " = __builtin_shufflevector(" << Src.getName() << ", " << Src.getName();
1214 for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1215 OS << ", " << utostr(J);
1216 OS << ");";
1217 emitNewLine();
1218 }
1219}
1220
1221void Intrinsic::emitArgumentReversal() {
1222 if (BigEndianSafe)
1223 return;
1224
1225 // Reverse all vector arguments.
1226 for (unsigned I = 0; I < getNumParams(); ++I) {
1227 std::string Name = "p" + utostr(I);
1228 std::string NewName = "rev" + utostr(I);
1229
1230 Variable &V = Variables[Name];
1231 Variable NewV(V.getType(), NewName + VariablePostfix);
1232
1233 if (!NewV.getType().isVector() || NewV.getType().getNumElements() == 1)
1234 continue;
1235
1236 OS << " " << NewV.getType().str() << " " << NewV.getName() << ";";
1237 emitReverseVariable(NewV, V);
1238 V = NewV;
1239 }
1240}
1241
1242void Intrinsic::emitReturnReversal() {
1243 if (BigEndianSafe)
1244 return;
1245 if (!getReturnType().isVector() || getReturnType().isVoid() ||
1246 getReturnType().getNumElements() == 1)
1247 return;
1248 emitReverseVariable(RetVar, RetVar);
1249}
1250
1251
James Molloydee4ab02014-06-17 13:11:27 +00001252void Intrinsic::emitShadowedArgs() {
1253 // Macro arguments are not type-checked like inline function arguments,
1254 // so assign them to local temporaries to get the right type checking.
1255 if (!UseMacro)
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001256 return;
1257
James Molloydee4ab02014-06-17 13:11:27 +00001258 for (unsigned I = 0; I < getNumParams(); ++I) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001259 // Do not create a temporary for an immediate argument.
1260 // That would defeat the whole point of using a macro!
James Molloydee4ab02014-06-17 13:11:27 +00001261 if (hasImmediate() && Proto[I+1] == 'i')
Peter Collingbournebee583f2011-10-06 13:03:08 +00001262 continue;
James Molloydee4ab02014-06-17 13:11:27 +00001263 // Do not create a temporary for pointer arguments. The input
1264 // pointer may have an alignment hint.
1265 if (getParamType(I).isPointer())
1266 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001267
James Molloyb452f782014-06-27 11:53:35 +00001268 std::string Name = "p" + utostr(I);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001269
James Molloydee4ab02014-06-17 13:11:27 +00001270 assert(Variables.find(Name) != Variables.end());
1271 Variable &V = Variables[Name];
Peter Collingbournebee583f2011-10-06 13:03:08 +00001272
James Molloydee4ab02014-06-17 13:11:27 +00001273 std::string NewName = "s" + utostr(I);
1274 Variable V2(V.getType(), NewName + VariablePostfix);
Jiangning Liu1bda93a2013-09-09 02:21:08 +00001275
James Molloydee4ab02014-06-17 13:11:27 +00001276 OS << " " << V2.getType().str() << " " << V2.getName() << " = "
1277 << V.getName() << ";";
1278 emitNewLine();
Jiangning Liu1bda93a2013-09-09 02:21:08 +00001279
James Molloydee4ab02014-06-17 13:11:27 +00001280 V = V2;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001281 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001282}
1283
Jiangning Liuee3e0872013-11-27 14:02:55 +00001284// We don't check 'a' in this function, because for builtin function the
1285// argument matching to 'a' uses a vector type splatted from a scalar type.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001286bool Intrinsic::protoHasScalar() const {
James Molloydee4ab02014-06-17 13:11:27 +00001287 return (Proto.find('s') != std::string::npos ||
1288 Proto.find('z') != std::string::npos ||
1289 Proto.find('r') != std::string::npos ||
1290 Proto.find('b') != std::string::npos ||
1291 Proto.find('$') != std::string::npos ||
1292 Proto.find('y') != std::string::npos ||
1293 Proto.find('o') != std::string::npos);
Jiangning Liub96ebac2013-10-05 08:22:55 +00001294}
1295
James Molloydee4ab02014-06-17 13:11:27 +00001296void Intrinsic::emitBodyAsBuiltinCall() {
1297 std::string S;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001298
1299 // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
1300 // sret-like argument.
James Molloydee4ab02014-06-17 13:11:27 +00001301 bool SRet = getReturnType().getNumVectors() >= 2;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001302
James Molloydee4ab02014-06-17 13:11:27 +00001303 StringRef N = Name;
1304 if (hasSplat()) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001305 // Call the non-splat builtin: chop off the "_n" suffix from the name.
James Molloydee4ab02014-06-17 13:11:27 +00001306 assert(N.endswith("_n"));
1307 N = N.drop_back(2);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001308 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001309
James Molloydee4ab02014-06-17 13:11:27 +00001310 ClassKind LocalCK = CK;
1311 if (!protoHasScalar())
1312 LocalCK = ClassB;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001313
James Molloydee4ab02014-06-17 13:11:27 +00001314 if (!getReturnType().isVoid() && !SRet)
1315 S += "(" + RetVar.getType().str() + ") ";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001316
James Molloydee4ab02014-06-17 13:11:27 +00001317 S += "__builtin_neon_" + mangleName(N, LocalCK) + "(";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001318
James Molloydee4ab02014-06-17 13:11:27 +00001319 if (SRet)
1320 S += "&" + RetVar.getName() + ", ";
1321
1322 for (unsigned I = 0; I < getNumParams(); ++I) {
1323 Variable &V = Variables["p" + utostr(I)];
1324 Type T = V.getType();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001325
1326 // Handle multiple-vector values specially, emitting each subvector as an
James Molloydee4ab02014-06-17 13:11:27 +00001327 // argument to the builtin.
1328 if (T.getNumVectors() > 1) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001329 // Check if an explicit cast is needed.
James Molloydee4ab02014-06-17 13:11:27 +00001330 std::string Cast;
1331 if (T.isChar() || T.isPoly() || !T.isSigned()) {
1332 Type T2 = T;
1333 T2.makeOneVector();
1334 T2.makeInteger(8, /*Signed=*/true);
1335 Cast = "(" + T2.str() + ")";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001336 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001337
James Molloydee4ab02014-06-17 13:11:27 +00001338 for (unsigned J = 0; J < T.getNumVectors(); ++J)
1339 S += Cast + V.getName() + ".val[" + utostr(J) + "], ";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001340 continue;
1341 }
1342
James Molloydee4ab02014-06-17 13:11:27 +00001343 std::string Arg;
1344 Type CastToType = T;
1345 if (hasSplat() && I == getSplatIdx()) {
1346 Arg = "(" + BaseType.str() + ") {";
1347 for (unsigned J = 0; J < BaseType.getNumElements(); ++J) {
1348 if (J != 0)
1349 Arg += ", ";
1350 Arg += V.getName();
1351 }
1352 Arg += "}";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001353
James Molloydee4ab02014-06-17 13:11:27 +00001354 CastToType = BaseType;
1355 } else {
1356 Arg = V.getName();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001357 }
1358
James Molloydee4ab02014-06-17 13:11:27 +00001359 // Check if an explicit cast is needed.
1360 if (CastToType.isVector()) {
1361 CastToType.makeInteger(8, true);
1362 Arg = "(" + CastToType.str() + ")" + Arg;
1363 }
1364
1365 S += Arg + ", ";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001366 }
1367
1368 // Extra constant integer to hold type class enum for this function, e.g. s8
James Molloydee4ab02014-06-17 13:11:27 +00001369 if (getClassKind(true) == ClassB) {
1370 Type ThisTy = getReturnType();
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001371 if (Proto[0] == 'v' || isFloatingPointProtoModifier(Proto[0]))
James Molloydee4ab02014-06-17 13:11:27 +00001372 ThisTy = getParamType(0);
1373 if (ThisTy.isPointer())
1374 ThisTy = getParamType(1);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001375
James Molloydee4ab02014-06-17 13:11:27 +00001376 S += utostr(ThisTy.getNeonEnum());
1377 } else {
1378 // Remove extraneous ", ".
1379 S.pop_back();
1380 S.pop_back();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001381 }
James Molloydee4ab02014-06-17 13:11:27 +00001382 S += ");";
1383
1384 std::string RetExpr;
1385 if (!SRet && !RetVar.getType().isVoid())
1386 RetExpr = RetVar.getName() + " = ";
1387
1388 OS << " " << RetExpr << S;
1389 emitNewLine();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001390}
1391
James Molloyb452f782014-06-27 11:53:35 +00001392void Intrinsic::emitBody(StringRef CallPrefix) {
James Molloydee4ab02014-06-17 13:11:27 +00001393 std::vector<std::string> Lines;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001394
James Molloydee4ab02014-06-17 13:11:27 +00001395 assert(RetVar.getType() == Types[0]);
1396 // Create a return variable, if we're not void.
1397 if (!RetVar.getType().isVoid()) {
1398 OS << " " << RetVar.getType().str() << " " << RetVar.getName() << ";";
1399 emitNewLine();
1400 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001401
James Molloydee4ab02014-06-17 13:11:27 +00001402 if (!Body || Body->getValues().size() == 0) {
1403 // Nothing specific to output - must output a builtin.
1404 emitBodyAsBuiltinCall();
1405 return;
1406 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001407
James Molloydee4ab02014-06-17 13:11:27 +00001408 // We have a list of "things to output". The last should be returned.
1409 for (auto *I : Body->getValues()) {
1410 if (StringInit *SI = dyn_cast<StringInit>(I)) {
1411 Lines.push_back(replaceParamsIn(SI->getAsString()));
1412 } else if (DagInit *DI = dyn_cast<DagInit>(I)) {
James Molloyb452f782014-06-27 11:53:35 +00001413 DagEmitter DE(*this, CallPrefix);
1414 Lines.push_back(DE.emitDag(DI).second + ";");
James Molloydee4ab02014-06-17 13:11:27 +00001415 }
1416 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001417
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00001418 assert(!Lines.empty() && "Empty def?");
James Molloydee4ab02014-06-17 13:11:27 +00001419 if (!RetVar.getType().isVoid())
1420 Lines.back().insert(0, RetVar.getName() + " = ");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001421
James Molloydee4ab02014-06-17 13:11:27 +00001422 for (auto &L : Lines) {
1423 OS << " " << L;
1424 emitNewLine();
1425 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001426}
1427
James Molloydee4ab02014-06-17 13:11:27 +00001428void Intrinsic::emitReturn() {
1429 if (RetVar.getType().isVoid())
1430 return;
1431 if (UseMacro)
1432 OS << " " << RetVar.getName() << ";";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001433 else
James Molloydee4ab02014-06-17 13:11:27 +00001434 OS << " return " << RetVar.getName() << ";";
1435 emitNewLine();
1436}
Peter Collingbournebee583f2011-10-06 13:03:08 +00001437
James Molloyb452f782014-06-27 11:53:35 +00001438std::pair<Type, std::string> Intrinsic::DagEmitter::emitDag(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001439 // At this point we should only be seeing a def.
1440 DefInit *DefI = cast<DefInit>(DI->getOperator());
1441 std::string Op = DefI->getAsString();
1442
1443 if (Op == "cast" || Op == "bitcast")
1444 return emitDagCast(DI, Op == "bitcast");
1445 if (Op == "shuffle")
1446 return emitDagShuffle(DI);
1447 if (Op == "dup")
1448 return emitDagDup(DI);
1449 if (Op == "splat")
1450 return emitDagSplat(DI);
1451 if (Op == "save_temp")
1452 return emitDagSaveTemp(DI);
1453 if (Op == "op")
1454 return emitDagOp(DI);
1455 if (Op == "call")
1456 return emitDagCall(DI);
1457 if (Op == "name_replace")
1458 return emitDagNameReplace(DI);
1459 if (Op == "literal")
1460 return emitDagLiteral(DI);
1461 assert_with_loc(false, "Unknown operation!");
1462 return std::make_pair(Type::getVoid(), "");
1463}
1464
James Molloyb452f782014-06-27 11:53:35 +00001465std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagOp(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001466 std::string Op = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1467 if (DI->getNumArgs() == 2) {
1468 // Unary op.
1469 std::pair<Type, std::string> R =
1470 emitDagArg(DI->getArg(1), DI->getArgName(1));
1471 return std::make_pair(R.first, Op + R.second);
1472 } else {
1473 assert(DI->getNumArgs() == 3 && "Can only handle unary and binary ops!");
1474 std::pair<Type, std::string> R1 =
1475 emitDagArg(DI->getArg(1), DI->getArgName(1));
1476 std::pair<Type, std::string> R2 =
1477 emitDagArg(DI->getArg(2), DI->getArgName(2));
1478 assert_with_loc(R1.first == R2.first, "Argument type mismatch!");
1479 return std::make_pair(R1.first, R1.second + " " + Op + " " + R2.second);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001480 }
James Molloydee4ab02014-06-17 13:11:27 +00001481}
Peter Collingbournebee583f2011-10-06 13:03:08 +00001482
James Molloyb452f782014-06-27 11:53:35 +00001483std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCall(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001484 std::vector<Type> Types;
1485 std::vector<std::string> Values;
1486 for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1487 std::pair<Type, std::string> R =
1488 emitDagArg(DI->getArg(I + 1), DI->getArgName(I + 1));
1489 Types.push_back(R.first);
1490 Values.push_back(R.second);
1491 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001492
James Molloydee4ab02014-06-17 13:11:27 +00001493 // Look up the called intrinsic.
1494 std::string N;
1495 if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0)))
1496 N = SI->getAsUnquotedString();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001497 else
James Molloydee4ab02014-06-17 13:11:27 +00001498 N = emitDagArg(DI->getArg(0), "").second;
David Blaikie4c96a5e2015-08-06 18:29:32 +00001499 Intrinsic &Callee = Intr.Emitter.getIntrinsic(N, Types);
James Molloydee4ab02014-06-17 13:11:27 +00001500
1501 // Make sure the callee is known as an early def.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001502 Callee.setNeededEarly();
1503 Intr.Dependencies.insert(&Callee);
James Molloydee4ab02014-06-17 13:11:27 +00001504
1505 // Now create the call itself.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001506 std::string S = CallPrefix.str() + Callee.getMangledName(true) + "(";
James Molloydee4ab02014-06-17 13:11:27 +00001507 for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1508 if (I != 0)
1509 S += ", ";
1510 S += Values[I];
1511 }
1512 S += ")";
1513
David Blaikie4c96a5e2015-08-06 18:29:32 +00001514 return std::make_pair(Callee.getReturnType(), S);
James Molloydee4ab02014-06-17 13:11:27 +00001515}
1516
James Molloyb452f782014-06-27 11:53:35 +00001517std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCast(DagInit *DI,
1518 bool IsBitCast){
James Molloydee4ab02014-06-17 13:11:27 +00001519 // (cast MOD* VAL) -> cast VAL to type given by MOD.
1520 std::pair<Type, std::string> R = emitDagArg(
1521 DI->getArg(DI->getNumArgs() - 1), DI->getArgName(DI->getNumArgs() - 1));
1522 Type castToType = R.first;
1523 for (unsigned ArgIdx = 0; ArgIdx < DI->getNumArgs() - 1; ++ArgIdx) {
1524
1525 // MOD can take several forms:
1526 // 1. $X - take the type of parameter / variable X.
1527 // 2. The value "R" - take the type of the return type.
1528 // 3. a type string
1529 // 4. The value "U" or "S" to switch the signedness.
1530 // 5. The value "H" or "D" to half or double the bitwidth.
1531 // 6. The value "8" to convert to 8-bit (signed) integer lanes.
1532 if (DI->getArgName(ArgIdx).size()) {
James Molloyb452f782014-06-27 11:53:35 +00001533 assert_with_loc(Intr.Variables.find(DI->getArgName(ArgIdx)) !=
1534 Intr.Variables.end(),
James Molloydee4ab02014-06-17 13:11:27 +00001535 "Variable not found");
James Molloyb452f782014-06-27 11:53:35 +00001536 castToType = Intr.Variables[DI->getArgName(ArgIdx)].getType();
James Molloydee4ab02014-06-17 13:11:27 +00001537 } else {
1538 StringInit *SI = dyn_cast<StringInit>(DI->getArg(ArgIdx));
1539 assert_with_loc(SI, "Expected string type or $Name for cast type");
1540
1541 if (SI->getAsUnquotedString() == "R") {
James Molloyb452f782014-06-27 11:53:35 +00001542 castToType = Intr.getReturnType();
James Molloydee4ab02014-06-17 13:11:27 +00001543 } else if (SI->getAsUnquotedString() == "U") {
1544 castToType.makeUnsigned();
1545 } else if (SI->getAsUnquotedString() == "S") {
1546 castToType.makeSigned();
1547 } else if (SI->getAsUnquotedString() == "H") {
1548 castToType.halveLanes();
1549 } else if (SI->getAsUnquotedString() == "D") {
1550 castToType.doubleLanes();
1551 } else if (SI->getAsUnquotedString() == "8") {
1552 castToType.makeInteger(8, true);
1553 } else {
1554 castToType = Type::fromTypedefName(SI->getAsUnquotedString());
1555 assert_with_loc(!castToType.isVoid(), "Unknown typedef");
1556 }
1557 }
1558 }
1559
1560 std::string S;
1561 if (IsBitCast) {
1562 // Emit a reinterpret cast. The second operand must be an lvalue, so create
1563 // a temporary.
1564 std::string N = "reint";
1565 unsigned I = 0;
James Molloyb452f782014-06-27 11:53:35 +00001566 while (Intr.Variables.find(N) != Intr.Variables.end())
James Molloydee4ab02014-06-17 13:11:27 +00001567 N = "reint" + utostr(++I);
James Molloyb452f782014-06-27 11:53:35 +00001568 Intr.Variables[N] = Variable(R.first, N + Intr.VariablePostfix);
James Molloydee4ab02014-06-17 13:11:27 +00001569
James Molloyb452f782014-06-27 11:53:35 +00001570 Intr.OS << R.first.str() << " " << Intr.Variables[N].getName() << " = "
1571 << R.second << ";";
1572 Intr.emitNewLine();
James Molloydee4ab02014-06-17 13:11:27 +00001573
James Molloyb452f782014-06-27 11:53:35 +00001574 S = "*(" + castToType.str() + " *) &" + Intr.Variables[N].getName() + "";
James Molloydee4ab02014-06-17 13:11:27 +00001575 } else {
1576 // Emit a normal (static) cast.
1577 S = "(" + castToType.str() + ")(" + R.second + ")";
1578 }
1579
1580 return std::make_pair(castToType, S);
1581}
1582
James Molloyb452f782014-06-27 11:53:35 +00001583std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
James Molloydee4ab02014-06-17 13:11:27 +00001584 // See the documentation in arm_neon.td for a description of these operators.
1585 class LowHalf : public SetTheory::Operator {
1586 public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001587 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1588 ArrayRef<SMLoc> Loc) override {
James Molloydee4ab02014-06-17 13:11:27 +00001589 SetTheory::RecSet Elts2;
1590 ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1591 Elts.insert(Elts2.begin(), Elts2.begin() + (Elts2.size() / 2));
1592 }
1593 };
1594 class HighHalf : public SetTheory::Operator {
1595 public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001596 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1597 ArrayRef<SMLoc> Loc) override {
James Molloydee4ab02014-06-17 13:11:27 +00001598 SetTheory::RecSet Elts2;
1599 ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1600 Elts.insert(Elts2.begin() + (Elts2.size() / 2), Elts2.end());
1601 }
1602 };
1603 class Rev : public SetTheory::Operator {
1604 unsigned ElementSize;
1605
1606 public:
1607 Rev(unsigned ElementSize) : ElementSize(ElementSize) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001608 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1609 ArrayRef<SMLoc> Loc) override {
James Molloydee4ab02014-06-17 13:11:27 +00001610 SetTheory::RecSet Elts2;
1611 ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Elts2, Loc);
1612
1613 int64_t VectorSize = cast<IntInit>(Expr->getArg(0))->getValue();
1614 VectorSize /= ElementSize;
1615
1616 std::vector<Record *> Revved;
1617 for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
1618 for (int LI = VectorSize - 1; LI >= 0; --LI) {
1619 Revved.push_back(Elts2[VI + LI]);
1620 }
1621 }
1622
1623 Elts.insert(Revved.begin(), Revved.end());
1624 }
1625 };
1626 class MaskExpander : public SetTheory::Expander {
1627 unsigned N;
1628
1629 public:
1630 MaskExpander(unsigned N) : N(N) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001631 void expand(SetTheory &ST, Record *R, SetTheory::RecSet &Elts) override {
James Molloydee4ab02014-06-17 13:11:27 +00001632 unsigned Addend = 0;
1633 if (R->getName() == "mask0")
1634 Addend = 0;
1635 else if (R->getName() == "mask1")
1636 Addend = N;
1637 else
1638 return;
1639 for (unsigned I = 0; I < N; ++I)
1640 Elts.insert(R->getRecords().getDef("sv" + utostr(I + Addend)));
1641 }
1642 };
1643
1644 // (shuffle arg1, arg2, sequence)
1645 std::pair<Type, std::string> Arg1 =
1646 emitDagArg(DI->getArg(0), DI->getArgName(0));
1647 std::pair<Type, std::string> Arg2 =
1648 emitDagArg(DI->getArg(1), DI->getArgName(1));
1649 assert_with_loc(Arg1.first == Arg2.first,
1650 "Different types in arguments to shuffle!");
1651
1652 SetTheory ST;
James Molloydee4ab02014-06-17 13:11:27 +00001653 SetTheory::RecSet Elts;
Craig Topperbccb7732015-04-24 06:53:50 +00001654 ST.addOperator("lowhalf", llvm::make_unique<LowHalf>());
1655 ST.addOperator("highhalf", llvm::make_unique<HighHalf>());
1656 ST.addOperator("rev",
1657 llvm::make_unique<Rev>(Arg1.first.getElementSizeInBits()));
1658 ST.addExpander("MaskExpand",
1659 llvm::make_unique<MaskExpander>(Arg1.first.getNumElements()));
Craig Topper5fc8fc22014-08-27 06:28:36 +00001660 ST.evaluate(DI->getArg(2), Elts, None);
James Molloydee4ab02014-06-17 13:11:27 +00001661
1662 std::string S = "__builtin_shufflevector(" + Arg1.second + ", " + Arg2.second;
1663 for (auto &E : Elts) {
1664 StringRef Name = E->getName();
1665 assert_with_loc(Name.startswith("sv"),
1666 "Incorrect element kind in shuffle mask!");
1667 S += ", " + Name.drop_front(2).str();
1668 }
1669 S += ")";
1670
1671 // Recalculate the return type - the shuffle may have halved or doubled it.
1672 Type T(Arg1.first);
1673 if (Elts.size() > T.getNumElements()) {
1674 assert_with_loc(
1675 Elts.size() == T.getNumElements() * 2,
1676 "Can only double or half the number of elements in a shuffle!");
1677 T.doubleLanes();
1678 } else if (Elts.size() < T.getNumElements()) {
1679 assert_with_loc(
1680 Elts.size() == T.getNumElements() / 2,
1681 "Can only double or half the number of elements in a shuffle!");
1682 T.halveLanes();
1683 }
1684
1685 return std::make_pair(T, S);
1686}
1687
James Molloyb452f782014-06-27 11:53:35 +00001688std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDup(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001689 assert_with_loc(DI->getNumArgs() == 1, "dup() expects one argument");
1690 std::pair<Type, std::string> A = emitDagArg(DI->getArg(0), DI->getArgName(0));
1691 assert_with_loc(A.first.isScalar(), "dup() expects a scalar argument");
1692
James Molloyb452f782014-06-27 11:53:35 +00001693 Type T = Intr.getBaseType();
James Molloydee4ab02014-06-17 13:11:27 +00001694 assert_with_loc(T.isVector(), "dup() used but default type is scalar!");
1695 std::string S = "(" + T.str() + ") {";
1696 for (unsigned I = 0; I < T.getNumElements(); ++I) {
1697 if (I != 0)
1698 S += ", ";
1699 S += A.second;
1700 }
1701 S += "}";
1702
1703 return std::make_pair(T, S);
1704}
1705
James Molloyb452f782014-06-27 11:53:35 +00001706std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSplat(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001707 assert_with_loc(DI->getNumArgs() == 2, "splat() expects two arguments");
1708 std::pair<Type, std::string> A = emitDagArg(DI->getArg(0), DI->getArgName(0));
1709 std::pair<Type, std::string> B = emitDagArg(DI->getArg(1), DI->getArgName(1));
1710
1711 assert_with_loc(B.first.isScalar(),
1712 "splat() requires a scalar int as the second argument");
1713
1714 std::string S = "__builtin_shufflevector(" + A.second + ", " + A.second;
James Molloyb452f782014-06-27 11:53:35 +00001715 for (unsigned I = 0; I < Intr.getBaseType().getNumElements(); ++I) {
James Molloydee4ab02014-06-17 13:11:27 +00001716 S += ", " + B.second;
1717 }
1718 S += ")";
1719
James Molloyb452f782014-06-27 11:53:35 +00001720 return std::make_pair(Intr.getBaseType(), S);
James Molloydee4ab02014-06-17 13:11:27 +00001721}
1722
James Molloyb452f782014-06-27 11:53:35 +00001723std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSaveTemp(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001724 assert_with_loc(DI->getNumArgs() == 2, "save_temp() expects two arguments");
1725 std::pair<Type, std::string> A = emitDagArg(DI->getArg(1), DI->getArgName(1));
1726
1727 assert_with_loc(!A.first.isVoid(),
1728 "Argument to save_temp() must have non-void type!");
1729
1730 std::string N = DI->getArgName(0);
1731 assert_with_loc(N.size(), "save_temp() expects a name as the first argument");
1732
James Molloyb452f782014-06-27 11:53:35 +00001733 assert_with_loc(Intr.Variables.find(N) == Intr.Variables.end(),
James Molloydee4ab02014-06-17 13:11:27 +00001734 "Variable already defined!");
James Molloyb452f782014-06-27 11:53:35 +00001735 Intr.Variables[N] = Variable(A.first, N + Intr.VariablePostfix);
James Molloydee4ab02014-06-17 13:11:27 +00001736
1737 std::string S =
James Molloyb452f782014-06-27 11:53:35 +00001738 A.first.str() + " " + Intr.Variables[N].getName() + " = " + A.second;
James Molloydee4ab02014-06-17 13:11:27 +00001739
1740 return std::make_pair(Type::getVoid(), S);
1741}
1742
James Molloyb452f782014-06-27 11:53:35 +00001743std::pair<Type, std::string>
1744Intrinsic::DagEmitter::emitDagNameReplace(DagInit *DI) {
1745 std::string S = Intr.Name;
James Molloydee4ab02014-06-17 13:11:27 +00001746
1747 assert_with_loc(DI->getNumArgs() == 2, "name_replace requires 2 arguments!");
1748 std::string ToReplace = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1749 std::string ReplaceWith = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1750
1751 size_t Idx = S.find(ToReplace);
1752
1753 assert_with_loc(Idx != std::string::npos, "name should contain '" + ToReplace + "'!");
1754 S.replace(Idx, ToReplace.size(), ReplaceWith);
1755
1756 return std::make_pair(Type::getVoid(), S);
1757}
1758
James Molloyb452f782014-06-27 11:53:35 +00001759std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagLiteral(DagInit *DI){
James Molloydee4ab02014-06-17 13:11:27 +00001760 std::string Ty = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1761 std::string Value = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1762 return std::make_pair(Type::fromTypedefName(Ty), Value);
1763}
1764
James Molloyb452f782014-06-27 11:53:35 +00001765std::pair<Type, std::string>
1766Intrinsic::DagEmitter::emitDagArg(Init *Arg, std::string ArgName) {
James Molloydee4ab02014-06-17 13:11:27 +00001767 if (ArgName.size()) {
1768 assert_with_loc(!Arg->isComplete(),
1769 "Arguments must either be DAGs or names, not both!");
James Molloyb452f782014-06-27 11:53:35 +00001770 assert_with_loc(Intr.Variables.find(ArgName) != Intr.Variables.end(),
James Molloydee4ab02014-06-17 13:11:27 +00001771 "Variable not defined!");
James Molloyb452f782014-06-27 11:53:35 +00001772 Variable &V = Intr.Variables[ArgName];
James Molloydee4ab02014-06-17 13:11:27 +00001773 return std::make_pair(V.getType(), V.getName());
1774 }
1775
1776 assert(Arg && "Neither ArgName nor Arg?!");
1777 DagInit *DI = dyn_cast<DagInit>(Arg);
1778 assert_with_loc(DI, "Arguments must either be DAGs or names!");
1779
1780 return emitDag(DI);
1781}
1782
1783std::string Intrinsic::generate() {
James Molloyb452f782014-06-27 11:53:35 +00001784 // Little endian intrinsics are simple and don't require any argument
1785 // swapping.
1786 OS << "#ifdef __LITTLE_ENDIAN__\n";
1787
1788 generateImpl(false, "", "");
1789
1790 OS << "#else\n";
1791
1792 // Big endian intrinsics are more complex. The user intended these
1793 // intrinsics to operate on a vector "as-if" loaded by (V)LDR,
1794 // but we load as-if (V)LD1. So we should swap all arguments and
1795 // swap the return value too.
1796 //
1797 // If we call sub-intrinsics, we should call a version that does
1798 // not re-swap the arguments!
1799 generateImpl(true, "", "__noswap_");
1800
1801 // If we're needed early, create a non-swapping variant for
1802 // big-endian.
1803 if (NeededEarly) {
1804 generateImpl(false, "__noswap_", "__noswap_");
1805 }
1806 OS << "#endif\n\n";
1807
1808 return OS.str();
1809}
1810
1811void Intrinsic::generateImpl(bool ReverseArguments,
1812 StringRef NamePrefix, StringRef CallPrefix) {
James Molloydee4ab02014-06-17 13:11:27 +00001813 CurrentRecord = R;
1814
1815 // If we call a macro, our local variables may be corrupted due to
1816 // lack of proper lexical scoping. So, add a globally unique postfix
1817 // to every variable.
1818 //
1819 // indexBody() should have set up the Dependencies set by now.
1820 for (auto *I : Dependencies)
1821 if (I->UseMacro) {
1822 VariablePostfix = "_" + utostr(Emitter.getUniqueNumber());
1823 break;
1824 }
1825
1826 initVariables();
1827
James Molloyb452f782014-06-27 11:53:35 +00001828 emitPrototype(NamePrefix);
James Molloydee4ab02014-06-17 13:11:27 +00001829
1830 if (IsUnavailable) {
1831 OS << " __attribute__((unavailable));";
1832 } else {
1833 emitOpeningBrace();
1834 emitShadowedArgs();
James Molloyb452f782014-06-27 11:53:35 +00001835 if (ReverseArguments)
1836 emitArgumentReversal();
1837 emitBody(CallPrefix);
1838 if (ReverseArguments)
1839 emitReturnReversal();
James Molloydee4ab02014-06-17 13:11:27 +00001840 emitReturn();
1841 emitClosingBrace();
1842 }
1843 OS << "\n";
1844
1845 CurrentRecord = nullptr;
James Molloydee4ab02014-06-17 13:11:27 +00001846}
1847
1848void Intrinsic::indexBody() {
1849 CurrentRecord = R;
1850
1851 initVariables();
James Molloyb452f782014-06-27 11:53:35 +00001852 emitBody("");
James Molloydee4ab02014-06-17 13:11:27 +00001853 OS.str("");
1854
1855 CurrentRecord = nullptr;
1856}
1857
1858//===----------------------------------------------------------------------===//
1859// NeonEmitter implementation
1860//===----------------------------------------------------------------------===//
1861
David Blaikie4c96a5e2015-08-06 18:29:32 +00001862Intrinsic &NeonEmitter::getIntrinsic(StringRef Name, ArrayRef<Type> Types) {
James Molloydee4ab02014-06-17 13:11:27 +00001863 // First, look up the name in the intrinsic map.
1864 assert_with_loc(IntrinsicMap.find(Name.str()) != IntrinsicMap.end(),
1865 ("Intrinsic '" + Name + "' not found!").str());
David Blaikie4c96a5e2015-08-06 18:29:32 +00001866 auto &V = IntrinsicMap.find(Name.str())->second;
James Molloydee4ab02014-06-17 13:11:27 +00001867 std::vector<Intrinsic *> GoodVec;
1868
1869 // Create a string to print if we end up failing.
1870 std::string ErrMsg = "looking up intrinsic '" + Name.str() + "(";
1871 for (unsigned I = 0; I < Types.size(); ++I) {
1872 if (I != 0)
1873 ErrMsg += ", ";
1874 ErrMsg += Types[I].str();
1875 }
1876 ErrMsg += ")'\n";
1877 ErrMsg += "Available overloads:\n";
1878
1879 // Now, look through each intrinsic implementation and see if the types are
1880 // compatible.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001881 for (auto &I : V) {
1882 ErrMsg += " - " + I.getReturnType().str() + " " + I.getMangledName();
James Molloydee4ab02014-06-17 13:11:27 +00001883 ErrMsg += "(";
David Blaikie4c96a5e2015-08-06 18:29:32 +00001884 for (unsigned A = 0; A < I.getNumParams(); ++A) {
James Molloydee4ab02014-06-17 13:11:27 +00001885 if (A != 0)
1886 ErrMsg += ", ";
David Blaikie4c96a5e2015-08-06 18:29:32 +00001887 ErrMsg += I.getParamType(A).str();
James Molloydee4ab02014-06-17 13:11:27 +00001888 }
1889 ErrMsg += ")\n";
1890
David Blaikie4c96a5e2015-08-06 18:29:32 +00001891 if (I.getNumParams() != Types.size())
James Molloydee4ab02014-06-17 13:11:27 +00001892 continue;
1893
1894 bool Good = true;
1895 for (unsigned Arg = 0; Arg < Types.size(); ++Arg) {
David Blaikie4c96a5e2015-08-06 18:29:32 +00001896 if (I.getParamType(Arg) != Types[Arg]) {
James Molloydee4ab02014-06-17 13:11:27 +00001897 Good = false;
1898 break;
1899 }
1900 }
1901 if (Good)
David Blaikie4c96a5e2015-08-06 18:29:32 +00001902 GoodVec.push_back(&I);
James Molloydee4ab02014-06-17 13:11:27 +00001903 }
1904
1905 assert_with_loc(GoodVec.size() > 0,
1906 "No compatible intrinsic found - " + ErrMsg);
1907 assert_with_loc(GoodVec.size() == 1, "Multiple overloads found - " + ErrMsg);
1908
David Blaikie4c96a5e2015-08-06 18:29:32 +00001909 return *GoodVec.front();
James Molloydee4ab02014-06-17 13:11:27 +00001910}
1911
1912void NeonEmitter::createIntrinsic(Record *R,
1913 SmallVectorImpl<Intrinsic *> &Out) {
1914 std::string Name = R->getValueAsString("Name");
1915 std::string Proto = R->getValueAsString("Prototype");
1916 std::string Types = R->getValueAsString("Types");
1917 Record *OperationRec = R->getValueAsDef("Operation");
1918 bool CartesianProductOfTypes = R->getValueAsBit("CartesianProductOfTypes");
James Molloyb452f782014-06-27 11:53:35 +00001919 bool BigEndianSafe = R->getValueAsBit("BigEndianSafe");
James Molloydee4ab02014-06-17 13:11:27 +00001920 std::string Guard = R->getValueAsString("ArchGuard");
1921 bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
1922
1923 // Set the global current record. This allows assert_with_loc to produce
1924 // decent location information even when highly nested.
1925 CurrentRecord = R;
1926
1927 ListInit *Body = OperationRec->getValueAsListInit("Ops");
1928
1929 std::vector<TypeSpec> TypeSpecs = TypeSpec::fromTypeSpecs(Types);
1930
1931 ClassKind CK = ClassNone;
1932 if (R->getSuperClasses().size() >= 2)
1933 CK = ClassMap[R->getSuperClasses()[1]];
1934
1935 std::vector<std::pair<TypeSpec, TypeSpec>> NewTypeSpecs;
1936 for (auto TS : TypeSpecs) {
1937 if (CartesianProductOfTypes) {
1938 Type DefaultT(TS, 'd');
1939 for (auto SrcTS : TypeSpecs) {
1940 Type DefaultSrcT(SrcTS, 'd');
1941 if (TS == SrcTS ||
1942 DefaultSrcT.getSizeInBits() != DefaultT.getSizeInBits())
1943 continue;
1944 NewTypeSpecs.push_back(std::make_pair(TS, SrcTS));
1945 }
1946 } else {
1947 NewTypeSpecs.push_back(std::make_pair(TS, TS));
1948 }
1949 }
1950
1951 std::sort(NewTypeSpecs.begin(), NewTypeSpecs.end());
James Dennettfa245492015-04-06 21:09:24 +00001952 NewTypeSpecs.erase(std::unique(NewTypeSpecs.begin(), NewTypeSpecs.end()),
1953 NewTypeSpecs.end());
David Blaikie4c96a5e2015-08-06 18:29:32 +00001954 auto &Entry = IntrinsicMap[Name];
James Molloydee4ab02014-06-17 13:11:27 +00001955
1956 for (auto &I : NewTypeSpecs) {
David Blaikie4c96a5e2015-08-06 18:29:32 +00001957 Entry.emplace_back(R, Name, Proto, I.first, I.second, CK, Body, *this,
1958 Guard, IsUnavailable, BigEndianSafe);
1959 Out.push_back(&Entry.back());
James Molloydee4ab02014-06-17 13:11:27 +00001960 }
1961
1962 CurrentRecord = nullptr;
1963}
1964
1965/// genBuiltinsDef: Generate the BuiltinsARM.def and BuiltinsAArch64.def
1966/// declaration of builtins, checking for unique builtin declarations.
1967void NeonEmitter::genBuiltinsDef(raw_ostream &OS,
1968 SmallVectorImpl<Intrinsic *> &Defs) {
1969 OS << "#ifdef GET_NEON_BUILTINS\n";
1970
1971 // We only want to emit a builtin once, and we want to emit them in
1972 // alphabetical order, so use a std::set.
1973 std::set<std::string> Builtins;
1974
1975 for (auto *Def : Defs) {
1976 if (Def->hasBody())
1977 continue;
1978 // Functions with 'a' (the splat code) in the type prototype should not get
1979 // their own builtin as they use the non-splat variant.
1980 if (Def->hasSplat())
1981 continue;
1982
1983 std::string S = "BUILTIN(__builtin_neon_" + Def->getMangledName() + ", \"";
1984
1985 S += Def->getBuiltinTypeStr();
1986 S += "\", \"n\")";
1987
1988 Builtins.insert(S);
1989 }
1990
1991 for (auto &S : Builtins)
1992 OS << S << "\n";
1993 OS << "#endif\n\n";
1994}
1995
1996/// Generate the ARM and AArch64 overloaded type checking code for
1997/// SemaChecking.cpp, checking for unique builtin declarations.
1998void NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS,
1999 SmallVectorImpl<Intrinsic *> &Defs) {
2000 OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
2001
2002 // We record each overload check line before emitting because subsequent Inst
2003 // definitions may extend the number of permitted types (i.e. augment the
2004 // Mask). Use std::map to avoid sorting the table by hash number.
2005 struct OverloadInfo {
2006 uint64_t Mask;
2007 int PtrArgNum;
2008 bool HasConstPtr;
2009 OverloadInfo() : Mask(0ULL), PtrArgNum(0), HasConstPtr(false) {}
2010 };
2011 std::map<std::string, OverloadInfo> OverloadMap;
2012
2013 for (auto *Def : Defs) {
2014 // If the def has a body (that is, it has Operation DAGs), it won't call
2015 // __builtin_neon_* so we don't need to generate a definition for it.
2016 if (Def->hasBody())
2017 continue;
2018 // Functions with 'a' (the splat code) in the type prototype should not get
2019 // their own builtin as they use the non-splat variant.
2020 if (Def->hasSplat())
2021 continue;
2022 // Functions which have a scalar argument cannot be overloaded, no need to
2023 // check them if we are emitting the type checking code.
2024 if (Def->protoHasScalar())
2025 continue;
2026
2027 uint64_t Mask = 0ULL;
2028 Type Ty = Def->getReturnType();
Ahmed Bougacha22a16962015-08-21 23:24:18 +00002029 if (Def->getProto()[0] == 'v' ||
2030 isFloatingPointProtoModifier(Def->getProto()[0]))
James Molloydee4ab02014-06-17 13:11:27 +00002031 Ty = Def->getParamType(0);
2032 if (Ty.isPointer())
2033 Ty = Def->getParamType(1);
2034
2035 Mask |= 1ULL << Ty.getNeonEnum();
2036
2037 // Check if the function has a pointer or const pointer argument.
2038 std::string Proto = Def->getProto();
2039 int PtrArgNum = -1;
2040 bool HasConstPtr = false;
2041 for (unsigned I = 0; I < Def->getNumParams(); ++I) {
2042 char ArgType = Proto[I + 1];
2043 if (ArgType == 'c') {
2044 HasConstPtr = true;
2045 PtrArgNum = I;
2046 break;
2047 }
2048 if (ArgType == 'p') {
2049 PtrArgNum = I;
2050 break;
2051 }
2052 }
2053 // For sret builtins, adjust the pointer argument index.
2054 if (PtrArgNum >= 0 && Def->getReturnType().getNumVectors() > 1)
2055 PtrArgNum += 1;
2056
2057 std::string Name = Def->getName();
2058 // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
2059 // and vst1_lane intrinsics. Using a pointer to the vector element
2060 // type with one of those operations causes codegen to select an aligned
2061 // load/store instruction. If you want an unaligned operation,
2062 // the pointer argument needs to have less alignment than element type,
2063 // so just accept any pointer type.
2064 if (Name == "vld1_lane" || Name == "vld1_dup" || Name == "vst1_lane") {
2065 PtrArgNum = -1;
2066 HasConstPtr = false;
2067 }
2068
2069 if (Mask) {
2070 std::string Name = Def->getMangledName();
2071 OverloadMap.insert(std::make_pair(Name, OverloadInfo()));
2072 OverloadInfo &OI = OverloadMap[Name];
2073 OI.Mask |= Mask;
2074 OI.PtrArgNum |= PtrArgNum;
2075 OI.HasConstPtr = HasConstPtr;
2076 }
2077 }
2078
2079 for (auto &I : OverloadMap) {
2080 OverloadInfo &OI = I.second;
2081
2082 OS << "case NEON::BI__builtin_neon_" << I.first << ": ";
2083 OS << "mask = 0x" << utohexstr(OI.Mask) << "ULL";
2084 if (OI.PtrArgNum >= 0)
2085 OS << "; PtrArgNum = " << OI.PtrArgNum;
2086 if (OI.HasConstPtr)
2087 OS << "; HasConstPtr = true";
2088 OS << "; break;\n";
2089 }
2090 OS << "#endif\n\n";
2091}
2092
2093void
2094NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
2095 SmallVectorImpl<Intrinsic *> &Defs) {
2096 OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
2097
2098 std::set<std::string> Emitted;
2099
2100 for (auto *Def : Defs) {
2101 if (Def->hasBody())
2102 continue;
2103 // Functions with 'a' (the splat code) in the type prototype should not get
2104 // their own builtin as they use the non-splat variant.
2105 if (Def->hasSplat())
2106 continue;
Alp Toker958027b2014-07-14 19:42:55 +00002107 // Functions which do not have an immediate do not need to have range
2108 // checking code emitted.
James Molloydee4ab02014-06-17 13:11:27 +00002109 if (!Def->hasImmediate())
2110 continue;
2111 if (Emitted.find(Def->getMangledName()) != Emitted.end())
2112 continue;
2113
2114 std::string LowerBound, UpperBound;
2115
2116 Record *R = Def->getRecord();
2117 if (R->getValueAsBit("isVCVT_N")) {
2118 // VCVT between floating- and fixed-point values takes an immediate
2119 // in the range [1, 32) for f32 or [1, 64) for f64.
2120 LowerBound = "1";
2121 if (Def->getBaseType().getElementSizeInBits() == 32)
2122 UpperBound = "31";
2123 else
2124 UpperBound = "63";
2125 } else if (R->getValueAsBit("isScalarShift")) {
2126 // Right shifts have an 'r' in the name, left shifts do not. Convert
2127 // instructions have the same bounds and right shifts.
2128 if (Def->getName().find('r') != std::string::npos ||
2129 Def->getName().find("cvt") != std::string::npos)
2130 LowerBound = "1";
2131
2132 UpperBound = utostr(Def->getReturnType().getElementSizeInBits() - 1);
2133 } else if (R->getValueAsBit("isShift")) {
Alp Toker958027b2014-07-14 19:42:55 +00002134 // Builtins which are overloaded by type will need to have their upper
James Molloydee4ab02014-06-17 13:11:27 +00002135 // bound computed at Sema time based on the type constant.
2136
2137 // Right shifts have an 'r' in the name, left shifts do not.
2138 if (Def->getName().find('r') != std::string::npos)
2139 LowerBound = "1";
2140 UpperBound = "RFT(TV, true)";
2141 } else if (Def->getClassKind(true) == ClassB) {
2142 // ClassB intrinsics have a type (and hence lane number) that is only
2143 // known at runtime.
2144 if (R->getValueAsBit("isLaneQ"))
2145 UpperBound = "RFT(TV, false, true)";
2146 else
2147 UpperBound = "RFT(TV, false, false)";
2148 } else {
2149 // The immediate generally refers to a lane in the preceding argument.
2150 assert(Def->getImmediateIdx() > 0);
2151 Type T = Def->getParamType(Def->getImmediateIdx() - 1);
2152 UpperBound = utostr(T.getNumElements() - 1);
2153 }
2154
2155 // Calculate the index of the immediate that should be range checked.
2156 unsigned Idx = Def->getNumParams();
2157 if (Def->hasImmediate())
2158 Idx = Def->getGeneratedParamIdx(Def->getImmediateIdx());
2159
2160 OS << "case NEON::BI__builtin_neon_" << Def->getMangledName() << ": "
2161 << "i = " << Idx << ";";
2162 if (LowerBound.size())
2163 OS << " l = " << LowerBound << ";";
2164 if (UpperBound.size())
2165 OS << " u = " << UpperBound << ";";
2166 OS << " break;\n";
2167
2168 Emitted.insert(Def->getMangledName());
2169 }
2170
2171 OS << "#endif\n\n";
2172}
2173
2174/// runHeader - Emit a file with sections defining:
2175/// 1. the NEON section of BuiltinsARM.def and BuiltinsAArch64.def.
2176/// 2. the SemaChecking code for the type overload checking.
2177/// 3. the SemaChecking code for validation of intrinsic immediate arguments.
2178void NeonEmitter::runHeader(raw_ostream &OS) {
2179 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2180
2181 SmallVector<Intrinsic *, 128> Defs;
2182 for (auto *R : RV)
2183 createIntrinsic(R, Defs);
2184
2185 // Generate shared BuiltinsXXX.def
2186 genBuiltinsDef(OS, Defs);
2187
2188 // Generate ARM overloaded type checking code for SemaChecking.cpp
2189 genOverloadTypeCheckCode(OS, Defs);
2190
2191 // Generate ARM range checking code for shift/lane immediates.
2192 genIntrinsicRangeCheckCode(OS, Defs);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002193}
2194
2195/// run - Read the records in arm_neon.td and output arm_neon.h. arm_neon.h
2196/// is comprised of type definitions and function declarations.
2197void NeonEmitter::run(raw_ostream &OS) {
James Molloydee4ab02014-06-17 13:11:27 +00002198 OS << "/*===---- arm_neon.h - ARM Neon intrinsics "
2199 "------------------------------"
2200 "---===\n"
2201 " *\n"
2202 " * Permission is hereby granted, free of charge, to any person "
2203 "obtaining "
2204 "a copy\n"
2205 " * of this software and associated documentation files (the "
2206 "\"Software\"),"
2207 " to deal\n"
2208 " * in the Software without restriction, including without limitation "
2209 "the "
2210 "rights\n"
2211 " * to use, copy, modify, merge, publish, distribute, sublicense, "
2212 "and/or sell\n"
2213 " * copies of the Software, and to permit persons to whom the Software "
2214 "is\n"
2215 " * furnished to do so, subject to the following conditions:\n"
2216 " *\n"
2217 " * The above copyright notice and this permission notice shall be "
2218 "included in\n"
2219 " * all copies or substantial portions of the Software.\n"
2220 " *\n"
2221 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2222 "EXPRESS OR\n"
2223 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2224 "MERCHANTABILITY,\n"
2225 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2226 "SHALL THE\n"
2227 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2228 "OTHER\n"
2229 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2230 "ARISING FROM,\n"
2231 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2232 "DEALINGS IN\n"
2233 " * THE SOFTWARE.\n"
2234 " *\n"
2235 " *===-----------------------------------------------------------------"
2236 "---"
2237 "---===\n"
2238 " */\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002239
2240 OS << "#ifndef __ARM_NEON_H\n";
2241 OS << "#define __ARM_NEON_H\n\n";
2242
Tim Northover5bb34ca2013-11-21 12:36:34 +00002243 OS << "#if !defined(__ARM_NEON)\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002244 OS << "#error \"NEON support not enabled\"\n";
2245 OS << "#endif\n\n";
2246
2247 OS << "#include <stdint.h>\n\n";
2248
2249 // Emit NEON-specific scalar typedefs.
2250 OS << "typedef float float32_t;\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002251 OS << "typedef __fp16 float16_t;\n";
2252
2253 OS << "#ifdef __aarch64__\n";
2254 OS << "typedef double float64_t;\n";
2255 OS << "#endif\n\n";
2256
2257 // For now, signedness of polynomial types depends on target
2258 OS << "#ifdef __aarch64__\n";
2259 OS << "typedef uint8_t poly8_t;\n";
2260 OS << "typedef uint16_t poly16_t;\n";
Kevin Qincaac85e2013-11-14 03:29:16 +00002261 OS << "typedef uint64_t poly64_t;\n";
Kevin Qinfb79d7f2013-12-10 06:49:01 +00002262 OS << "typedef __uint128_t poly128_t;\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002263 OS << "#else\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002264 OS << "typedef int8_t poly8_t;\n";
2265 OS << "typedef int16_t poly16_t;\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002266 OS << "#endif\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002267
2268 // Emit Neon vector typedefs.
Tim Northover2fe823a2013-08-01 09:23:19 +00002269 std::string TypedefTypes(
Kevin Qincaac85e2013-11-14 03:29:16 +00002270 "cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfdQdPcQPcPsQPsPlQPl");
James Molloydee4ab02014-06-17 13:11:27 +00002271 std::vector<TypeSpec> TDTypeVec = TypeSpec::fromTypeSpecs(TypedefTypes);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002272
2273 // Emit vector typedefs.
James Molloydee4ab02014-06-17 13:11:27 +00002274 bool InIfdef = false;
2275 for (auto &TS : TDTypeVec) {
2276 bool IsA64 = false;
2277 Type T(TS, 'd');
2278 if (T.isDouble() || (T.isPoly() && T.isLong()))
2279 IsA64 = true;
Tim Northover2fe823a2013-08-01 09:23:19 +00002280
James Molloydee4ab02014-06-17 13:11:27 +00002281 if (InIfdef && !IsA64) {
Jiangning Liu4617e9d2013-10-04 09:21:17 +00002282 OS << "#endif\n";
James Molloydee4ab02014-06-17 13:11:27 +00002283 InIfdef = false;
2284 }
2285 if (!InIfdef && IsA64) {
Tim Northover2fe823a2013-08-01 09:23:19 +00002286 OS << "#ifdef __aarch64__\n";
James Molloydee4ab02014-06-17 13:11:27 +00002287 InIfdef = true;
2288 }
Tim Northover2fe823a2013-08-01 09:23:19 +00002289
James Molloydee4ab02014-06-17 13:11:27 +00002290 if (T.isPoly())
Peter Collingbournebee583f2011-10-06 13:03:08 +00002291 OS << "typedef __attribute__((neon_polyvector_type(";
2292 else
2293 OS << "typedef __attribute__((neon_vector_type(";
2294
James Molloydee4ab02014-06-17 13:11:27 +00002295 Type T2 = T;
2296 T2.makeScalar();
2297 OS << utostr(T.getNumElements()) << "))) ";
2298 OS << T2.str();
2299 OS << " " << T.str() << ";\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002300 }
James Molloydee4ab02014-06-17 13:11:27 +00002301 if (InIfdef)
Kevin Qincaac85e2013-11-14 03:29:16 +00002302 OS << "#endif\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002303 OS << "\n";
2304
2305 // Emit struct typedefs.
James Molloydee4ab02014-06-17 13:11:27 +00002306 InIfdef = false;
2307 for (unsigned NumMembers = 2; NumMembers <= 4; ++NumMembers) {
2308 for (auto &TS : TDTypeVec) {
2309 bool IsA64 = false;
2310 Type T(TS, 'd');
2311 if (T.isDouble() || (T.isPoly() && T.isLong()))
2312 IsA64 = true;
Tim Northover2fe823a2013-08-01 09:23:19 +00002313
James Molloydee4ab02014-06-17 13:11:27 +00002314 if (InIfdef && !IsA64) {
Jiangning Liu4617e9d2013-10-04 09:21:17 +00002315 OS << "#endif\n";
James Molloydee4ab02014-06-17 13:11:27 +00002316 InIfdef = false;
2317 }
2318 if (!InIfdef && IsA64) {
Tim Northover2fe823a2013-08-01 09:23:19 +00002319 OS << "#ifdef __aarch64__\n";
James Molloydee4ab02014-06-17 13:11:27 +00002320 InIfdef = true;
2321 }
Tim Northover2fe823a2013-08-01 09:23:19 +00002322
James Molloydee4ab02014-06-17 13:11:27 +00002323 char M = '2' + (NumMembers - 2);
2324 Type VT(TS, M);
2325 OS << "typedef struct " << VT.str() << " {\n";
2326 OS << " " << T.str() << " val";
2327 OS << "[" << utostr(NumMembers) << "]";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002328 OS << ";\n} ";
James Molloydee4ab02014-06-17 13:11:27 +00002329 OS << VT.str() << ";\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002330 OS << "\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002331 }
2332 }
James Molloydee4ab02014-06-17 13:11:27 +00002333 if (InIfdef)
Kevin Qincaac85e2013-11-14 03:29:16 +00002334 OS << "#endif\n";
2335 OS << "\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002336
James Molloydee4ab02014-06-17 13:11:27 +00002337 OS << "#define __ai static inline __attribute__((__always_inline__, "
2338 "__nodebug__))\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002339
James Molloydee4ab02014-06-17 13:11:27 +00002340 SmallVector<Intrinsic *, 128> Defs;
2341 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2342 for (auto *R : RV)
2343 createIntrinsic(R, Defs);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002344
James Molloydee4ab02014-06-17 13:11:27 +00002345 for (auto *I : Defs)
2346 I->indexBody();
Tim Northover2fe823a2013-08-01 09:23:19 +00002347
James Molloydee4ab02014-06-17 13:11:27 +00002348 std::stable_sort(
2349 Defs.begin(), Defs.end(),
2350 [](const Intrinsic *A, const Intrinsic *B) { return *A < *B; });
Tim Northover2fe823a2013-08-01 09:23:19 +00002351
James Molloydee4ab02014-06-17 13:11:27 +00002352 // Only emit a def when its requirements have been met.
2353 // FIXME: This loop could be made faster, but it's fast enough for now.
2354 bool MadeProgress = true;
2355 std::string InGuard = "";
2356 while (!Defs.empty() && MadeProgress) {
2357 MadeProgress = false;
2358
2359 for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2360 I != Defs.end(); /*No step*/) {
2361 bool DependenciesSatisfied = true;
2362 for (auto *II : (*I)->getDependencies()) {
2363 if (std::find(Defs.begin(), Defs.end(), II) != Defs.end())
2364 DependenciesSatisfied = false;
2365 }
2366 if (!DependenciesSatisfied) {
2367 // Try the next one.
2368 ++I;
2369 continue;
2370 }
2371
2372 // Emit #endif/#if pair if needed.
2373 if ((*I)->getGuard() != InGuard) {
2374 if (!InGuard.empty())
2375 OS << "#endif\n";
2376 InGuard = (*I)->getGuard();
2377 if (!InGuard.empty())
2378 OS << "#if " << InGuard << "\n";
2379 }
2380
2381 // Actually generate the intrinsic code.
2382 OS << (*I)->generate();
2383
2384 MadeProgress = true;
2385 I = Defs.erase(I);
2386 }
Tim Northover2fe823a2013-08-01 09:23:19 +00002387 }
James Molloydee4ab02014-06-17 13:11:27 +00002388 assert(Defs.empty() && "Some requirements were not satisfied!");
2389 if (!InGuard.empty())
2390 OS << "#endif\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002391
James Molloydee4ab02014-06-17 13:11:27 +00002392 OS << "\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002393 OS << "#undef __ai\n\n";
2394 OS << "#endif /* __ARM_NEON_H */\n";
2395}
2396
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002397namespace clang {
2398void EmitNeon(RecordKeeper &Records, raw_ostream &OS) {
2399 NeonEmitter(Records).run(OS);
2400}
2401void EmitNeonSema(RecordKeeper &Records, raw_ostream &OS) {
2402 NeonEmitter(Records).runHeader(OS);
2403}
2404void EmitNeonTest(RecordKeeper &Records, raw_ostream &OS) {
Craig Topper0039f3f2014-06-18 03:57:25 +00002405 llvm_unreachable("Neon test generation no longer implemented!");
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002406}
2407} // End namespace clang