blob: 62f9740296e36ef505858f7a1e4d0a8820d0b905 [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
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000027#include "llvm/ADT/ArrayRef.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000028#include "llvm/ADT/DenseMap.h"
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000029#include "llvm/ADT/None.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000030#include "llvm/ADT/SmallVector.h"
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000031#include "llvm/ADT/STLExtras.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000032#include "llvm/ADT/StringExtras.h"
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000033#include "llvm/ADT/StringRef.h"
34#include "llvm/Support/Casting.h"
David Blaikie8a40f702012-01-17 06:56:22 +000035#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000036#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000037#include "llvm/TableGen/Error.h"
38#include "llvm/TableGen/Record.h"
James Molloydee4ab02014-06-17 13:11:27 +000039#include "llvm/TableGen/SetTheory.h"
James Molloydee4ab02014-06-17 13:11:27 +000040#include <algorithm>
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000041#include <cassert>
42#include <cctype>
43#include <cstddef>
44#include <cstdint>
David Blaikie4c96a5e2015-08-06 18:29:32 +000045#include <deque>
Chandler Carruth575bc3ba2015-01-14 11:23:58 +000046#include <map>
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000047#include <set>
Chandler Carruth575bc3ba2015-01-14 11:23:58 +000048#include <sstream>
49#include <string>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000050#include <utility>
Chandler Carruth575bc3ba2015-01-14 11:23:58 +000051#include <vector>
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000052
Peter Collingbournebee583f2011-10-06 13:03:08 +000053using namespace llvm;
54
James Molloydee4ab02014-06-17 13:11:27 +000055namespace {
56
57// While globals are generally bad, this one allows us to perform assertions
58// liberally and somehow still trace them back to the def they indirectly
59// came from.
60static Record *CurrentRecord = nullptr;
61static void assert_with_loc(bool Assertion, const std::string &Str) {
62 if (!Assertion) {
63 if (CurrentRecord)
64 PrintFatalError(CurrentRecord->getLoc(), Str);
65 else
66 PrintFatalError(Str);
67 }
68}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000069
70enum ClassKind {
71 ClassNone,
James Molloydee4ab02014-06-17 13:11:27 +000072 ClassI, // generic integer instruction, e.g., "i8" suffix
73 ClassS, // signed/unsigned/poly, e.g., "s8", "u8" or "p8" suffix
74 ClassW, // width-specific instruction, e.g., "8" suffix
75 ClassB, // bitcast arguments with enum argument to specify type
76 ClassL, // Logical instructions which are op instructions
77 // but we need to not emit any suffix for in our
78 // tests.
79 ClassNoTest // Instructions which we do not test since they are
80 // not TRUE instructions.
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000081};
82
83/// NeonTypeFlags - Flags to identify the types for overloaded Neon
84/// builtins. These must be kept in sync with the flags in
85/// include/clang/Basic/TargetBuiltins.h.
James Molloydee4ab02014-06-17 13:11:27 +000086namespace NeonTypeFlags {
Eugene Zelenko58ab22f2016-11-29 22:44:24 +000087
James Molloydee4ab02014-06-17 13:11:27 +000088enum { EltTypeMask = 0xf, UnsignedFlag = 0x10, QuadFlag = 0x20 };
89
90enum EltType {
91 Int8,
92 Int16,
93 Int32,
94 Int64,
95 Poly8,
96 Poly16,
97 Poly64,
98 Poly128,
99 Float16,
100 Float32,
101 Float64
102};
James Molloydee4ab02014-06-17 13:11:27 +0000103
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000104} // end namespace NeonTypeFlags
105
James Molloydee4ab02014-06-17 13:11:27 +0000106class NeonEmitter;
James Molloydee4ab02014-06-17 13:11:27 +0000107
108//===----------------------------------------------------------------------===//
109// TypeSpec
110//===----------------------------------------------------------------------===//
111
112/// A TypeSpec is just a simple wrapper around a string, but gets its own type
113/// for strong typing purposes.
114///
115/// A TypeSpec can be used to create a type.
116class TypeSpec : public std::string {
117public:
118 static std::vector<TypeSpec> fromTypeSpecs(StringRef Str) {
119 std::vector<TypeSpec> Ret;
120 TypeSpec Acc;
121 for (char I : Str.str()) {
122 if (islower(I)) {
123 Acc.push_back(I);
124 Ret.push_back(TypeSpec(Acc));
125 Acc.clear();
126 } else {
127 Acc.push_back(I);
128 }
129 }
130 return Ret;
131 }
132};
133
134//===----------------------------------------------------------------------===//
135// Type
136//===----------------------------------------------------------------------===//
137
138/// A Type. Not much more to say here.
139class Type {
140private:
141 TypeSpec TS;
142
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000143 bool Float, Signed, Immediate, Void, Poly, Constant, Pointer;
James Molloydee4ab02014-06-17 13:11:27 +0000144 // ScalarForMangling and NoManglingQ are really not suited to live here as
145 // they are not related to the type. But they live in the TypeSpec (not the
146 // prototype), so this is really the only place to store them.
147 bool ScalarForMangling, NoManglingQ;
148 unsigned Bitwidth, ElementBitwidth, NumVectors;
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000149
150public:
James Molloydee4ab02014-06-17 13:11:27 +0000151 Type()
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000152 : Float(false), Signed(false), Immediate(false), Void(true), Poly(false),
153 Constant(false), Pointer(false), ScalarForMangling(false),
154 NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000155
James Molloydee4ab02014-06-17 13:11:27 +0000156 Type(TypeSpec TS, char CharMod)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000157 : TS(std::move(TS)), Float(false), Signed(false), Immediate(false),
158 Void(false), Poly(false), Constant(false), Pointer(false),
159 ScalarForMangling(false), NoManglingQ(false), Bitwidth(0),
160 ElementBitwidth(0), NumVectors(0) {
James Molloydee4ab02014-06-17 13:11:27 +0000161 applyModifier(CharMod);
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000162 }
163
James Molloydee4ab02014-06-17 13:11:27 +0000164 /// Returns a type representing "void".
165 static Type getVoid() { return Type(); }
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000166
James Molloydee4ab02014-06-17 13:11:27 +0000167 bool operator==(const Type &Other) const { return str() == Other.str(); }
168 bool operator!=(const Type &Other) const { return !operator==(Other); }
169
170 //
171 // Query functions
172 //
173 bool isScalarForMangling() const { return ScalarForMangling; }
174 bool noManglingQ() const { return NoManglingQ; }
175
176 bool isPointer() const { return Pointer; }
177 bool isFloating() const { return Float; }
178 bool isInteger() const { return !Float && !Poly; }
179 bool isSigned() const { return Signed; }
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000180 bool isImmediate() const { return Immediate; }
James Molloydee4ab02014-06-17 13:11:27 +0000181 bool isScalar() const { return NumVectors == 0; }
182 bool isVector() const { return NumVectors > 0; }
183 bool isFloat() const { return Float && ElementBitwidth == 32; }
184 bool isDouble() const { return Float && ElementBitwidth == 64; }
185 bool isHalf() const { return Float && ElementBitwidth == 16; }
186 bool isPoly() const { return Poly; }
187 bool isChar() const { return ElementBitwidth == 8; }
188 bool isShort() const { return !Float && ElementBitwidth == 16; }
189 bool isInt() const { return !Float && ElementBitwidth == 32; }
190 bool isLong() const { return !Float && ElementBitwidth == 64; }
191 bool isVoid() const { return Void; }
192 unsigned getNumElements() const { return Bitwidth / ElementBitwidth; }
193 unsigned getSizeInBits() const { return Bitwidth; }
194 unsigned getElementSizeInBits() const { return ElementBitwidth; }
195 unsigned getNumVectors() const { return NumVectors; }
196
197 //
198 // Mutator functions
199 //
200 void makeUnsigned() { Signed = false; }
201 void makeSigned() { Signed = true; }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000202
James Molloydee4ab02014-06-17 13:11:27 +0000203 void makeInteger(unsigned ElemWidth, bool Sign) {
204 Float = false;
205 Poly = false;
206 Signed = Sign;
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000207 Immediate = false;
208 ElementBitwidth = ElemWidth;
209 }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000210
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000211 void makeImmediate(unsigned ElemWidth) {
212 Float = false;
213 Poly = false;
214 Signed = true;
215 Immediate = true;
James Molloydee4ab02014-06-17 13:11:27 +0000216 ElementBitwidth = ElemWidth;
217 }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000218
James Molloydee4ab02014-06-17 13:11:27 +0000219 void makeScalar() {
220 Bitwidth = ElementBitwidth;
221 NumVectors = 0;
222 }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000223
James Molloydee4ab02014-06-17 13:11:27 +0000224 void makeOneVector() {
225 assert(isVector());
226 NumVectors = 1;
227 }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000228
James Molloydee4ab02014-06-17 13:11:27 +0000229 void doubleLanes() {
230 assert_with_loc(Bitwidth != 128, "Can't get bigger than 128!");
231 Bitwidth = 128;
232 }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000233
James Molloydee4ab02014-06-17 13:11:27 +0000234 void halveLanes() {
235 assert_with_loc(Bitwidth != 64, "Can't get smaller than 64!");
236 Bitwidth = 64;
237 }
238
239 /// Return the C string representation of a type, which is the typename
240 /// defined in stdint.h or arm_neon.h.
241 std::string str() const;
242
243 /// Return the string representation of a type, which is an encoded
244 /// string for passing to the BUILTIN() macro in Builtins.def.
245 std::string builtin_str() const;
246
247 /// Return the value in NeonTypeFlags for this type.
248 unsigned getNeonEnum() const;
249
250 /// Parse a type from a stdint.h or arm_neon.h typedef name,
251 /// for example uint32x2_t or int64_t.
252 static Type fromTypedefName(StringRef Name);
253
254private:
255 /// Creates the type based on the typespec string in TS.
256 /// Sets "Quad" to true if the "Q" or "H" modifiers were
257 /// seen. This is needed by applyModifier as some modifiers
258 /// only take effect if the type size was changed by "Q" or "H".
259 void applyTypespec(bool &Quad);
260 /// Applies a prototype modifier to the type.
261 void applyModifier(char Mod);
262};
263
264//===----------------------------------------------------------------------===//
265// Variable
266//===----------------------------------------------------------------------===//
267
268/// A variable is a simple class that just has a type and a name.
269class Variable {
270 Type T;
271 std::string N;
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000272
273public:
James Molloydee4ab02014-06-17 13:11:27 +0000274 Variable() : T(Type::getVoid()), N("") {}
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000275 Variable(Type T, std::string N) : T(std::move(T)), N(std::move(N)) {}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000276
James Molloydee4ab02014-06-17 13:11:27 +0000277 Type getType() const { return T; }
278 std::string getName() const { return "__" + N; }
279};
280
281//===----------------------------------------------------------------------===//
282// Intrinsic
283//===----------------------------------------------------------------------===//
284
285/// The main grunt class. This represents an instantiation of an intrinsic with
286/// a particular typespec and prototype.
287class Intrinsic {
James Molloyb452f782014-06-27 11:53:35 +0000288 friend class DagEmitter;
289
James Molloydee4ab02014-06-17 13:11:27 +0000290 /// The Record this intrinsic was created from.
291 Record *R;
292 /// The unmangled name and prototype.
293 std::string Name, Proto;
294 /// The input and output typespecs. InTS == OutTS except when
295 /// CartesianProductOfTypes is 1 - this is the case for vreinterpret.
296 TypeSpec OutTS, InTS;
297 /// The base class kind. Most intrinsics use ClassS, which has full type
298 /// info for integers (s32/u32). Some use ClassI, which doesn't care about
299 /// signedness (i32), while some (ClassB) have no type at all, only a width
300 /// (32).
301 ClassKind CK;
302 /// The list of DAGs for the body. May be empty, in which case we should
303 /// emit a builtin call.
304 ListInit *Body;
305 /// The architectural #ifdef guard.
306 std::string Guard;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000307 /// Set if the Unavailable bit is 1. This means we don't generate a body,
James Molloydee4ab02014-06-17 13:11:27 +0000308 /// just an "unavailable" attribute on a declaration.
309 bool IsUnavailable;
James Molloyb452f782014-06-27 11:53:35 +0000310 /// Is this intrinsic safe for big-endian? or does it need its arguments
311 /// reversing?
312 bool BigEndianSafe;
James Molloydee4ab02014-06-17 13:11:27 +0000313
314 /// The types of return value [0] and parameters [1..].
315 std::vector<Type> Types;
316 /// The local variables defined.
317 std::map<std::string, Variable> Variables;
318 /// NeededEarly - set if any other intrinsic depends on this intrinsic.
319 bool NeededEarly;
320 /// UseMacro - set if we should implement using a macro or unset for a
321 /// function.
322 bool UseMacro;
323 /// The set of intrinsics that this intrinsic uses/requires.
324 std::set<Intrinsic *> Dependencies;
325 /// The "base type", which is Type('d', OutTS). InBaseType is only
326 /// different if CartesianProductOfTypes = 1 (for vreinterpret).
327 Type BaseType, InBaseType;
328 /// The return variable.
329 Variable RetVar;
330 /// A postfix to apply to every variable. Defaults to "".
331 std::string VariablePostfix;
332
333 NeonEmitter &Emitter;
334 std::stringstream OS;
335
336public:
337 Intrinsic(Record *R, StringRef Name, StringRef Proto, TypeSpec OutTS,
338 TypeSpec InTS, ClassKind CK, ListInit *Body, NeonEmitter &Emitter,
James Molloyb452f782014-06-27 11:53:35 +0000339 StringRef Guard, bool IsUnavailable, bool BigEndianSafe)
James Molloydee4ab02014-06-17 13:11:27 +0000340 : R(R), Name(Name.str()), Proto(Proto.str()), OutTS(OutTS), InTS(InTS),
341 CK(CK), Body(Body), Guard(Guard.str()), IsUnavailable(IsUnavailable),
James Molloyb452f782014-06-27 11:53:35 +0000342 BigEndianSafe(BigEndianSafe), NeededEarly(false), UseMacro(false),
343 BaseType(OutTS, 'd'), InBaseType(InTS, 'd'), Emitter(Emitter) {
James Molloydee4ab02014-06-17 13:11:27 +0000344 // If this builtin takes an immediate argument, we need to #define it rather
345 // than use a standard declaration, so that SemaChecking can range check
346 // the immediate passed by the user.
347 if (Proto.find('i') != std::string::npos)
348 UseMacro = true;
349
350 // Pointer arguments need to use macros to avoid hiding aligned attributes
351 // from the pointer type.
352 if (Proto.find('p') != std::string::npos ||
353 Proto.find('c') != std::string::npos)
354 UseMacro = true;
355
356 // It is not permitted to pass or return an __fp16 by value, so intrinsics
357 // taking a scalar float16_t must be implemented as macros.
358 if (OutTS.find('h') != std::string::npos &&
359 Proto.find('s') != std::string::npos)
360 UseMacro = true;
361
362 // Modify the TypeSpec per-argument to get a concrete Type, and create
363 // known variables for each.
364 // Types[0] is the return value.
Benjamin Kramer3204b152015-05-29 19:42:19 +0000365 Types.emplace_back(OutTS, Proto[0]);
James Molloydee4ab02014-06-17 13:11:27 +0000366 for (unsigned I = 1; I < Proto.size(); ++I)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000367 Types.emplace_back(InTS, Proto[I]);
James Molloydee4ab02014-06-17 13:11:27 +0000368 }
369
370 /// Get the Record that this intrinsic is based off.
371 Record *getRecord() const { return R; }
372 /// Get the set of Intrinsics that this intrinsic calls.
373 /// this is the set of immediate dependencies, NOT the
374 /// transitive closure.
375 const std::set<Intrinsic *> &getDependencies() const { return Dependencies; }
376 /// Get the architectural guard string (#ifdef).
377 std::string getGuard() const { return Guard; }
378 /// Get the non-mangled name.
379 std::string getName() const { return Name; }
380
381 /// Return true if the intrinsic takes an immediate operand.
382 bool hasImmediate() const {
383 return Proto.find('i') != std::string::npos;
384 }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000385
James Molloydee4ab02014-06-17 13:11:27 +0000386 /// Return the parameter index of the immediate operand.
387 unsigned getImmediateIdx() const {
388 assert(hasImmediate());
389 unsigned Idx = Proto.find('i');
390 assert(Idx > 0 && "Can't return an immediate!");
391 return Idx - 1;
392 }
393
394 /// Return true if the intrinsic takes an splat operand.
395 bool hasSplat() const { return Proto.find('a') != std::string::npos; }
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000396
James Molloydee4ab02014-06-17 13:11:27 +0000397 /// Return the parameter index of the splat operand.
398 unsigned getSplatIdx() const {
399 assert(hasSplat());
400 unsigned Idx = Proto.find('a');
401 assert(Idx > 0 && "Can't return a splat!");
402 return Idx - 1;
403 }
404
405 unsigned getNumParams() const { return Proto.size() - 1; }
406 Type getReturnType() const { return Types[0]; }
407 Type getParamType(unsigned I) const { return Types[I + 1]; }
408 Type getBaseType() const { return BaseType; }
409 /// Return the raw prototype string.
410 std::string getProto() const { return Proto; }
411
412 /// Return true if the prototype has a scalar argument.
413 /// This does not return true for the "splat" code ('a').
David Blaikie4c96a5e2015-08-06 18:29:32 +0000414 bool protoHasScalar() const;
James Molloydee4ab02014-06-17 13:11:27 +0000415
416 /// Return the index that parameter PIndex will sit at
417 /// in a generated function call. This is often just PIndex,
418 /// but may not be as things such as multiple-vector operands
419 /// and sret parameters need to be taken into accont.
420 unsigned getGeneratedParamIdx(unsigned PIndex) {
421 unsigned Idx = 0;
422 if (getReturnType().getNumVectors() > 1)
423 // Multiple vectors are passed as sret.
424 ++Idx;
425
426 for (unsigned I = 0; I < PIndex; ++I)
427 Idx += std::max(1U, getParamType(I).getNumVectors());
428
429 return Idx;
430 }
431
Eugene Zelenko58ab22f2016-11-29 22:44:24 +0000432 bool hasBody() const { return Body && !Body->getValues().empty(); }
James Molloydee4ab02014-06-17 13:11:27 +0000433
434 void setNeededEarly() { NeededEarly = true; }
435
436 bool operator<(const Intrinsic &Other) const {
437 // Sort lexicographically on a two-tuple (Guard, Name)
438 if (Guard != Other.Guard)
439 return Guard < Other.Guard;
440 return Name < Other.Name;
441 }
442
443 ClassKind getClassKind(bool UseClassBIfScalar = false) {
444 if (UseClassBIfScalar && !protoHasScalar())
445 return ClassB;
446 return CK;
447 }
448
449 /// Return the name, mangled with type information.
450 /// If ForceClassS is true, use ClassS (u32/s32) instead
451 /// of the intrinsic's own type class.
David Blaikie4c96a5e2015-08-06 18:29:32 +0000452 std::string getMangledName(bool ForceClassS = false) const;
James Molloydee4ab02014-06-17 13:11:27 +0000453 /// Return the type code for a builtin function call.
David Blaikie4c96a5e2015-08-06 18:29:32 +0000454 std::string getInstTypeCode(Type T, ClassKind CK) const;
James Molloydee4ab02014-06-17 13:11:27 +0000455 /// Return the type string for a BUILTIN() macro in Builtins.def.
456 std::string getBuiltinTypeStr();
457
458 /// Generate the intrinsic, returning code.
459 std::string generate();
460 /// Perform type checking and populate the dependency graph, but
461 /// don't generate code yet.
462 void indexBody();
463
464private:
David Blaikie4c96a5e2015-08-06 18:29:32 +0000465 std::string mangleName(std::string Name, ClassKind CK) const;
James Molloydee4ab02014-06-17 13:11:27 +0000466
467 void initVariables();
468 std::string replaceParamsIn(std::string S);
469
470 void emitBodyAsBuiltinCall();
James Molloydee4ab02014-06-17 13:11:27 +0000471
James Molloyb452f782014-06-27 11:53:35 +0000472 void generateImpl(bool ReverseArguments,
473 StringRef NamePrefix, StringRef CallPrefix);
James Molloydee4ab02014-06-17 13:11:27 +0000474 void emitReturn();
James Molloyb452f782014-06-27 11:53:35 +0000475 void emitBody(StringRef CallPrefix);
James Molloydee4ab02014-06-17 13:11:27 +0000476 void emitShadowedArgs();
James Molloyb452f782014-06-27 11:53:35 +0000477 void emitArgumentReversal();
478 void emitReturnReversal();
479 void emitReverseVariable(Variable &Dest, Variable &Src);
James Molloydee4ab02014-06-17 13:11:27 +0000480 void emitNewLine();
481 void emitClosingBrace();
482 void emitOpeningBrace();
James Molloyb452f782014-06-27 11:53:35 +0000483 void emitPrototype(StringRef NamePrefix);
484
485 class DagEmitter {
486 Intrinsic &Intr;
487 StringRef CallPrefix;
488
489 public:
490 DagEmitter(Intrinsic &Intr, StringRef CallPrefix) :
491 Intr(Intr), CallPrefix(CallPrefix) {
492 }
493 std::pair<Type, std::string> emitDagArg(Init *Arg, std::string ArgName);
494 std::pair<Type, std::string> emitDagSaveTemp(DagInit *DI);
495 std::pair<Type, std::string> emitDagSplat(DagInit *DI);
496 std::pair<Type, std::string> emitDagDup(DagInit *DI);
497 std::pair<Type, std::string> emitDagShuffle(DagInit *DI);
498 std::pair<Type, std::string> emitDagCast(DagInit *DI, bool IsBitCast);
499 std::pair<Type, std::string> emitDagCall(DagInit *DI);
500 std::pair<Type, std::string> emitDagNameReplace(DagInit *DI);
501 std::pair<Type, std::string> emitDagLiteral(DagInit *DI);
502 std::pair<Type, std::string> emitDagOp(DagInit *DI);
503 std::pair<Type, std::string> emitDag(DagInit *DI);
504 };
James Molloydee4ab02014-06-17 13:11:27 +0000505};
506
507//===----------------------------------------------------------------------===//
508// NeonEmitter
509//===----------------------------------------------------------------------===//
510
511class NeonEmitter {
512 RecordKeeper &Records;
513 DenseMap<Record *, ClassKind> ClassMap;
David Blaikie4c96a5e2015-08-06 18:29:32 +0000514 std::map<std::string, std::deque<Intrinsic>> IntrinsicMap;
James Molloydee4ab02014-06-17 13:11:27 +0000515 unsigned UniqueNumber;
516
517 void createIntrinsic(Record *R, SmallVectorImpl<Intrinsic *> &Out);
518 void genBuiltinsDef(raw_ostream &OS, SmallVectorImpl<Intrinsic *> &Defs);
519 void genOverloadTypeCheckCode(raw_ostream &OS,
520 SmallVectorImpl<Intrinsic *> &Defs);
521 void genIntrinsicRangeCheckCode(raw_ostream &OS,
522 SmallVectorImpl<Intrinsic *> &Defs);
523
524public:
525 /// Called by Intrinsic - this attempts to get an intrinsic that takes
526 /// the given types as arguments.
David Blaikie4c96a5e2015-08-06 18:29:32 +0000527 Intrinsic &getIntrinsic(StringRef Name, ArrayRef<Type> Types);
James Molloydee4ab02014-06-17 13:11:27 +0000528
529 /// Called by Intrinsic - returns a globally-unique number.
530 unsigned getUniqueNumber() { return UniqueNumber++; }
531
532 NeonEmitter(RecordKeeper &R) : Records(R), UniqueNumber(0) {
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000533 Record *SI = R.getClass("SInst");
534 Record *II = R.getClass("IInst");
535 Record *WI = R.getClass("WInst");
Michael Gottesmanfc89cc22013-04-16 21:18:42 +0000536 Record *SOpI = R.getClass("SOpInst");
537 Record *IOpI = R.getClass("IOpInst");
538 Record *WOpI = R.getClass("WOpInst");
539 Record *LOpI = R.getClass("LOpInst");
540 Record *NoTestOpI = R.getClass("NoTestOpInst");
541
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000542 ClassMap[SI] = ClassS;
543 ClassMap[II] = ClassI;
544 ClassMap[WI] = ClassW;
Michael Gottesmanfc89cc22013-04-16 21:18:42 +0000545 ClassMap[SOpI] = ClassS;
546 ClassMap[IOpI] = ClassI;
547 ClassMap[WOpI] = ClassW;
548 ClassMap[LOpI] = ClassL;
549 ClassMap[NoTestOpI] = ClassNoTest;
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000550 }
551
552 // run - Emit arm_neon.h.inc
553 void run(raw_ostream &o);
554
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +0000555 // runFP16 - Emit arm_fp16.h.inc
556 void runFP16(raw_ostream &o);
557
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000558 // runHeader - Emit all the __builtin prototypes used in arm_neon.h
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +0000559 // and arm_fp16.h
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000560 void runHeader(raw_ostream &o);
561
562 // runTests - Emit tests for all the Neon intrinsics.
563 void runTests(raw_ostream &o);
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000564};
James Molloydee4ab02014-06-17 13:11:27 +0000565
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +0000566} // end anonymous namespace
567
James Molloydee4ab02014-06-17 13:11:27 +0000568//===----------------------------------------------------------------------===//
569// Type implementation
570//===----------------------------------------------------------------------===//
Peter Collingbournebee583f2011-10-06 13:03:08 +0000571
James Molloydee4ab02014-06-17 13:11:27 +0000572std::string Type::str() const {
573 if (Void)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000574 return "void";
James Molloydee4ab02014-06-17 13:11:27 +0000575 std::string S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000576
James Molloydee4ab02014-06-17 13:11:27 +0000577 if (!Signed && isInteger())
578 S += "u";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000579
James Molloydee4ab02014-06-17 13:11:27 +0000580 if (Poly)
581 S += "poly";
582 else if (Float)
583 S += "float";
584 else
585 S += "int";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000586
James Molloydee4ab02014-06-17 13:11:27 +0000587 S += utostr(ElementBitwidth);
588 if (isVector())
589 S += "x" + utostr(getNumElements());
590 if (NumVectors > 1)
591 S += "x" + utostr(NumVectors);
592 S += "_t";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000593
James Molloydee4ab02014-06-17 13:11:27 +0000594 if (Constant)
595 S += " const";
596 if (Pointer)
597 S += " *";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000598
James Molloydee4ab02014-06-17 13:11:27 +0000599 return S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000600}
601
James Molloydee4ab02014-06-17 13:11:27 +0000602std::string Type::builtin_str() const {
603 std::string S;
604 if (isVoid())
605 return "v";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000606
James Molloydee4ab02014-06-17 13:11:27 +0000607 if (Pointer)
608 // All pointers are void pointers.
609 S += "v";
610 else if (isInteger())
611 switch (ElementBitwidth) {
612 case 8: S += "c"; break;
613 case 16: S += "s"; break;
614 case 32: S += "i"; break;
615 case 64: S += "Wi"; break;
616 case 128: S += "LLLi"; break;
Craig Topper0039f3f2014-06-18 03:57:25 +0000617 default: llvm_unreachable("Unhandled case!");
James Molloydee4ab02014-06-17 13:11:27 +0000618 }
619 else
620 switch (ElementBitwidth) {
621 case 16: S += "h"; break;
622 case 32: S += "f"; break;
623 case 64: S += "d"; break;
Craig Topper0039f3f2014-06-18 03:57:25 +0000624 default: llvm_unreachable("Unhandled case!");
James Molloydee4ab02014-06-17 13:11:27 +0000625 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000626
James Molloydee4ab02014-06-17 13:11:27 +0000627 if (isChar() && !Pointer)
628 // Make chars explicitly signed.
629 S = "S" + S;
630 else if (isInteger() && !Pointer && !Signed)
631 S = "U" + S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000632
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000633 // Constant indices are "int", but have the "constant expression" modifier.
634 if (isImmediate()) {
635 assert(isInteger() && isSigned());
636 S = "I" + S;
637 }
638
James Molloydee4ab02014-06-17 13:11:27 +0000639 if (isScalar()) {
640 if (Constant) S += "C";
641 if (Pointer) S += "*";
642 return S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000643 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000644
James Molloydee4ab02014-06-17 13:11:27 +0000645 std::string Ret;
646 for (unsigned I = 0; I < NumVectors; ++I)
647 Ret += "V" + utostr(getNumElements()) + S;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000648
James Molloydee4ab02014-06-17 13:11:27 +0000649 return Ret;
650}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000651
James Molloydee4ab02014-06-17 13:11:27 +0000652unsigned Type::getNeonEnum() const {
653 unsigned Addend;
654 switch (ElementBitwidth) {
655 case 8: Addend = 0; break;
656 case 16: Addend = 1; break;
657 case 32: Addend = 2; break;
658 case 64: Addend = 3; break;
659 case 128: Addend = 4; break;
Craig Topperc7193c42014-06-18 03:13:41 +0000660 default: llvm_unreachable("Unhandled element bitwidth!");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000661 }
662
James Molloydee4ab02014-06-17 13:11:27 +0000663 unsigned Base = (unsigned)NeonTypeFlags::Int8 + Addend;
664 if (Poly) {
665 // Adjustment needed because Poly32 doesn't exist.
666 if (Addend >= 2)
667 --Addend;
668 Base = (unsigned)NeonTypeFlags::Poly8 + Addend;
669 }
670 if (Float) {
671 assert(Addend != 0 && "Float8 doesn't exist!");
672 Base = (unsigned)NeonTypeFlags::Float16 + (Addend - 1);
673 }
674
675 if (Bitwidth == 128)
676 Base |= (unsigned)NeonTypeFlags::QuadFlag;
677 if (isInteger() && !Signed)
678 Base |= (unsigned)NeonTypeFlags::UnsignedFlag;
679
680 return Base;
681}
682
683Type Type::fromTypedefName(StringRef Name) {
684 Type T;
685 T.Void = false;
686 T.Float = false;
687 T.Poly = false;
688
689 if (Name.front() == 'u') {
690 T.Signed = false;
691 Name = Name.drop_front();
692 } else {
693 T.Signed = true;
694 }
695
696 if (Name.startswith("float")) {
697 T.Float = true;
698 Name = Name.drop_front(5);
699 } else if (Name.startswith("poly")) {
700 T.Poly = true;
701 Name = Name.drop_front(4);
702 } else {
703 assert(Name.startswith("int"));
704 Name = Name.drop_front(3);
705 }
706
707 unsigned I = 0;
708 for (I = 0; I < Name.size(); ++I) {
709 if (!isdigit(Name[I]))
710 break;
711 }
712 Name.substr(0, I).getAsInteger(10, T.ElementBitwidth);
713 Name = Name.drop_front(I);
714
715 T.Bitwidth = T.ElementBitwidth;
716 T.NumVectors = 1;
717
718 if (Name.front() == 'x') {
719 Name = Name.drop_front();
720 unsigned I = 0;
721 for (I = 0; I < Name.size(); ++I) {
722 if (!isdigit(Name[I]))
723 break;
724 }
725 unsigned NumLanes;
726 Name.substr(0, I).getAsInteger(10, NumLanes);
727 Name = Name.drop_front(I);
728 T.Bitwidth = T.ElementBitwidth * NumLanes;
729 } else {
730 // Was scalar.
731 T.NumVectors = 0;
732 }
733 if (Name.front() == 'x') {
734 Name = Name.drop_front();
735 unsigned I = 0;
736 for (I = 0; I < Name.size(); ++I) {
737 if (!isdigit(Name[I]))
738 break;
739 }
740 Name.substr(0, I).getAsInteger(10, T.NumVectors);
741 Name = Name.drop_front(I);
742 }
743
744 assert(Name.startswith("_t") && "Malformed typedef!");
745 return T;
746}
747
748void Type::applyTypespec(bool &Quad) {
749 std::string S = TS;
750 ScalarForMangling = false;
751 Void = false;
752 Poly = Float = false;
753 ElementBitwidth = ~0U;
754 Signed = true;
755 NumVectors = 1;
756
757 for (char I : S) {
758 switch (I) {
759 case 'S':
760 ScalarForMangling = true;
761 break;
762 case 'H':
763 NoManglingQ = true;
764 Quad = true;
765 break;
766 case 'Q':
767 Quad = true;
768 break;
769 case 'P':
770 Poly = true;
771 break;
772 case 'U':
773 Signed = false;
774 break;
775 case 'c':
776 ElementBitwidth = 8;
777 break;
778 case 'h':
779 Float = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000780 LLVM_FALLTHROUGH;
James Molloydee4ab02014-06-17 13:11:27 +0000781 case 's':
782 ElementBitwidth = 16;
783 break;
784 case 'f':
785 Float = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000786 LLVM_FALLTHROUGH;
James Molloydee4ab02014-06-17 13:11:27 +0000787 case 'i':
788 ElementBitwidth = 32;
789 break;
790 case 'd':
791 Float = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000792 LLVM_FALLTHROUGH;
James Molloydee4ab02014-06-17 13:11:27 +0000793 case 'l':
794 ElementBitwidth = 64;
795 break;
796 case 'k':
797 ElementBitwidth = 128;
798 // Poly doesn't have a 128x1 type.
799 if (Poly)
800 NumVectors = 0;
801 break;
802 default:
Craig Topper0039f3f2014-06-18 03:57:25 +0000803 llvm_unreachable("Unhandled type code!");
James Molloydee4ab02014-06-17 13:11:27 +0000804 }
805 }
806 assert(ElementBitwidth != ~0U && "Bad element bitwidth!");
807
808 Bitwidth = Quad ? 128 : 64;
809}
810
811void Type::applyModifier(char Mod) {
812 bool AppliedQuad = false;
813 applyTypespec(AppliedQuad);
814
815 switch (Mod) {
816 case 'v':
817 Void = true;
818 break;
819 case 't':
820 if (Poly) {
821 Poly = false;
822 Signed = false;
823 }
824 break;
825 case 'b':
826 Signed = false;
827 Float = false;
828 Poly = false;
829 NumVectors = 0;
830 Bitwidth = ElementBitwidth;
831 break;
832 case '$':
833 Signed = true;
834 Float = false;
835 Poly = false;
836 NumVectors = 0;
837 Bitwidth = ElementBitwidth;
838 break;
839 case 'u':
840 Signed = false;
841 Poly = false;
842 Float = false;
843 break;
844 case 'x':
845 Signed = true;
846 assert(!Poly && "'u' can't be used with poly types!");
847 Float = false;
848 break;
849 case 'o':
850 Bitwidth = ElementBitwidth = 64;
851 NumVectors = 0;
852 Float = true;
853 break;
854 case 'y':
855 Bitwidth = ElementBitwidth = 32;
856 NumVectors = 0;
857 Float = true;
858 break;
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +0000859 case 'Y':
860 Bitwidth = ElementBitwidth = 16;
861 NumVectors = 0;
862 Float = true;
863 break;
864 case 'I':
865 Bitwidth = ElementBitwidth = 32;
866 NumVectors = 0;
867 Float = false;
868 Signed = true;
869 break;
870 case 'L':
871 Bitwidth = ElementBitwidth = 64;
872 NumVectors = 0;
873 Float = false;
874 Signed = true;
875 break;
876 case 'U':
877 Bitwidth = ElementBitwidth = 32;
878 NumVectors = 0;
879 Float = false;
880 Signed = false;
881 break;
882 case 'O':
883 Bitwidth = ElementBitwidth = 64;
884 NumVectors = 0;
885 Float = false;
886 Signed = false;
887 break;
James Molloydee4ab02014-06-17 13:11:27 +0000888 case 'f':
James Molloydee4ab02014-06-17 13:11:27 +0000889 Float = true;
890 ElementBitwidth = 32;
891 break;
892 case 'F':
893 Float = true;
894 ElementBitwidth = 64;
895 break;
Abderrazek Zaafranif58a1322017-12-21 19:20:01 +0000896 case 'H':
897 Float = true;
898 ElementBitwidth = 16;
899 break;
James Molloydee4ab02014-06-17 13:11:27 +0000900 case 'g':
901 if (AppliedQuad)
902 Bitwidth /= 2;
903 break;
904 case 'j':
905 if (!AppliedQuad)
906 Bitwidth *= 2;
907 break;
908 case 'w':
909 ElementBitwidth *= 2;
910 Bitwidth *= 2;
911 break;
912 case 'n':
913 ElementBitwidth *= 2;
914 break;
915 case 'i':
916 Float = false;
917 Poly = false;
918 ElementBitwidth = Bitwidth = 32;
919 NumVectors = 0;
920 Signed = true;
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000921 Immediate = true;
James Molloydee4ab02014-06-17 13:11:27 +0000922 break;
923 case 'l':
924 Float = false;
925 Poly = false;
926 ElementBitwidth = Bitwidth = 64;
927 NumVectors = 0;
928 Signed = false;
Ahmed Bougacha94df7302015-06-04 01:43:41 +0000929 Immediate = true;
James Molloydee4ab02014-06-17 13:11:27 +0000930 break;
931 case 'z':
932 ElementBitwidth /= 2;
933 Bitwidth = ElementBitwidth;
934 NumVectors = 0;
935 break;
936 case 'r':
937 ElementBitwidth *= 2;
938 Bitwidth = ElementBitwidth;
939 NumVectors = 0;
940 break;
941 case 's':
942 case 'a':
943 Bitwidth = ElementBitwidth;
944 NumVectors = 0;
945 break;
946 case 'k':
947 Bitwidth *= 2;
948 break;
949 case 'c':
950 Constant = true;
Adrian Prantl6691e112018-02-01 18:10:20 +0000951 LLVM_FALLTHROUGH;
James Molloydee4ab02014-06-17 13:11:27 +0000952 case 'p':
953 Pointer = true;
954 Bitwidth = ElementBitwidth;
955 NumVectors = 0;
956 break;
957 case 'h':
958 ElementBitwidth /= 2;
959 break;
960 case 'q':
961 ElementBitwidth /= 2;
962 Bitwidth *= 2;
963 break;
964 case 'e':
965 ElementBitwidth /= 2;
966 Signed = false;
967 break;
968 case 'm':
969 ElementBitwidth /= 2;
970 Bitwidth /= 2;
971 break;
972 case 'd':
973 break;
974 case '2':
975 NumVectors = 2;
976 break;
977 case '3':
978 NumVectors = 3;
979 break;
980 case '4':
981 NumVectors = 4;
982 break;
983 case 'B':
984 NumVectors = 2;
985 if (!AppliedQuad)
986 Bitwidth *= 2;
987 break;
988 case 'C':
989 NumVectors = 3;
990 if (!AppliedQuad)
991 Bitwidth *= 2;
992 break;
993 case 'D':
994 NumVectors = 4;
995 if (!AppliedQuad)
996 Bitwidth *= 2;
997 break;
998 default:
Craig Topper0039f3f2014-06-18 03:57:25 +0000999 llvm_unreachable("Unhandled character!");
James Molloydee4ab02014-06-17 13:11:27 +00001000 }
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// Intrinsic implementation
1005//===----------------------------------------------------------------------===//
1006
David Blaikie4c96a5e2015-08-06 18:29:32 +00001007std::string Intrinsic::getInstTypeCode(Type T, ClassKind CK) const {
James Molloydee4ab02014-06-17 13:11:27 +00001008 char typeCode = '\0';
1009 bool printNumber = true;
1010
1011 if (CK == ClassB)
1012 return "";
1013
1014 if (T.isPoly())
1015 typeCode = 'p';
1016 else if (T.isInteger())
1017 typeCode = T.isSigned() ? 's' : 'u';
1018 else
1019 typeCode = 'f';
1020
1021 if (CK == ClassI) {
1022 switch (typeCode) {
1023 default:
1024 break;
1025 case 's':
1026 case 'u':
1027 case 'p':
1028 typeCode = 'i';
1029 break;
1030 }
1031 }
1032 if (CK == ClassB) {
1033 typeCode = '\0';
1034 }
1035
1036 std::string S;
1037 if (typeCode != '\0')
1038 S.push_back(typeCode);
1039 if (printNumber)
1040 S += utostr(T.getElementSizeInBits());
1041
1042 return S;
1043}
1044
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001045static bool isFloatingPointProtoModifier(char Mod) {
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001046 return Mod == 'F' || Mod == 'f' || Mod == 'H' || Mod == 'Y' || Mod == 'I';
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001047}
1048
James Molloydee4ab02014-06-17 13:11:27 +00001049std::string Intrinsic::getBuiltinTypeStr() {
1050 ClassKind LocalCK = getClassKind(true);
1051 std::string S;
1052
1053 Type RetT = getReturnType();
1054 if ((LocalCK == ClassI || LocalCK == ClassW) && RetT.isScalar() &&
1055 !RetT.isFloating())
1056 RetT.makeInteger(RetT.getElementSizeInBits(), false);
1057
Peter Collingbournebee583f2011-10-06 13:03:08 +00001058 // Since the return value must be one type, return a vector type of the
1059 // appropriate width which we will bitcast. An exception is made for
1060 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
1061 // fashion, storing them to a pointer arg.
James Molloydee4ab02014-06-17 13:11:27 +00001062 if (RetT.getNumVectors() > 1) {
1063 S += "vv*"; // void result with void* first argument
1064 } else {
1065 if (RetT.isPoly())
1066 RetT.makeInteger(RetT.getElementSizeInBits(), false);
1067 if (!RetT.isScalar() && !RetT.isSigned())
1068 RetT.makeSigned();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001069
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001070 bool ForcedVectorFloatingType = isFloatingPointProtoModifier(Proto[0]);
James Molloydee4ab02014-06-17 13:11:27 +00001071 if (LocalCK == ClassB && !RetT.isScalar() && !ForcedVectorFloatingType)
1072 // Cast to vector of 8-bit elements.
1073 RetT.makeInteger(8, true);
1074
1075 S += RetT.builtin_str();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001076 }
1077
James Molloydee4ab02014-06-17 13:11:27 +00001078 for (unsigned I = 0; I < getNumParams(); ++I) {
1079 Type T = getParamType(I);
1080 if (T.isPoly())
1081 T.makeInteger(T.getElementSizeInBits(), false);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001082
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001083 bool ForcedFloatingType = isFloatingPointProtoModifier(Proto[I + 1]);
James Molloydee4ab02014-06-17 13:11:27 +00001084 if (LocalCK == ClassB && !T.isScalar() && !ForcedFloatingType)
1085 T.makeInteger(8, true);
1086 // Halves always get converted to 8-bit elements.
1087 if (T.isHalf() && T.isVector() && !T.isScalarForMangling())
1088 T.makeInteger(8, true);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001089
James Molloydee4ab02014-06-17 13:11:27 +00001090 if (LocalCK == ClassI)
1091 T.makeSigned();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001092
James Molloydee4ab02014-06-17 13:11:27 +00001093 if (hasImmediate() && getImmediateIdx() == I)
Ahmed Bougacha94df7302015-06-04 01:43:41 +00001094 T.makeImmediate(32);
Michael Gottesman095c58f2013-04-16 22:07:30 +00001095
James Molloydee4ab02014-06-17 13:11:27 +00001096 S += T.builtin_str();
Michael Gottesman095c58f2013-04-16 22:07:30 +00001097 }
James Molloydee4ab02014-06-17 13:11:27 +00001098
1099 // Extra constant integer to hold type class enum for this function, e.g. s8
1100 if (LocalCK == ClassB)
1101 S += "i";
1102
1103 return S;
Michael Gottesman095c58f2013-04-16 22:07:30 +00001104}
1105
David Blaikie4c96a5e2015-08-06 18:29:32 +00001106std::string Intrinsic::getMangledName(bool ForceClassS) const {
James Molloydee4ab02014-06-17 13:11:27 +00001107 // Check if the prototype has a scalar operand with the type of the vector
1108 // elements. If not, bitcasting the args will take care of arg checking.
1109 // The actual signedness etc. will be taken care of with special enums.
1110 ClassKind LocalCK = CK;
1111 if (!protoHasScalar())
1112 LocalCK = ClassB;
1113
1114 return mangleName(Name, ForceClassS ? ClassS : LocalCK);
Kevin Qinc076d062013-08-29 07:55:15 +00001115}
1116
David Blaikie4c96a5e2015-08-06 18:29:32 +00001117std::string Intrinsic::mangleName(std::string Name, ClassKind LocalCK) const {
James Molloydee4ab02014-06-17 13:11:27 +00001118 std::string typeCode = getInstTypeCode(BaseType, LocalCK);
1119 std::string S = Name;
Hao Liu5e4ce1a2013-11-18 06:33:43 +00001120
Ahmed Bougachacd5b8a02015-08-21 23:34:20 +00001121 if (Name == "vcvt_f16_f32" || Name == "vcvt_f32_f16" ||
1122 Name == "vcvt_f32_f64" || Name == "vcvt_f64_f32")
James Molloydee4ab02014-06-17 13:11:27 +00001123 return Name;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001124
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001125 if (!typeCode.empty()) {
James Molloydee4ab02014-06-17 13:11:27 +00001126 // If the name ends with _xN (N = 2,3,4), insert the typeCode before _xN.
1127 if (Name.size() >= 3 && isdigit(Name.back()) &&
1128 Name[Name.length() - 2] == 'x' && Name[Name.length() - 3] == '_')
1129 S.insert(S.length() - 3, "_" + typeCode);
Hao Liu5e4ce1a2013-11-18 06:33:43 +00001130 else
James Molloydee4ab02014-06-17 13:11:27 +00001131 S += "_" + typeCode;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001132 }
Michael Gottesman095c58f2013-04-16 22:07:30 +00001133
James Molloydee4ab02014-06-17 13:11:27 +00001134 if (BaseType != InBaseType) {
1135 // A reinterpret - out the input base type at the end.
1136 S += "_" + getInstTypeCode(InBaseType, LocalCK);
1137 }
1138
1139 if (LocalCK == ClassB)
1140 S += "_v";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001141
1142 // Insert a 'q' before the first '_' character so that it ends up before
1143 // _lane or _n on vector-scalar operations.
James Molloydee4ab02014-06-17 13:11:27 +00001144 if (BaseType.getSizeInBits() == 128 && !BaseType.noManglingQ()) {
1145 size_t Pos = S.find('_');
1146 S.insert(Pos, "q");
Kevin Qinc076d062013-08-29 07:55:15 +00001147 }
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001148
James Molloydee4ab02014-06-17 13:11:27 +00001149 char Suffix = '\0';
1150 if (BaseType.isScalarForMangling()) {
1151 switch (BaseType.getElementSizeInBits()) {
1152 case 8: Suffix = 'b'; break;
1153 case 16: Suffix = 'h'; break;
1154 case 32: Suffix = 's'; break;
1155 case 64: Suffix = 'd'; break;
Craig Topper0039f3f2014-06-18 03:57:25 +00001156 default: llvm_unreachable("Bad suffix!");
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001157 }
1158 }
James Molloydee4ab02014-06-17 13:11:27 +00001159 if (Suffix != '\0') {
1160 size_t Pos = S.find('_');
1161 S.insert(Pos, &Suffix, 1);
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001162 }
James Molloydee4ab02014-06-17 13:11:27 +00001163
1164 return S;
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001165}
1166
James Molloydee4ab02014-06-17 13:11:27 +00001167std::string Intrinsic::replaceParamsIn(std::string S) {
1168 while (S.find('$') != std::string::npos) {
1169 size_t Pos = S.find('$');
1170 size_t End = Pos + 1;
1171 while (isalpha(S[End]))
1172 ++End;
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001173
James Molloydee4ab02014-06-17 13:11:27 +00001174 std::string VarName = S.substr(Pos + 1, End - Pos - 1);
1175 assert_with_loc(Variables.find(VarName) != Variables.end(),
1176 "Variable not defined!");
1177 S.replace(Pos, End - Pos, Variables.find(VarName)->second.getName());
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001178 }
1179
James Molloydee4ab02014-06-17 13:11:27 +00001180 return S;
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001181}
1182
James Molloydee4ab02014-06-17 13:11:27 +00001183void Intrinsic::initVariables() {
1184 Variables.clear();
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001185
James Molloydee4ab02014-06-17 13:11:27 +00001186 // Modify the TypeSpec per-argument to get a concrete Type, and create
1187 // known variables for each.
1188 for (unsigned I = 1; I < Proto.size(); ++I) {
1189 char NameC = '0' + (I - 1);
1190 std::string Name = "p";
1191 Name.push_back(NameC);
1192
1193 Variables[Name] = Variable(Types[I], Name + VariablePostfix);
1194 }
1195 RetVar = Variable(Types[0], "ret" + VariablePostfix);
1196}
1197
James Molloyb452f782014-06-27 11:53:35 +00001198void Intrinsic::emitPrototype(StringRef NamePrefix) {
James Molloydee4ab02014-06-17 13:11:27 +00001199 if (UseMacro)
1200 OS << "#define ";
1201 else
1202 OS << "__ai " << Types[0].str() << " ";
1203
James Molloyb452f782014-06-27 11:53:35 +00001204 OS << NamePrefix.str() << mangleName(Name, ClassS) << "(";
James Molloydee4ab02014-06-17 13:11:27 +00001205
1206 for (unsigned I = 0; I < getNumParams(); ++I) {
1207 if (I != 0)
1208 OS << ", ";
1209
1210 char NameC = '0' + I;
1211 std::string Name = "p";
1212 Name.push_back(NameC);
1213 assert(Variables.find(Name) != Variables.end());
1214 Variable &V = Variables[Name];
1215
1216 if (!UseMacro)
1217 OS << V.getType().str() << " ";
1218 OS << V.getName();
1219 }
1220
1221 OS << ")";
1222}
1223
1224void Intrinsic::emitOpeningBrace() {
1225 if (UseMacro)
1226 OS << " __extension__ ({";
1227 else
1228 OS << " {";
1229 emitNewLine();
1230}
1231
1232void Intrinsic::emitClosingBrace() {
1233 if (UseMacro)
1234 OS << "})";
1235 else
1236 OS << "}";
1237}
1238
1239void Intrinsic::emitNewLine() {
1240 if (UseMacro)
1241 OS << " \\\n";
1242 else
1243 OS << "\n";
1244}
1245
James Molloyb452f782014-06-27 11:53:35 +00001246void Intrinsic::emitReverseVariable(Variable &Dest, Variable &Src) {
1247 if (Dest.getType().getNumVectors() > 1) {
1248 emitNewLine();
1249
1250 for (unsigned K = 0; K < Dest.getType().getNumVectors(); ++K) {
Craig Topper054b3912016-01-31 00:20:26 +00001251 OS << " " << Dest.getName() << ".val[" << K << "] = "
James Molloyb452f782014-06-27 11:53:35 +00001252 << "__builtin_shufflevector("
Craig Topper054b3912016-01-31 00:20:26 +00001253 << Src.getName() << ".val[" << K << "], "
1254 << Src.getName() << ".val[" << K << "]";
James Molloyb452f782014-06-27 11:53:35 +00001255 for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
Craig Topper054b3912016-01-31 00:20:26 +00001256 OS << ", " << J;
James Molloyb452f782014-06-27 11:53:35 +00001257 OS << ");";
1258 emitNewLine();
1259 }
1260 } else {
1261 OS << " " << Dest.getName()
1262 << " = __builtin_shufflevector(" << Src.getName() << ", " << Src.getName();
1263 for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
Craig Topper054b3912016-01-31 00:20:26 +00001264 OS << ", " << J;
James Molloyb452f782014-06-27 11:53:35 +00001265 OS << ");";
1266 emitNewLine();
1267 }
1268}
1269
1270void Intrinsic::emitArgumentReversal() {
1271 if (BigEndianSafe)
1272 return;
1273
1274 // Reverse all vector arguments.
1275 for (unsigned I = 0; I < getNumParams(); ++I) {
1276 std::string Name = "p" + utostr(I);
1277 std::string NewName = "rev" + utostr(I);
1278
1279 Variable &V = Variables[Name];
1280 Variable NewV(V.getType(), NewName + VariablePostfix);
1281
1282 if (!NewV.getType().isVector() || NewV.getType().getNumElements() == 1)
1283 continue;
1284
1285 OS << " " << NewV.getType().str() << " " << NewV.getName() << ";";
1286 emitReverseVariable(NewV, V);
1287 V = NewV;
1288 }
1289}
1290
1291void Intrinsic::emitReturnReversal() {
1292 if (BigEndianSafe)
1293 return;
1294 if (!getReturnType().isVector() || getReturnType().isVoid() ||
1295 getReturnType().getNumElements() == 1)
1296 return;
1297 emitReverseVariable(RetVar, RetVar);
1298}
1299
James Molloydee4ab02014-06-17 13:11:27 +00001300void Intrinsic::emitShadowedArgs() {
1301 // Macro arguments are not type-checked like inline function arguments,
1302 // so assign them to local temporaries to get the right type checking.
1303 if (!UseMacro)
Michael Gottesman6cd3e562013-04-16 23:00:26 +00001304 return;
1305
James Molloydee4ab02014-06-17 13:11:27 +00001306 for (unsigned I = 0; I < getNumParams(); ++I) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001307 // Do not create a temporary for an immediate argument.
1308 // That would defeat the whole point of using a macro!
James Molloydee4ab02014-06-17 13:11:27 +00001309 if (hasImmediate() && Proto[I+1] == 'i')
Peter Collingbournebee583f2011-10-06 13:03:08 +00001310 continue;
James Molloydee4ab02014-06-17 13:11:27 +00001311 // Do not create a temporary for pointer arguments. The input
1312 // pointer may have an alignment hint.
1313 if (getParamType(I).isPointer())
1314 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001315
James Molloyb452f782014-06-27 11:53:35 +00001316 std::string Name = "p" + utostr(I);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001317
James Molloydee4ab02014-06-17 13:11:27 +00001318 assert(Variables.find(Name) != Variables.end());
1319 Variable &V = Variables[Name];
Peter Collingbournebee583f2011-10-06 13:03:08 +00001320
James Molloydee4ab02014-06-17 13:11:27 +00001321 std::string NewName = "s" + utostr(I);
1322 Variable V2(V.getType(), NewName + VariablePostfix);
Jiangning Liu1bda93a2013-09-09 02:21:08 +00001323
James Molloydee4ab02014-06-17 13:11:27 +00001324 OS << " " << V2.getType().str() << " " << V2.getName() << " = "
1325 << V.getName() << ";";
1326 emitNewLine();
Jiangning Liu1bda93a2013-09-09 02:21:08 +00001327
James Molloydee4ab02014-06-17 13:11:27 +00001328 V = V2;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001329 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001330}
1331
Jiangning Liuee3e0872013-11-27 14:02:55 +00001332// We don't check 'a' in this function, because for builtin function the
1333// argument matching to 'a' uses a vector type splatted from a scalar type.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001334bool Intrinsic::protoHasScalar() const {
James Molloydee4ab02014-06-17 13:11:27 +00001335 return (Proto.find('s') != std::string::npos ||
1336 Proto.find('z') != std::string::npos ||
1337 Proto.find('r') != std::string::npos ||
1338 Proto.find('b') != std::string::npos ||
1339 Proto.find('$') != std::string::npos ||
1340 Proto.find('y') != std::string::npos ||
1341 Proto.find('o') != std::string::npos);
Jiangning Liub96ebac2013-10-05 08:22:55 +00001342}
1343
James Molloydee4ab02014-06-17 13:11:27 +00001344void Intrinsic::emitBodyAsBuiltinCall() {
1345 std::string S;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001346
1347 // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
1348 // sret-like argument.
James Molloydee4ab02014-06-17 13:11:27 +00001349 bool SRet = getReturnType().getNumVectors() >= 2;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001350
James Molloydee4ab02014-06-17 13:11:27 +00001351 StringRef N = Name;
1352 if (hasSplat()) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001353 // Call the non-splat builtin: chop off the "_n" suffix from the name.
James Molloydee4ab02014-06-17 13:11:27 +00001354 assert(N.endswith("_n"));
1355 N = N.drop_back(2);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001356 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001357
James Molloydee4ab02014-06-17 13:11:27 +00001358 ClassKind LocalCK = CK;
1359 if (!protoHasScalar())
1360 LocalCK = ClassB;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001361
James Molloydee4ab02014-06-17 13:11:27 +00001362 if (!getReturnType().isVoid() && !SRet)
1363 S += "(" + RetVar.getType().str() + ") ";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001364
James Molloydee4ab02014-06-17 13:11:27 +00001365 S += "__builtin_neon_" + mangleName(N, LocalCK) + "(";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001366
James Molloydee4ab02014-06-17 13:11:27 +00001367 if (SRet)
1368 S += "&" + RetVar.getName() + ", ";
1369
1370 for (unsigned I = 0; I < getNumParams(); ++I) {
1371 Variable &V = Variables["p" + utostr(I)];
1372 Type T = V.getType();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001373
1374 // Handle multiple-vector values specially, emitting each subvector as an
James Molloydee4ab02014-06-17 13:11:27 +00001375 // argument to the builtin.
1376 if (T.getNumVectors() > 1) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001377 // Check if an explicit cast is needed.
James Molloydee4ab02014-06-17 13:11:27 +00001378 std::string Cast;
1379 if (T.isChar() || T.isPoly() || !T.isSigned()) {
1380 Type T2 = T;
1381 T2.makeOneVector();
1382 T2.makeInteger(8, /*Signed=*/true);
1383 Cast = "(" + T2.str() + ")";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001384 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001385
James Molloydee4ab02014-06-17 13:11:27 +00001386 for (unsigned J = 0; J < T.getNumVectors(); ++J)
1387 S += Cast + V.getName() + ".val[" + utostr(J) + "], ";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001388 continue;
1389 }
1390
James Molloydee4ab02014-06-17 13:11:27 +00001391 std::string Arg;
1392 Type CastToType = T;
1393 if (hasSplat() && I == getSplatIdx()) {
1394 Arg = "(" + BaseType.str() + ") {";
1395 for (unsigned J = 0; J < BaseType.getNumElements(); ++J) {
1396 if (J != 0)
1397 Arg += ", ";
1398 Arg += V.getName();
1399 }
1400 Arg += "}";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001401
James Molloydee4ab02014-06-17 13:11:27 +00001402 CastToType = BaseType;
1403 } else {
1404 Arg = V.getName();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001405 }
1406
James Molloydee4ab02014-06-17 13:11:27 +00001407 // Check if an explicit cast is needed.
1408 if (CastToType.isVector()) {
1409 CastToType.makeInteger(8, true);
1410 Arg = "(" + CastToType.str() + ")" + Arg;
1411 }
1412
1413 S += Arg + ", ";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001414 }
1415
1416 // Extra constant integer to hold type class enum for this function, e.g. s8
James Molloydee4ab02014-06-17 13:11:27 +00001417 if (getClassKind(true) == ClassB) {
1418 Type ThisTy = getReturnType();
Ahmed Bougacha22a16962015-08-21 23:24:18 +00001419 if (Proto[0] == 'v' || isFloatingPointProtoModifier(Proto[0]))
James Molloydee4ab02014-06-17 13:11:27 +00001420 ThisTy = getParamType(0);
1421 if (ThisTy.isPointer())
1422 ThisTy = getParamType(1);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001423
James Molloydee4ab02014-06-17 13:11:27 +00001424 S += utostr(ThisTy.getNeonEnum());
1425 } else {
1426 // Remove extraneous ", ".
1427 S.pop_back();
1428 S.pop_back();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001429 }
James Molloydee4ab02014-06-17 13:11:27 +00001430 S += ");";
1431
1432 std::string RetExpr;
1433 if (!SRet && !RetVar.getType().isVoid())
1434 RetExpr = RetVar.getName() + " = ";
1435
1436 OS << " " << RetExpr << S;
1437 emitNewLine();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001438}
1439
James Molloyb452f782014-06-27 11:53:35 +00001440void Intrinsic::emitBody(StringRef CallPrefix) {
James Molloydee4ab02014-06-17 13:11:27 +00001441 std::vector<std::string> Lines;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001442
James Molloydee4ab02014-06-17 13:11:27 +00001443 assert(RetVar.getType() == Types[0]);
1444 // Create a return variable, if we're not void.
1445 if (!RetVar.getType().isVoid()) {
1446 OS << " " << RetVar.getType().str() << " " << RetVar.getName() << ";";
1447 emitNewLine();
1448 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001449
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001450 if (!Body || Body->getValues().empty()) {
James Molloydee4ab02014-06-17 13:11:27 +00001451 // Nothing specific to output - must output a builtin.
1452 emitBodyAsBuiltinCall();
1453 return;
1454 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001455
James Molloydee4ab02014-06-17 13:11:27 +00001456 // We have a list of "things to output". The last should be returned.
1457 for (auto *I : Body->getValues()) {
1458 if (StringInit *SI = dyn_cast<StringInit>(I)) {
1459 Lines.push_back(replaceParamsIn(SI->getAsString()));
1460 } else if (DagInit *DI = dyn_cast<DagInit>(I)) {
James Molloyb452f782014-06-27 11:53:35 +00001461 DagEmitter DE(*this, CallPrefix);
1462 Lines.push_back(DE.emitDag(DI).second + ";");
James Molloydee4ab02014-06-17 13:11:27 +00001463 }
1464 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001465
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00001466 assert(!Lines.empty() && "Empty def?");
James Molloydee4ab02014-06-17 13:11:27 +00001467 if (!RetVar.getType().isVoid())
1468 Lines.back().insert(0, RetVar.getName() + " = ");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001469
James Molloydee4ab02014-06-17 13:11:27 +00001470 for (auto &L : Lines) {
1471 OS << " " << L;
1472 emitNewLine();
1473 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001474}
1475
James Molloydee4ab02014-06-17 13:11:27 +00001476void Intrinsic::emitReturn() {
1477 if (RetVar.getType().isVoid())
1478 return;
1479 if (UseMacro)
1480 OS << " " << RetVar.getName() << ";";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001481 else
James Molloydee4ab02014-06-17 13:11:27 +00001482 OS << " return " << RetVar.getName() << ";";
1483 emitNewLine();
1484}
Peter Collingbournebee583f2011-10-06 13:03:08 +00001485
James Molloyb452f782014-06-27 11:53:35 +00001486std::pair<Type, std::string> Intrinsic::DagEmitter::emitDag(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001487 // At this point we should only be seeing a def.
1488 DefInit *DefI = cast<DefInit>(DI->getOperator());
1489 std::string Op = DefI->getAsString();
1490
1491 if (Op == "cast" || Op == "bitcast")
1492 return emitDagCast(DI, Op == "bitcast");
1493 if (Op == "shuffle")
1494 return emitDagShuffle(DI);
1495 if (Op == "dup")
1496 return emitDagDup(DI);
1497 if (Op == "splat")
1498 return emitDagSplat(DI);
1499 if (Op == "save_temp")
1500 return emitDagSaveTemp(DI);
1501 if (Op == "op")
1502 return emitDagOp(DI);
1503 if (Op == "call")
1504 return emitDagCall(DI);
1505 if (Op == "name_replace")
1506 return emitDagNameReplace(DI);
1507 if (Op == "literal")
1508 return emitDagLiteral(DI);
1509 assert_with_loc(false, "Unknown operation!");
1510 return std::make_pair(Type::getVoid(), "");
1511}
1512
James Molloyb452f782014-06-27 11:53:35 +00001513std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagOp(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001514 std::string Op = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1515 if (DI->getNumArgs() == 2) {
1516 // Unary op.
1517 std::pair<Type, std::string> R =
Matthias Braunf1b01992016-12-05 06:00:51 +00001518 emitDagArg(DI->getArg(1), DI->getArgNameStr(1));
James Molloydee4ab02014-06-17 13:11:27 +00001519 return std::make_pair(R.first, Op + R.second);
1520 } else {
1521 assert(DI->getNumArgs() == 3 && "Can only handle unary and binary ops!");
1522 std::pair<Type, std::string> R1 =
Matthias Braunf1b01992016-12-05 06:00:51 +00001523 emitDagArg(DI->getArg(1), DI->getArgNameStr(1));
James Molloydee4ab02014-06-17 13:11:27 +00001524 std::pair<Type, std::string> R2 =
Matthias Braunf1b01992016-12-05 06:00:51 +00001525 emitDagArg(DI->getArg(2), DI->getArgNameStr(2));
James Molloydee4ab02014-06-17 13:11:27 +00001526 assert_with_loc(R1.first == R2.first, "Argument type mismatch!");
1527 return std::make_pair(R1.first, R1.second + " " + Op + " " + R2.second);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001528 }
James Molloydee4ab02014-06-17 13:11:27 +00001529}
Peter Collingbournebee583f2011-10-06 13:03:08 +00001530
James Molloyb452f782014-06-27 11:53:35 +00001531std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCall(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001532 std::vector<Type> Types;
1533 std::vector<std::string> Values;
1534 for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1535 std::pair<Type, std::string> R =
Matthias Braunf1b01992016-12-05 06:00:51 +00001536 emitDagArg(DI->getArg(I + 1), DI->getArgNameStr(I + 1));
James Molloydee4ab02014-06-17 13:11:27 +00001537 Types.push_back(R.first);
1538 Values.push_back(R.second);
1539 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001540
James Molloydee4ab02014-06-17 13:11:27 +00001541 // Look up the called intrinsic.
1542 std::string N;
1543 if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0)))
1544 N = SI->getAsUnquotedString();
Peter Collingbournebee583f2011-10-06 13:03:08 +00001545 else
James Molloydee4ab02014-06-17 13:11:27 +00001546 N = emitDagArg(DI->getArg(0), "").second;
David Blaikie4c96a5e2015-08-06 18:29:32 +00001547 Intrinsic &Callee = Intr.Emitter.getIntrinsic(N, Types);
James Molloydee4ab02014-06-17 13:11:27 +00001548
1549 // Make sure the callee is known as an early def.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001550 Callee.setNeededEarly();
1551 Intr.Dependencies.insert(&Callee);
James Molloydee4ab02014-06-17 13:11:27 +00001552
1553 // Now create the call itself.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001554 std::string S = CallPrefix.str() + Callee.getMangledName(true) + "(";
James Molloydee4ab02014-06-17 13:11:27 +00001555 for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1556 if (I != 0)
1557 S += ", ";
1558 S += Values[I];
1559 }
1560 S += ")";
1561
David Blaikie4c96a5e2015-08-06 18:29:32 +00001562 return std::make_pair(Callee.getReturnType(), S);
James Molloydee4ab02014-06-17 13:11:27 +00001563}
1564
James Molloyb452f782014-06-27 11:53:35 +00001565std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCast(DagInit *DI,
1566 bool IsBitCast){
James Molloydee4ab02014-06-17 13:11:27 +00001567 // (cast MOD* VAL) -> cast VAL to type given by MOD.
1568 std::pair<Type, std::string> R = emitDagArg(
Matthias Braunf1b01992016-12-05 06:00:51 +00001569 DI->getArg(DI->getNumArgs() - 1),
1570 DI->getArgNameStr(DI->getNumArgs() - 1));
James Molloydee4ab02014-06-17 13:11:27 +00001571 Type castToType = R.first;
1572 for (unsigned ArgIdx = 0; ArgIdx < DI->getNumArgs() - 1; ++ArgIdx) {
1573
1574 // MOD can take several forms:
1575 // 1. $X - take the type of parameter / variable X.
1576 // 2. The value "R" - take the type of the return type.
1577 // 3. a type string
1578 // 4. The value "U" or "S" to switch the signedness.
1579 // 5. The value "H" or "D" to half or double the bitwidth.
1580 // 6. The value "8" to convert to 8-bit (signed) integer lanes.
Matthias Braunf1b01992016-12-05 06:00:51 +00001581 if (!DI->getArgNameStr(ArgIdx).empty()) {
1582 assert_with_loc(Intr.Variables.find(DI->getArgNameStr(ArgIdx)) !=
James Molloyb452f782014-06-27 11:53:35 +00001583 Intr.Variables.end(),
James Molloydee4ab02014-06-17 13:11:27 +00001584 "Variable not found");
Matthias Braunf1b01992016-12-05 06:00:51 +00001585 castToType = Intr.Variables[DI->getArgNameStr(ArgIdx)].getType();
James Molloydee4ab02014-06-17 13:11:27 +00001586 } else {
1587 StringInit *SI = dyn_cast<StringInit>(DI->getArg(ArgIdx));
1588 assert_with_loc(SI, "Expected string type or $Name for cast type");
1589
1590 if (SI->getAsUnquotedString() == "R") {
James Molloyb452f782014-06-27 11:53:35 +00001591 castToType = Intr.getReturnType();
James Molloydee4ab02014-06-17 13:11:27 +00001592 } else if (SI->getAsUnquotedString() == "U") {
1593 castToType.makeUnsigned();
1594 } else if (SI->getAsUnquotedString() == "S") {
1595 castToType.makeSigned();
1596 } else if (SI->getAsUnquotedString() == "H") {
1597 castToType.halveLanes();
1598 } else if (SI->getAsUnquotedString() == "D") {
1599 castToType.doubleLanes();
1600 } else if (SI->getAsUnquotedString() == "8") {
1601 castToType.makeInteger(8, true);
1602 } else {
1603 castToType = Type::fromTypedefName(SI->getAsUnquotedString());
1604 assert_with_loc(!castToType.isVoid(), "Unknown typedef");
1605 }
1606 }
1607 }
1608
1609 std::string S;
1610 if (IsBitCast) {
1611 // Emit a reinterpret cast. The second operand must be an lvalue, so create
1612 // a temporary.
1613 std::string N = "reint";
1614 unsigned I = 0;
James Molloyb452f782014-06-27 11:53:35 +00001615 while (Intr.Variables.find(N) != Intr.Variables.end())
James Molloydee4ab02014-06-17 13:11:27 +00001616 N = "reint" + utostr(++I);
James Molloyb452f782014-06-27 11:53:35 +00001617 Intr.Variables[N] = Variable(R.first, N + Intr.VariablePostfix);
James Molloydee4ab02014-06-17 13:11:27 +00001618
James Molloyb452f782014-06-27 11:53:35 +00001619 Intr.OS << R.first.str() << " " << Intr.Variables[N].getName() << " = "
1620 << R.second << ";";
1621 Intr.emitNewLine();
James Molloydee4ab02014-06-17 13:11:27 +00001622
James Molloyb452f782014-06-27 11:53:35 +00001623 S = "*(" + castToType.str() + " *) &" + Intr.Variables[N].getName() + "";
James Molloydee4ab02014-06-17 13:11:27 +00001624 } else {
1625 // Emit a normal (static) cast.
1626 S = "(" + castToType.str() + ")(" + R.second + ")";
1627 }
1628
1629 return std::make_pair(castToType, S);
1630}
1631
James Molloyb452f782014-06-27 11:53:35 +00001632std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
James Molloydee4ab02014-06-17 13:11:27 +00001633 // See the documentation in arm_neon.td for a description of these operators.
1634 class LowHalf : public SetTheory::Operator {
1635 public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001636 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1637 ArrayRef<SMLoc> Loc) override {
James Molloydee4ab02014-06-17 13:11:27 +00001638 SetTheory::RecSet Elts2;
1639 ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1640 Elts.insert(Elts2.begin(), Elts2.begin() + (Elts2.size() / 2));
1641 }
1642 };
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001643
James Molloydee4ab02014-06-17 13:11:27 +00001644 class HighHalf : public SetTheory::Operator {
1645 public:
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001646 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1647 ArrayRef<SMLoc> Loc) override {
James Molloydee4ab02014-06-17 13:11:27 +00001648 SetTheory::RecSet Elts2;
1649 ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1650 Elts.insert(Elts2.begin() + (Elts2.size() / 2), Elts2.end());
1651 }
1652 };
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001653
James Molloydee4ab02014-06-17 13:11:27 +00001654 class Rev : public SetTheory::Operator {
1655 unsigned ElementSize;
1656
1657 public:
1658 Rev(unsigned ElementSize) : ElementSize(ElementSize) {}
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001659
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001660 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1661 ArrayRef<SMLoc> Loc) override {
James Molloydee4ab02014-06-17 13:11:27 +00001662 SetTheory::RecSet Elts2;
1663 ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Elts2, Loc);
1664
1665 int64_t VectorSize = cast<IntInit>(Expr->getArg(0))->getValue();
1666 VectorSize /= ElementSize;
1667
1668 std::vector<Record *> Revved;
1669 for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
1670 for (int LI = VectorSize - 1; LI >= 0; --LI) {
1671 Revved.push_back(Elts2[VI + LI]);
1672 }
1673 }
1674
1675 Elts.insert(Revved.begin(), Revved.end());
1676 }
1677 };
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001678
James Molloydee4ab02014-06-17 13:11:27 +00001679 class MaskExpander : public SetTheory::Expander {
1680 unsigned N;
1681
1682 public:
1683 MaskExpander(unsigned N) : N(N) {}
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001684
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001685 void expand(SetTheory &ST, Record *R, SetTheory::RecSet &Elts) override {
James Molloydee4ab02014-06-17 13:11:27 +00001686 unsigned Addend = 0;
1687 if (R->getName() == "mask0")
1688 Addend = 0;
1689 else if (R->getName() == "mask1")
1690 Addend = N;
1691 else
1692 return;
1693 for (unsigned I = 0; I < N; ++I)
1694 Elts.insert(R->getRecords().getDef("sv" + utostr(I + Addend)));
1695 }
1696 };
1697
1698 // (shuffle arg1, arg2, sequence)
1699 std::pair<Type, std::string> Arg1 =
Matthias Braunf1b01992016-12-05 06:00:51 +00001700 emitDagArg(DI->getArg(0), DI->getArgNameStr(0));
James Molloydee4ab02014-06-17 13:11:27 +00001701 std::pair<Type, std::string> Arg2 =
Matthias Braunf1b01992016-12-05 06:00:51 +00001702 emitDagArg(DI->getArg(1), DI->getArgNameStr(1));
James Molloydee4ab02014-06-17 13:11:27 +00001703 assert_with_loc(Arg1.first == Arg2.first,
1704 "Different types in arguments to shuffle!");
1705
1706 SetTheory ST;
James Molloydee4ab02014-06-17 13:11:27 +00001707 SetTheory::RecSet Elts;
Craig Topperbccb7732015-04-24 06:53:50 +00001708 ST.addOperator("lowhalf", llvm::make_unique<LowHalf>());
1709 ST.addOperator("highhalf", llvm::make_unique<HighHalf>());
1710 ST.addOperator("rev",
1711 llvm::make_unique<Rev>(Arg1.first.getElementSizeInBits()));
1712 ST.addExpander("MaskExpand",
1713 llvm::make_unique<MaskExpander>(Arg1.first.getNumElements()));
Craig Topper5fc8fc22014-08-27 06:28:36 +00001714 ST.evaluate(DI->getArg(2), Elts, None);
James Molloydee4ab02014-06-17 13:11:27 +00001715
1716 std::string S = "__builtin_shufflevector(" + Arg1.second + ", " + Arg2.second;
1717 for (auto &E : Elts) {
1718 StringRef Name = E->getName();
1719 assert_with_loc(Name.startswith("sv"),
1720 "Incorrect element kind in shuffle mask!");
1721 S += ", " + Name.drop_front(2).str();
1722 }
1723 S += ")";
1724
1725 // Recalculate the return type - the shuffle may have halved or doubled it.
1726 Type T(Arg1.first);
1727 if (Elts.size() > T.getNumElements()) {
1728 assert_with_loc(
1729 Elts.size() == T.getNumElements() * 2,
1730 "Can only double or half the number of elements in a shuffle!");
1731 T.doubleLanes();
1732 } else if (Elts.size() < T.getNumElements()) {
1733 assert_with_loc(
1734 Elts.size() == T.getNumElements() / 2,
1735 "Can only double or half the number of elements in a shuffle!");
1736 T.halveLanes();
1737 }
1738
1739 return std::make_pair(T, S);
1740}
1741
James Molloyb452f782014-06-27 11:53:35 +00001742std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDup(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001743 assert_with_loc(DI->getNumArgs() == 1, "dup() expects one argument");
Matthias Braunf1b01992016-12-05 06:00:51 +00001744 std::pair<Type, std::string> A = emitDagArg(DI->getArg(0),
1745 DI->getArgNameStr(0));
James Molloydee4ab02014-06-17 13:11:27 +00001746 assert_with_loc(A.first.isScalar(), "dup() expects a scalar argument");
1747
James Molloyb452f782014-06-27 11:53:35 +00001748 Type T = Intr.getBaseType();
James Molloydee4ab02014-06-17 13:11:27 +00001749 assert_with_loc(T.isVector(), "dup() used but default type is scalar!");
1750 std::string S = "(" + T.str() + ") {";
1751 for (unsigned I = 0; I < T.getNumElements(); ++I) {
1752 if (I != 0)
1753 S += ", ";
1754 S += A.second;
1755 }
1756 S += "}";
1757
1758 return std::make_pair(T, S);
1759}
1760
James Molloyb452f782014-06-27 11:53:35 +00001761std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSplat(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001762 assert_with_loc(DI->getNumArgs() == 2, "splat() expects two arguments");
Matthias Braunf1b01992016-12-05 06:00:51 +00001763 std::pair<Type, std::string> A = emitDagArg(DI->getArg(0),
1764 DI->getArgNameStr(0));
1765 std::pair<Type, std::string> B = emitDagArg(DI->getArg(1),
1766 DI->getArgNameStr(1));
James Molloydee4ab02014-06-17 13:11:27 +00001767
1768 assert_with_loc(B.first.isScalar(),
1769 "splat() requires a scalar int as the second argument");
1770
1771 std::string S = "__builtin_shufflevector(" + A.second + ", " + A.second;
James Molloyb452f782014-06-27 11:53:35 +00001772 for (unsigned I = 0; I < Intr.getBaseType().getNumElements(); ++I) {
James Molloydee4ab02014-06-17 13:11:27 +00001773 S += ", " + B.second;
1774 }
1775 S += ")";
1776
James Molloyb452f782014-06-27 11:53:35 +00001777 return std::make_pair(Intr.getBaseType(), S);
James Molloydee4ab02014-06-17 13:11:27 +00001778}
1779
James Molloyb452f782014-06-27 11:53:35 +00001780std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSaveTemp(DagInit *DI) {
James Molloydee4ab02014-06-17 13:11:27 +00001781 assert_with_loc(DI->getNumArgs() == 2, "save_temp() expects two arguments");
Matthias Braunf1b01992016-12-05 06:00:51 +00001782 std::pair<Type, std::string> A = emitDagArg(DI->getArg(1),
1783 DI->getArgNameStr(1));
James Molloydee4ab02014-06-17 13:11:27 +00001784
1785 assert_with_loc(!A.first.isVoid(),
1786 "Argument to save_temp() must have non-void type!");
1787
Matthias Braunf1b01992016-12-05 06:00:51 +00001788 std::string N = DI->getArgNameStr(0);
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001789 assert_with_loc(!N.empty(),
1790 "save_temp() expects a name as the first argument");
James Molloydee4ab02014-06-17 13:11:27 +00001791
James Molloyb452f782014-06-27 11:53:35 +00001792 assert_with_loc(Intr.Variables.find(N) == Intr.Variables.end(),
James Molloydee4ab02014-06-17 13:11:27 +00001793 "Variable already defined!");
James Molloyb452f782014-06-27 11:53:35 +00001794 Intr.Variables[N] = Variable(A.first, N + Intr.VariablePostfix);
James Molloydee4ab02014-06-17 13:11:27 +00001795
1796 std::string S =
James Molloyb452f782014-06-27 11:53:35 +00001797 A.first.str() + " " + Intr.Variables[N].getName() + " = " + A.second;
James Molloydee4ab02014-06-17 13:11:27 +00001798
1799 return std::make_pair(Type::getVoid(), S);
1800}
1801
James Molloyb452f782014-06-27 11:53:35 +00001802std::pair<Type, std::string>
1803Intrinsic::DagEmitter::emitDagNameReplace(DagInit *DI) {
1804 std::string S = Intr.Name;
James Molloydee4ab02014-06-17 13:11:27 +00001805
1806 assert_with_loc(DI->getNumArgs() == 2, "name_replace requires 2 arguments!");
1807 std::string ToReplace = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1808 std::string ReplaceWith = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1809
1810 size_t Idx = S.find(ToReplace);
1811
1812 assert_with_loc(Idx != std::string::npos, "name should contain '" + ToReplace + "'!");
1813 S.replace(Idx, ToReplace.size(), ReplaceWith);
1814
1815 return std::make_pair(Type::getVoid(), S);
1816}
1817
James Molloyb452f782014-06-27 11:53:35 +00001818std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagLiteral(DagInit *DI){
James Molloydee4ab02014-06-17 13:11:27 +00001819 std::string Ty = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1820 std::string Value = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1821 return std::make_pair(Type::fromTypedefName(Ty), Value);
1822}
1823
James Molloyb452f782014-06-27 11:53:35 +00001824std::pair<Type, std::string>
1825Intrinsic::DagEmitter::emitDagArg(Init *Arg, std::string ArgName) {
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001826 if (!ArgName.empty()) {
James Molloydee4ab02014-06-17 13:11:27 +00001827 assert_with_loc(!Arg->isComplete(),
1828 "Arguments must either be DAGs or names, not both!");
James Molloyb452f782014-06-27 11:53:35 +00001829 assert_with_loc(Intr.Variables.find(ArgName) != Intr.Variables.end(),
James Molloydee4ab02014-06-17 13:11:27 +00001830 "Variable not defined!");
James Molloyb452f782014-06-27 11:53:35 +00001831 Variable &V = Intr.Variables[ArgName];
James Molloydee4ab02014-06-17 13:11:27 +00001832 return std::make_pair(V.getType(), V.getName());
1833 }
1834
1835 assert(Arg && "Neither ArgName nor Arg?!");
1836 DagInit *DI = dyn_cast<DagInit>(Arg);
1837 assert_with_loc(DI, "Arguments must either be DAGs or names!");
1838
1839 return emitDag(DI);
1840}
1841
1842std::string Intrinsic::generate() {
James Molloyb452f782014-06-27 11:53:35 +00001843 // Little endian intrinsics are simple and don't require any argument
1844 // swapping.
1845 OS << "#ifdef __LITTLE_ENDIAN__\n";
1846
1847 generateImpl(false, "", "");
1848
1849 OS << "#else\n";
1850
1851 // Big endian intrinsics are more complex. The user intended these
1852 // intrinsics to operate on a vector "as-if" loaded by (V)LDR,
1853 // but we load as-if (V)LD1. So we should swap all arguments and
1854 // swap the return value too.
1855 //
1856 // If we call sub-intrinsics, we should call a version that does
1857 // not re-swap the arguments!
1858 generateImpl(true, "", "__noswap_");
1859
1860 // If we're needed early, create a non-swapping variant for
1861 // big-endian.
1862 if (NeededEarly) {
1863 generateImpl(false, "__noswap_", "__noswap_");
1864 }
1865 OS << "#endif\n\n";
1866
1867 return OS.str();
1868}
1869
1870void Intrinsic::generateImpl(bool ReverseArguments,
1871 StringRef NamePrefix, StringRef CallPrefix) {
James Molloydee4ab02014-06-17 13:11:27 +00001872 CurrentRecord = R;
1873
1874 // If we call a macro, our local variables may be corrupted due to
1875 // lack of proper lexical scoping. So, add a globally unique postfix
1876 // to every variable.
1877 //
1878 // indexBody() should have set up the Dependencies set by now.
1879 for (auto *I : Dependencies)
1880 if (I->UseMacro) {
1881 VariablePostfix = "_" + utostr(Emitter.getUniqueNumber());
1882 break;
1883 }
1884
1885 initVariables();
1886
James Molloyb452f782014-06-27 11:53:35 +00001887 emitPrototype(NamePrefix);
James Molloydee4ab02014-06-17 13:11:27 +00001888
1889 if (IsUnavailable) {
1890 OS << " __attribute__((unavailable));";
1891 } else {
1892 emitOpeningBrace();
1893 emitShadowedArgs();
James Molloyb452f782014-06-27 11:53:35 +00001894 if (ReverseArguments)
1895 emitArgumentReversal();
1896 emitBody(CallPrefix);
1897 if (ReverseArguments)
1898 emitReturnReversal();
James Molloydee4ab02014-06-17 13:11:27 +00001899 emitReturn();
1900 emitClosingBrace();
1901 }
1902 OS << "\n";
1903
1904 CurrentRecord = nullptr;
James Molloydee4ab02014-06-17 13:11:27 +00001905}
1906
1907void Intrinsic::indexBody() {
1908 CurrentRecord = R;
1909
1910 initVariables();
James Molloyb452f782014-06-27 11:53:35 +00001911 emitBody("");
James Molloydee4ab02014-06-17 13:11:27 +00001912 OS.str("");
1913
1914 CurrentRecord = nullptr;
1915}
1916
1917//===----------------------------------------------------------------------===//
1918// NeonEmitter implementation
1919//===----------------------------------------------------------------------===//
1920
David Blaikie4c96a5e2015-08-06 18:29:32 +00001921Intrinsic &NeonEmitter::getIntrinsic(StringRef Name, ArrayRef<Type> Types) {
James Molloydee4ab02014-06-17 13:11:27 +00001922 // First, look up the name in the intrinsic map.
1923 assert_with_loc(IntrinsicMap.find(Name.str()) != IntrinsicMap.end(),
1924 ("Intrinsic '" + Name + "' not found!").str());
David Blaikie4c96a5e2015-08-06 18:29:32 +00001925 auto &V = IntrinsicMap.find(Name.str())->second;
James Molloydee4ab02014-06-17 13:11:27 +00001926 std::vector<Intrinsic *> GoodVec;
1927
1928 // Create a string to print if we end up failing.
1929 std::string ErrMsg = "looking up intrinsic '" + Name.str() + "(";
1930 for (unsigned I = 0; I < Types.size(); ++I) {
1931 if (I != 0)
1932 ErrMsg += ", ";
1933 ErrMsg += Types[I].str();
1934 }
1935 ErrMsg += ")'\n";
1936 ErrMsg += "Available overloads:\n";
1937
1938 // Now, look through each intrinsic implementation and see if the types are
1939 // compatible.
David Blaikie4c96a5e2015-08-06 18:29:32 +00001940 for (auto &I : V) {
1941 ErrMsg += " - " + I.getReturnType().str() + " " + I.getMangledName();
James Molloydee4ab02014-06-17 13:11:27 +00001942 ErrMsg += "(";
David Blaikie4c96a5e2015-08-06 18:29:32 +00001943 for (unsigned A = 0; A < I.getNumParams(); ++A) {
James Molloydee4ab02014-06-17 13:11:27 +00001944 if (A != 0)
1945 ErrMsg += ", ";
David Blaikie4c96a5e2015-08-06 18:29:32 +00001946 ErrMsg += I.getParamType(A).str();
James Molloydee4ab02014-06-17 13:11:27 +00001947 }
1948 ErrMsg += ")\n";
1949
David Blaikie4c96a5e2015-08-06 18:29:32 +00001950 if (I.getNumParams() != Types.size())
James Molloydee4ab02014-06-17 13:11:27 +00001951 continue;
1952
1953 bool Good = true;
1954 for (unsigned Arg = 0; Arg < Types.size(); ++Arg) {
David Blaikie4c96a5e2015-08-06 18:29:32 +00001955 if (I.getParamType(Arg) != Types[Arg]) {
James Molloydee4ab02014-06-17 13:11:27 +00001956 Good = false;
1957 break;
1958 }
1959 }
1960 if (Good)
David Blaikie4c96a5e2015-08-06 18:29:32 +00001961 GoodVec.push_back(&I);
James Molloydee4ab02014-06-17 13:11:27 +00001962 }
1963
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00001964 assert_with_loc(!GoodVec.empty(),
James Molloydee4ab02014-06-17 13:11:27 +00001965 "No compatible intrinsic found - " + ErrMsg);
1966 assert_with_loc(GoodVec.size() == 1, "Multiple overloads found - " + ErrMsg);
1967
David Blaikie4c96a5e2015-08-06 18:29:32 +00001968 return *GoodVec.front();
James Molloydee4ab02014-06-17 13:11:27 +00001969}
1970
1971void NeonEmitter::createIntrinsic(Record *R,
1972 SmallVectorImpl<Intrinsic *> &Out) {
1973 std::string Name = R->getValueAsString("Name");
1974 std::string Proto = R->getValueAsString("Prototype");
1975 std::string Types = R->getValueAsString("Types");
1976 Record *OperationRec = R->getValueAsDef("Operation");
1977 bool CartesianProductOfTypes = R->getValueAsBit("CartesianProductOfTypes");
James Molloyb452f782014-06-27 11:53:35 +00001978 bool BigEndianSafe = R->getValueAsBit("BigEndianSafe");
James Molloydee4ab02014-06-17 13:11:27 +00001979 std::string Guard = R->getValueAsString("ArchGuard");
1980 bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
1981
1982 // Set the global current record. This allows assert_with_loc to produce
1983 // decent location information even when highly nested.
1984 CurrentRecord = R;
1985
1986 ListInit *Body = OperationRec->getValueAsListInit("Ops");
1987
1988 std::vector<TypeSpec> TypeSpecs = TypeSpec::fromTypeSpecs(Types);
1989
1990 ClassKind CK = ClassNone;
1991 if (R->getSuperClasses().size() >= 2)
Craig Topper25761242016-01-18 19:52:54 +00001992 CK = ClassMap[R->getSuperClasses()[1].first];
James Molloydee4ab02014-06-17 13:11:27 +00001993
1994 std::vector<std::pair<TypeSpec, TypeSpec>> NewTypeSpecs;
1995 for (auto TS : TypeSpecs) {
1996 if (CartesianProductOfTypes) {
1997 Type DefaultT(TS, 'd');
1998 for (auto SrcTS : TypeSpecs) {
1999 Type DefaultSrcT(SrcTS, 'd');
2000 if (TS == SrcTS ||
2001 DefaultSrcT.getSizeInBits() != DefaultT.getSizeInBits())
2002 continue;
2003 NewTypeSpecs.push_back(std::make_pair(TS, SrcTS));
2004 }
2005 } else {
2006 NewTypeSpecs.push_back(std::make_pair(TS, TS));
2007 }
2008 }
2009
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002010 llvm::sort(NewTypeSpecs.begin(), NewTypeSpecs.end());
James Dennettfa245492015-04-06 21:09:24 +00002011 NewTypeSpecs.erase(std::unique(NewTypeSpecs.begin(), NewTypeSpecs.end()),
2012 NewTypeSpecs.end());
David Blaikie4c96a5e2015-08-06 18:29:32 +00002013 auto &Entry = IntrinsicMap[Name];
James Molloydee4ab02014-06-17 13:11:27 +00002014
2015 for (auto &I : NewTypeSpecs) {
David Blaikie4c96a5e2015-08-06 18:29:32 +00002016 Entry.emplace_back(R, Name, Proto, I.first, I.second, CK, Body, *this,
2017 Guard, IsUnavailable, BigEndianSafe);
2018 Out.push_back(&Entry.back());
James Molloydee4ab02014-06-17 13:11:27 +00002019 }
2020
2021 CurrentRecord = nullptr;
2022}
2023
2024/// genBuiltinsDef: Generate the BuiltinsARM.def and BuiltinsAArch64.def
2025/// declaration of builtins, checking for unique builtin declarations.
2026void NeonEmitter::genBuiltinsDef(raw_ostream &OS,
2027 SmallVectorImpl<Intrinsic *> &Defs) {
2028 OS << "#ifdef GET_NEON_BUILTINS\n";
2029
2030 // We only want to emit a builtin once, and we want to emit them in
2031 // alphabetical order, so use a std::set.
2032 std::set<std::string> Builtins;
2033
2034 for (auto *Def : Defs) {
2035 if (Def->hasBody())
2036 continue;
2037 // Functions with 'a' (the splat code) in the type prototype should not get
2038 // their own builtin as they use the non-splat variant.
2039 if (Def->hasSplat())
2040 continue;
2041
2042 std::string S = "BUILTIN(__builtin_neon_" + Def->getMangledName() + ", \"";
2043
2044 S += Def->getBuiltinTypeStr();
2045 S += "\", \"n\")";
2046
2047 Builtins.insert(S);
2048 }
2049
2050 for (auto &S : Builtins)
2051 OS << S << "\n";
2052 OS << "#endif\n\n";
2053}
2054
2055/// Generate the ARM and AArch64 overloaded type checking code for
2056/// SemaChecking.cpp, checking for unique builtin declarations.
2057void NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS,
2058 SmallVectorImpl<Intrinsic *> &Defs) {
2059 OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
2060
2061 // We record each overload check line before emitting because subsequent Inst
2062 // definitions may extend the number of permitted types (i.e. augment the
2063 // Mask). Use std::map to avoid sorting the table by hash number.
2064 struct OverloadInfo {
2065 uint64_t Mask;
2066 int PtrArgNum;
2067 bool HasConstPtr;
2068 OverloadInfo() : Mask(0ULL), PtrArgNum(0), HasConstPtr(false) {}
2069 };
2070 std::map<std::string, OverloadInfo> OverloadMap;
2071
2072 for (auto *Def : Defs) {
2073 // If the def has a body (that is, it has Operation DAGs), it won't call
2074 // __builtin_neon_* so we don't need to generate a definition for it.
2075 if (Def->hasBody())
2076 continue;
2077 // Functions with 'a' (the splat code) in the type prototype should not get
2078 // their own builtin as they use the non-splat variant.
2079 if (Def->hasSplat())
2080 continue;
2081 // Functions which have a scalar argument cannot be overloaded, no need to
2082 // check them if we are emitting the type checking code.
2083 if (Def->protoHasScalar())
2084 continue;
2085
2086 uint64_t Mask = 0ULL;
2087 Type Ty = Def->getReturnType();
Ahmed Bougacha22a16962015-08-21 23:24:18 +00002088 if (Def->getProto()[0] == 'v' ||
2089 isFloatingPointProtoModifier(Def->getProto()[0]))
James Molloydee4ab02014-06-17 13:11:27 +00002090 Ty = Def->getParamType(0);
2091 if (Ty.isPointer())
2092 Ty = Def->getParamType(1);
2093
2094 Mask |= 1ULL << Ty.getNeonEnum();
2095
2096 // Check if the function has a pointer or const pointer argument.
2097 std::string Proto = Def->getProto();
2098 int PtrArgNum = -1;
2099 bool HasConstPtr = false;
2100 for (unsigned I = 0; I < Def->getNumParams(); ++I) {
2101 char ArgType = Proto[I + 1];
2102 if (ArgType == 'c') {
2103 HasConstPtr = true;
2104 PtrArgNum = I;
2105 break;
2106 }
2107 if (ArgType == 'p') {
2108 PtrArgNum = I;
2109 break;
2110 }
2111 }
2112 // For sret builtins, adjust the pointer argument index.
2113 if (PtrArgNum >= 0 && Def->getReturnType().getNumVectors() > 1)
2114 PtrArgNum += 1;
2115
2116 std::string Name = Def->getName();
2117 // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
2118 // and vst1_lane intrinsics. Using a pointer to the vector element
2119 // type with one of those operations causes codegen to select an aligned
2120 // load/store instruction. If you want an unaligned operation,
2121 // the pointer argument needs to have less alignment than element type,
2122 // so just accept any pointer type.
2123 if (Name == "vld1_lane" || Name == "vld1_dup" || Name == "vst1_lane") {
2124 PtrArgNum = -1;
2125 HasConstPtr = false;
2126 }
2127
2128 if (Mask) {
2129 std::string Name = Def->getMangledName();
2130 OverloadMap.insert(std::make_pair(Name, OverloadInfo()));
2131 OverloadInfo &OI = OverloadMap[Name];
2132 OI.Mask |= Mask;
2133 OI.PtrArgNum |= PtrArgNum;
2134 OI.HasConstPtr = HasConstPtr;
2135 }
2136 }
2137
2138 for (auto &I : OverloadMap) {
2139 OverloadInfo &OI = I.second;
2140
2141 OS << "case NEON::BI__builtin_neon_" << I.first << ": ";
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002142 OS << "mask = 0x" << Twine::utohexstr(OI.Mask) << "ULL";
James Molloydee4ab02014-06-17 13:11:27 +00002143 if (OI.PtrArgNum >= 0)
2144 OS << "; PtrArgNum = " << OI.PtrArgNum;
2145 if (OI.HasConstPtr)
2146 OS << "; HasConstPtr = true";
2147 OS << "; break;\n";
2148 }
2149 OS << "#endif\n\n";
2150}
2151
2152void
2153NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
2154 SmallVectorImpl<Intrinsic *> &Defs) {
2155 OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
2156
2157 std::set<std::string> Emitted;
2158
2159 for (auto *Def : Defs) {
2160 if (Def->hasBody())
2161 continue;
2162 // Functions with 'a' (the splat code) in the type prototype should not get
2163 // their own builtin as they use the non-splat variant.
2164 if (Def->hasSplat())
2165 continue;
Alp Toker958027b2014-07-14 19:42:55 +00002166 // Functions which do not have an immediate do not need to have range
2167 // checking code emitted.
James Molloydee4ab02014-06-17 13:11:27 +00002168 if (!Def->hasImmediate())
2169 continue;
2170 if (Emitted.find(Def->getMangledName()) != Emitted.end())
2171 continue;
2172
2173 std::string LowerBound, UpperBound;
2174
2175 Record *R = Def->getRecord();
2176 if (R->getValueAsBit("isVCVT_N")) {
2177 // VCVT between floating- and fixed-point values takes an immediate
2178 // in the range [1, 32) for f32 or [1, 64) for f64.
2179 LowerBound = "1";
2180 if (Def->getBaseType().getElementSizeInBits() == 32)
2181 UpperBound = "31";
2182 else
2183 UpperBound = "63";
2184 } else if (R->getValueAsBit("isScalarShift")) {
2185 // Right shifts have an 'r' in the name, left shifts do not. Convert
2186 // instructions have the same bounds and right shifts.
2187 if (Def->getName().find('r') != std::string::npos ||
2188 Def->getName().find("cvt") != std::string::npos)
2189 LowerBound = "1";
2190
2191 UpperBound = utostr(Def->getReturnType().getElementSizeInBits() - 1);
2192 } else if (R->getValueAsBit("isShift")) {
Alp Toker958027b2014-07-14 19:42:55 +00002193 // Builtins which are overloaded by type will need to have their upper
James Molloydee4ab02014-06-17 13:11:27 +00002194 // bound computed at Sema time based on the type constant.
2195
2196 // Right shifts have an 'r' in the name, left shifts do not.
2197 if (Def->getName().find('r') != std::string::npos)
2198 LowerBound = "1";
2199 UpperBound = "RFT(TV, true)";
2200 } else if (Def->getClassKind(true) == ClassB) {
2201 // ClassB intrinsics have a type (and hence lane number) that is only
2202 // known at runtime.
2203 if (R->getValueAsBit("isLaneQ"))
2204 UpperBound = "RFT(TV, false, true)";
2205 else
2206 UpperBound = "RFT(TV, false, false)";
2207 } else {
2208 // The immediate generally refers to a lane in the preceding argument.
2209 assert(Def->getImmediateIdx() > 0);
2210 Type T = Def->getParamType(Def->getImmediateIdx() - 1);
2211 UpperBound = utostr(T.getNumElements() - 1);
2212 }
2213
2214 // Calculate the index of the immediate that should be range checked.
2215 unsigned Idx = Def->getNumParams();
2216 if (Def->hasImmediate())
2217 Idx = Def->getGeneratedParamIdx(Def->getImmediateIdx());
2218
2219 OS << "case NEON::BI__builtin_neon_" << Def->getMangledName() << ": "
2220 << "i = " << Idx << ";";
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00002221 if (!LowerBound.empty())
James Molloydee4ab02014-06-17 13:11:27 +00002222 OS << " l = " << LowerBound << ";";
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00002223 if (!UpperBound.empty())
James Molloydee4ab02014-06-17 13:11:27 +00002224 OS << " u = " << UpperBound << ";";
2225 OS << " break;\n";
2226
2227 Emitted.insert(Def->getMangledName());
2228 }
2229
2230 OS << "#endif\n\n";
2231}
2232
2233/// runHeader - Emit a file with sections defining:
2234/// 1. the NEON section of BuiltinsARM.def and BuiltinsAArch64.def.
2235/// 2. the SemaChecking code for the type overload checking.
2236/// 3. the SemaChecking code for validation of intrinsic immediate arguments.
2237void NeonEmitter::runHeader(raw_ostream &OS) {
2238 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2239
2240 SmallVector<Intrinsic *, 128> Defs;
2241 for (auto *R : RV)
2242 createIntrinsic(R, Defs);
2243
2244 // Generate shared BuiltinsXXX.def
2245 genBuiltinsDef(OS, Defs);
2246
2247 // Generate ARM overloaded type checking code for SemaChecking.cpp
2248 genOverloadTypeCheckCode(OS, Defs);
2249
2250 // Generate ARM range checking code for shift/lane immediates.
2251 genIntrinsicRangeCheckCode(OS, Defs);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002252}
2253
2254/// run - Read the records in arm_neon.td and output arm_neon.h. arm_neon.h
2255/// is comprised of type definitions and function declarations.
2256void NeonEmitter::run(raw_ostream &OS) {
James Molloydee4ab02014-06-17 13:11:27 +00002257 OS << "/*===---- arm_neon.h - ARM Neon intrinsics "
2258 "------------------------------"
2259 "---===\n"
2260 " *\n"
2261 " * Permission is hereby granted, free of charge, to any person "
2262 "obtaining "
2263 "a copy\n"
2264 " * of this software and associated documentation files (the "
2265 "\"Software\"),"
2266 " to deal\n"
2267 " * in the Software without restriction, including without limitation "
2268 "the "
2269 "rights\n"
2270 " * to use, copy, modify, merge, publish, distribute, sublicense, "
2271 "and/or sell\n"
2272 " * copies of the Software, and to permit persons to whom the Software "
2273 "is\n"
2274 " * furnished to do so, subject to the following conditions:\n"
2275 " *\n"
2276 " * The above copyright notice and this permission notice shall be "
2277 "included in\n"
2278 " * all copies or substantial portions of the Software.\n"
2279 " *\n"
2280 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2281 "EXPRESS OR\n"
2282 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2283 "MERCHANTABILITY,\n"
2284 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2285 "SHALL THE\n"
2286 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2287 "OTHER\n"
2288 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2289 "ARISING FROM,\n"
2290 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2291 "DEALINGS IN\n"
2292 " * THE SOFTWARE.\n"
2293 " *\n"
2294 " *===-----------------------------------------------------------------"
2295 "---"
2296 "---===\n"
2297 " */\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002298
2299 OS << "#ifndef __ARM_NEON_H\n";
2300 OS << "#define __ARM_NEON_H\n\n";
2301
Tim Northover5bb34ca2013-11-21 12:36:34 +00002302 OS << "#if !defined(__ARM_NEON)\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002303 OS << "#error \"NEON support not enabled\"\n";
2304 OS << "#endif\n\n";
2305
2306 OS << "#include <stdint.h>\n\n";
2307
2308 // Emit NEON-specific scalar typedefs.
2309 OS << "typedef float float32_t;\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002310 OS << "typedef __fp16 float16_t;\n";
2311
2312 OS << "#ifdef __aarch64__\n";
2313 OS << "typedef double float64_t;\n";
2314 OS << "#endif\n\n";
2315
2316 // For now, signedness of polynomial types depends on target
2317 OS << "#ifdef __aarch64__\n";
2318 OS << "typedef uint8_t poly8_t;\n";
2319 OS << "typedef uint16_t poly16_t;\n";
Kevin Qincaac85e2013-11-14 03:29:16 +00002320 OS << "typedef uint64_t poly64_t;\n";
Kevin Qinfb79d7f2013-12-10 06:49:01 +00002321 OS << "typedef __uint128_t poly128_t;\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002322 OS << "#else\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002323 OS << "typedef int8_t poly8_t;\n";
2324 OS << "typedef int16_t poly16_t;\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002325 OS << "#endif\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002326
2327 // Emit Neon vector typedefs.
Tim Northover2fe823a2013-08-01 09:23:19 +00002328 std::string TypedefTypes(
Kevin Qincaac85e2013-11-14 03:29:16 +00002329 "cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfdQdPcQPcPsQPsPlQPl");
James Molloydee4ab02014-06-17 13:11:27 +00002330 std::vector<TypeSpec> TDTypeVec = TypeSpec::fromTypeSpecs(TypedefTypes);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002331
2332 // Emit vector typedefs.
James Molloydee4ab02014-06-17 13:11:27 +00002333 bool InIfdef = false;
2334 for (auto &TS : TDTypeVec) {
2335 bool IsA64 = false;
2336 Type T(TS, 'd');
2337 if (T.isDouble() || (T.isPoly() && T.isLong()))
2338 IsA64 = true;
Tim Northover2fe823a2013-08-01 09:23:19 +00002339
James Molloydee4ab02014-06-17 13:11:27 +00002340 if (InIfdef && !IsA64) {
Jiangning Liu4617e9d2013-10-04 09:21:17 +00002341 OS << "#endif\n";
James Molloydee4ab02014-06-17 13:11:27 +00002342 InIfdef = false;
2343 }
2344 if (!InIfdef && IsA64) {
Tim Northover2fe823a2013-08-01 09:23:19 +00002345 OS << "#ifdef __aarch64__\n";
James Molloydee4ab02014-06-17 13:11:27 +00002346 InIfdef = true;
2347 }
Tim Northover2fe823a2013-08-01 09:23:19 +00002348
James Molloydee4ab02014-06-17 13:11:27 +00002349 if (T.isPoly())
Peter Collingbournebee583f2011-10-06 13:03:08 +00002350 OS << "typedef __attribute__((neon_polyvector_type(";
2351 else
2352 OS << "typedef __attribute__((neon_vector_type(";
2353
James Molloydee4ab02014-06-17 13:11:27 +00002354 Type T2 = T;
2355 T2.makeScalar();
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002356 OS << T.getNumElements() << "))) ";
James Molloydee4ab02014-06-17 13:11:27 +00002357 OS << T2.str();
2358 OS << " " << T.str() << ";\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002359 }
James Molloydee4ab02014-06-17 13:11:27 +00002360 if (InIfdef)
Kevin Qincaac85e2013-11-14 03:29:16 +00002361 OS << "#endif\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002362 OS << "\n";
2363
2364 // Emit struct typedefs.
James Molloydee4ab02014-06-17 13:11:27 +00002365 InIfdef = false;
2366 for (unsigned NumMembers = 2; NumMembers <= 4; ++NumMembers) {
2367 for (auto &TS : TDTypeVec) {
2368 bool IsA64 = false;
2369 Type T(TS, 'd');
2370 if (T.isDouble() || (T.isPoly() && T.isLong()))
2371 IsA64 = true;
Tim Northover2fe823a2013-08-01 09:23:19 +00002372
James Molloydee4ab02014-06-17 13:11:27 +00002373 if (InIfdef && !IsA64) {
Jiangning Liu4617e9d2013-10-04 09:21:17 +00002374 OS << "#endif\n";
James Molloydee4ab02014-06-17 13:11:27 +00002375 InIfdef = false;
2376 }
2377 if (!InIfdef && IsA64) {
Tim Northover2fe823a2013-08-01 09:23:19 +00002378 OS << "#ifdef __aarch64__\n";
James Molloydee4ab02014-06-17 13:11:27 +00002379 InIfdef = true;
2380 }
Tim Northover2fe823a2013-08-01 09:23:19 +00002381
James Molloydee4ab02014-06-17 13:11:27 +00002382 char M = '2' + (NumMembers - 2);
2383 Type VT(TS, M);
2384 OS << "typedef struct " << VT.str() << " {\n";
2385 OS << " " << T.str() << " val";
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002386 OS << "[" << NumMembers << "]";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002387 OS << ";\n} ";
James Molloydee4ab02014-06-17 13:11:27 +00002388 OS << VT.str() << ";\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002389 OS << "\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002390 }
2391 }
James Molloydee4ab02014-06-17 13:11:27 +00002392 if (InIfdef)
Kevin Qincaac85e2013-11-14 03:29:16 +00002393 OS << "#endif\n";
2394 OS << "\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002395
James Molloydee4ab02014-06-17 13:11:27 +00002396 OS << "#define __ai static inline __attribute__((__always_inline__, "
2397 "__nodebug__))\n\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002398
James Molloydee4ab02014-06-17 13:11:27 +00002399 SmallVector<Intrinsic *, 128> Defs;
2400 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2401 for (auto *R : RV)
2402 createIntrinsic(R, Defs);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002403
James Molloydee4ab02014-06-17 13:11:27 +00002404 for (auto *I : Defs)
2405 I->indexBody();
Tim Northover2fe823a2013-08-01 09:23:19 +00002406
James Molloydee4ab02014-06-17 13:11:27 +00002407 std::stable_sort(
2408 Defs.begin(), Defs.end(),
2409 [](const Intrinsic *A, const Intrinsic *B) { return *A < *B; });
Tim Northover2fe823a2013-08-01 09:23:19 +00002410
James Molloydee4ab02014-06-17 13:11:27 +00002411 // Only emit a def when its requirements have been met.
2412 // FIXME: This loop could be made faster, but it's fast enough for now.
2413 bool MadeProgress = true;
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00002414 std::string InGuard;
James Molloydee4ab02014-06-17 13:11:27 +00002415 while (!Defs.empty() && MadeProgress) {
2416 MadeProgress = false;
2417
2418 for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2419 I != Defs.end(); /*No step*/) {
2420 bool DependenciesSatisfied = true;
2421 for (auto *II : (*I)->getDependencies()) {
2422 if (std::find(Defs.begin(), Defs.end(), II) != Defs.end())
2423 DependenciesSatisfied = false;
2424 }
2425 if (!DependenciesSatisfied) {
2426 // Try the next one.
2427 ++I;
2428 continue;
2429 }
2430
2431 // Emit #endif/#if pair if needed.
2432 if ((*I)->getGuard() != InGuard) {
2433 if (!InGuard.empty())
2434 OS << "#endif\n";
2435 InGuard = (*I)->getGuard();
2436 if (!InGuard.empty())
2437 OS << "#if " << InGuard << "\n";
2438 }
2439
2440 // Actually generate the intrinsic code.
2441 OS << (*I)->generate();
2442
2443 MadeProgress = true;
2444 I = Defs.erase(I);
2445 }
Tim Northover2fe823a2013-08-01 09:23:19 +00002446 }
James Molloydee4ab02014-06-17 13:11:27 +00002447 assert(Defs.empty() && "Some requirements were not satisfied!");
2448 if (!InGuard.empty())
2449 OS << "#endif\n";
Tim Northover2fe823a2013-08-01 09:23:19 +00002450
James Molloydee4ab02014-06-17 13:11:27 +00002451 OS << "\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002452 OS << "#undef __ai\n\n";
2453 OS << "#endif /* __ARM_NEON_H */\n";
2454}
2455
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00002456/// run - Read the records in arm_fp16.td and output arm_fp16.h. arm_fp16.h
2457/// is comprised of type definitions and function declarations.
2458void NeonEmitter::runFP16(raw_ostream &OS) {
2459 OS << "/*===---- arm_fp16.h - ARM FP16 intrinsics "
2460 "------------------------------"
2461 "---===\n"
2462 " *\n"
2463 " * Permission is hereby granted, free of charge, to any person "
2464 "obtaining a copy\n"
2465 " * of this software and associated documentation files (the "
2466 "\"Software\"), to deal\n"
2467 " * in the Software without restriction, including without limitation "
2468 "the rights\n"
2469 " * to use, copy, modify, merge, publish, distribute, sublicense, "
2470 "and/or sell\n"
2471 " * copies of the Software, and to permit persons to whom the Software "
2472 "is\n"
2473 " * furnished to do so, subject to the following conditions:\n"
2474 " *\n"
2475 " * The above copyright notice and this permission notice shall be "
2476 "included in\n"
2477 " * all copies or substantial portions of the Software.\n"
2478 " *\n"
2479 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2480 "EXPRESS OR\n"
2481 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2482 "MERCHANTABILITY,\n"
2483 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2484 "SHALL THE\n"
2485 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2486 "OTHER\n"
2487 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2488 "ARISING FROM,\n"
2489 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2490 "DEALINGS IN\n"
2491 " * THE SOFTWARE.\n"
2492 " *\n"
2493 " *===-----------------------------------------------------------------"
2494 "---"
2495 "---===\n"
2496 " */\n\n";
2497
2498 OS << "#ifndef __ARM_FP16_H\n";
2499 OS << "#define __ARM_FP16_H\n\n";
2500
2501 OS << "#include <stdint.h>\n\n";
2502
2503 OS << "typedef __fp16 float16_t;\n";
2504
2505 OS << "#define __ai static inline __attribute__((__always_inline__, "
2506 "__nodebug__))\n\n";
2507
2508 SmallVector<Intrinsic *, 128> Defs;
2509 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2510 for (auto *R : RV)
2511 createIntrinsic(R, Defs);
2512
2513 for (auto *I : Defs)
2514 I->indexBody();
2515
2516 std::stable_sort(
2517 Defs.begin(), Defs.end(),
2518 [](const Intrinsic *A, const Intrinsic *B) { return *A < *B; });
2519
2520 // Only emit a def when its requirements have been met.
2521 // FIXME: This loop could be made faster, but it's fast enough for now.
2522 bool MadeProgress = true;
2523 std::string InGuard;
2524 while (!Defs.empty() && MadeProgress) {
2525 MadeProgress = false;
2526
2527 for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2528 I != Defs.end(); /*No step*/) {
2529 bool DependenciesSatisfied = true;
2530 for (auto *II : (*I)->getDependencies()) {
2531 if (std::find(Defs.begin(), Defs.end(), II) != Defs.end())
2532 DependenciesSatisfied = false;
2533 }
2534 if (!DependenciesSatisfied) {
2535 // Try the next one.
2536 ++I;
2537 continue;
2538 }
2539
2540 // Emit #endif/#if pair if needed.
2541 if ((*I)->getGuard() != InGuard) {
2542 if (!InGuard.empty())
2543 OS << "#endif\n";
2544 InGuard = (*I)->getGuard();
2545 if (!InGuard.empty())
2546 OS << "#if " << InGuard << "\n";
2547 }
2548
2549 // Actually generate the intrinsic code.
2550 OS << (*I)->generate();
2551
2552 MadeProgress = true;
2553 I = Defs.erase(I);
2554 }
2555 }
2556 assert(Defs.empty() && "Some requirements were not satisfied!");
2557 if (!InGuard.empty())
2558 OS << "#endif\n";
2559
2560 OS << "\n";
2561 OS << "#undef __ai\n\n";
2562 OS << "#endif /* __ARM_FP16_H */\n";
2563}
2564
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002565namespace clang {
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00002566
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002567void EmitNeon(RecordKeeper &Records, raw_ostream &OS) {
2568 NeonEmitter(Records).run(OS);
2569}
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00002570
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00002571void EmitFP16(RecordKeeper &Records, raw_ostream &OS) {
2572 NeonEmitter(Records).runFP16(OS);
2573}
2574
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002575void EmitNeonSema(RecordKeeper &Records, raw_ostream &OS) {
2576 NeonEmitter(Records).runHeader(OS);
2577}
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00002578
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002579void EmitNeonTest(RecordKeeper &Records, raw_ostream &OS) {
Craig Topper0039f3f2014-06-18 03:57:25 +00002580 llvm_unreachable("Neon test generation no longer implemented!");
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002581}
Eugene Zelenko58ab22f2016-11-29 22:44:24 +00002582
2583} // end namespace clang