Bug Summary

File:clang/utils/TableGen/MveEmitter.cpp
Warning:line 1092, column 33
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MveEmitter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/utils/TableGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/utils/TableGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen/MveEmitter.cpp
1//===- MveEmitter.cpp - Generate arm_mve.h for use with clang -*- C++ -*-=====//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This set of linked tablegen backends is responsible for emitting the bits
10// and pieces that implement <arm_mve.h>, which is defined by the ACLE standard
11// and provides a set of types and functions for (more or less) direct access
12// to the MVE instruction set, including the scalar shifts as well as the
13// vector instructions.
14//
15// MVE's standard intrinsic functions are unusual in that they have a system of
16// polymorphism. For example, the function vaddq() can behave like vaddq_u16(),
17// vaddq_f32(), vaddq_s8(), etc., depending on the types of the vector
18// arguments you give it.
19//
20// This constrains the implementation strategies. The usual approach to making
21// the user-facing functions polymorphic would be to either use
22// __attribute__((overloadable)) to make a set of vaddq() functions that are
23// all inline wrappers on the underlying clang builtins, or to define a single
24// vaddq() macro which expands to an instance of _Generic.
25//
26// The inline-wrappers approach would work fine for most intrinsics, except for
27// the ones that take an argument required to be a compile-time constant,
28// because if you wrap an inline function around a call to a builtin, the
29// constant nature of the argument is not passed through.
30//
31// The _Generic approach can be made to work with enough effort, but it takes a
32// lot of machinery, because of the design feature of _Generic that even the
33// untaken branches are required to pass all front-end validity checks such as
34// type-correctness. You can work around that by nesting further _Generics all
35// over the place to coerce things to the right type in untaken branches, but
36// what you get out is complicated, hard to guarantee its correctness, and
37// worst of all, gives _completely unreadable_ error messages if the user gets
38// the types wrong for an intrinsic call.
39//
40// Therefore, my strategy is to introduce a new __attribute__ that allows a
41// function to be mapped to a clang builtin even though it doesn't have the
42// same name, and then declare all the user-facing MVE function names with that
43// attribute, mapping each one directly to the clang builtin. And the
44// polymorphic ones have __attribute__((overloadable)) as well. So once the
45// compiler has resolved the overload, it knows the internal builtin ID of the
46// selected function, and can check the immediate arguments against that; and
47// if the user gets the types wrong in a call to a polymorphic intrinsic, they
48// get a completely clear error message showing all the declarations of that
49// function in the header file and explaining why each one doesn't fit their
50// call.
51//
52// The downside of this is that if every clang builtin has to correspond
53// exactly to a user-facing ACLE intrinsic, then you can't save work in the
54// frontend by doing it in the header file: CGBuiltin.cpp has to do the entire
55// job of converting an ACLE intrinsic call into LLVM IR. So the Tablegen
56// description for an MVE intrinsic has to contain a full description of the
57// sequence of IRBuilder calls that clang will need to make.
58//
59//===----------------------------------------------------------------------===//
60
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/StringRef.h"
63#include "llvm/ADT/StringSwitch.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/raw_ostream.h"
66#include "llvm/TableGen/Error.h"
67#include "llvm/TableGen/Record.h"
68#include "llvm/TableGen/StringToOffsetTable.h"
69#include <cassert>
70#include <cstddef>
71#include <cstdint>
72#include <list>
73#include <map>
74#include <memory>
75#include <set>
76#include <string>
77#include <vector>
78
79using namespace llvm;
80
81namespace {
82
83class MveEmitter;
84class Result;
85
86// -----------------------------------------------------------------------------
87// A system of classes to represent all the types we'll need to deal with in
88// the prototypes of intrinsics.
89//
90// Query methods include finding out the C name of a type; the "LLVM name" in
91// the sense of a C++ code snippet that can be used in the codegen function;
92// the suffix that represents the type in the ACLE intrinsic naming scheme
93// (e.g. 's32' represents int32_t in intrinsics such as vaddq_s32); whether the
94// type is floating-point related (hence should be under #ifdef in the MVE
95// header so that it isn't included in integer-only MVE mode); and the type's
96// size in bits. Not all subtypes support all these queries.
97
98class Type {
99public:
100 enum class TypeKind {
101 // Void appears as a return type (for store intrinsics, which are pure
102 // side-effect). It's also used as the parameter type in the Tablegen
103 // when an intrinsic doesn't need to come in various suffixed forms like
104 // vfooq_s8,vfooq_u16,vfooq_f32.
105 Void,
106
107 // Scalar is used for ordinary int and float types of all sizes.
108 Scalar,
109
110 // Vector is used for anything that occupies exactly one MVE vector
111 // register, i.e. {uint,int,float}NxM_t.
112 Vector,
113
114 // MultiVector is used for the {uint,int,float}NxMxK_t types used by the
115 // interleaving load/store intrinsics v{ld,st}{2,4}q.
116 MultiVector,
117
118 // Predicate is used by all the predicated intrinsics. Its C
119 // representation is mve_pred16_t (which is just an alias for uint16_t).
120 // But we give more detail here, by indicating that a given predicate
121 // instruction is logically regarded as a vector of i1 containing the
122 // same number of lanes as the input vector type. So our Predicate type
123 // comes with a lane count, which we use to decide which kind of <n x i1>
124 // we'll invoke the pred_i2v IR intrinsic to translate it into.
125 Predicate,
126
127 // Pointer is used for pointer types (obviously), and comes with a flag
128 // indicating whether it's a pointer to a const or mutable instance of
129 // the pointee type.
130 Pointer,
131 };
132
133private:
134 const TypeKind TKind;
135
136protected:
137 Type(TypeKind K) : TKind(K) {}
138
139public:
140 TypeKind typeKind() const { return TKind; }
141 virtual ~Type() = default;
142 virtual bool requiresFloat() const = 0;
143 virtual unsigned sizeInBits() const = 0;
144 virtual std::string cName() const = 0;
145 virtual std::string llvmName() const {
146 PrintFatalError("no LLVM type name available for type " + cName());
147 }
148 virtual std::string acleSuffix(std::string) const {
149 PrintFatalError("no ACLE suffix available for this type");
150 }
151};
152
153enum class ScalarTypeKind { SignedInt, UnsignedInt, Float };
154inline std::string toLetter(ScalarTypeKind kind) {
155 switch (kind) {
156 case ScalarTypeKind::SignedInt:
157 return "s";
158 case ScalarTypeKind::UnsignedInt:
159 return "u";
160 case ScalarTypeKind::Float:
161 return "f";
162 }
163 llvm_unreachable("Unhandled ScalarTypeKind enum")::llvm::llvm_unreachable_internal("Unhandled ScalarTypeKind enum"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen/MveEmitter.cpp"
, 163)
;
164}
165inline std::string toCPrefix(ScalarTypeKind kind) {
166 switch (kind) {
167 case ScalarTypeKind::SignedInt:
168 return "int";
169 case ScalarTypeKind::UnsignedInt:
170 return "uint";
171 case ScalarTypeKind::Float:
172 return "float";
173 }
174 llvm_unreachable("Unhandled ScalarTypeKind enum")::llvm::llvm_unreachable_internal("Unhandled ScalarTypeKind enum"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen/MveEmitter.cpp"
, 174)
;
175}
176
177class VoidType : public Type {
178public:
179 VoidType() : Type(TypeKind::Void) {}
180 unsigned sizeInBits() const override { return 0; }
19
Returning zero
181 bool requiresFloat() const override { return false; }
182 std::string cName() const override { return "void"; }
183
184 static bool classof(const Type *T) { return T->typeKind() == TypeKind::Void; }
185 std::string acleSuffix(std::string) const override { return ""; }
186};
187
188class PointerType : public Type {
189 const Type *Pointee;
190 bool Const;
191
192public:
193 PointerType(const Type *Pointee, bool Const)
194 : Type(TypeKind::Pointer), Pointee(Pointee), Const(Const) {}
195 unsigned sizeInBits() const override { return 32; }
196 bool requiresFloat() const override { return Pointee->requiresFloat(); }
197 std::string cName() const override {
198 std::string Name = Pointee->cName();
199
200 // The syntax for a pointer in C is different when the pointee is
201 // itself a pointer. The MVE intrinsics don't contain any double
202 // pointers, so we don't need to worry about that wrinkle.
203 assert(!isa<PointerType>(Pointee) && "Pointer to pointer not supported")((!isa<PointerType>(Pointee) && "Pointer to pointer not supported"
) ? static_cast<void> (0) : __assert_fail ("!isa<PointerType>(Pointee) && \"Pointer to pointer not supported\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen/MveEmitter.cpp"
, 203, __PRETTY_FUNCTION__))
;
204
205 if (Const)
206 Name = "const " + Name;
207 return Name + " *";
208 }
209 std::string llvmName() const override {
210 return "llvm::PointerType::getUnqual(" + Pointee->llvmName() + ")";
211 }
212
213 static bool classof(const Type *T) {
214 return T->typeKind() == TypeKind::Pointer;
215 }
216};
217
218// Base class for all the types that have a name of the form
219// [prefix][numbers]_t, like int32_t, uint16x8_t, float32x4x2_t.
220//
221// For this sub-hierarchy we invent a cNameBase() method which returns the
222// whole name except for the trailing "_t", so that Vector and MultiVector can
223// append an extra "x2" or whatever to their element type's cNameBase(). Then
224// the main cName() query method puts "_t" on the end for the final type name.
225
226class CRegularNamedType : public Type {
227 using Type::Type;
228 virtual std::string cNameBase() const = 0;
229
230public:
231 std::string cName() const override { return cNameBase() + "_t"; }
232};
233
234class ScalarType : public CRegularNamedType {
235 ScalarTypeKind Kind;
236 unsigned Bits;
237 std::string NameOverride;
238
239public:
240 ScalarType(const Record *Record) : CRegularNamedType(TypeKind::Scalar) {
241 Kind = StringSwitch<ScalarTypeKind>(Record->getValueAsString("kind"))
242 .Case("s", ScalarTypeKind::SignedInt)
243 .Case("u", ScalarTypeKind::UnsignedInt)
244 .Case("f", ScalarTypeKind::Float);
245 Bits = Record->getValueAsInt("size");
246 NameOverride = std::string(Record->getValueAsString("nameOverride"));
247 }
248 unsigned sizeInBits() const override { return Bits; }
249 ScalarTypeKind kind() const { return Kind; }
250 std::string suffix() const { return toLetter(Kind) + utostr(Bits); }
251 std::string cNameBase() const override {
252 return toCPrefix(Kind) + utostr(Bits);
253 }
254 std::string cName() const override {
255 if (NameOverride.empty())
256 return CRegularNamedType::cName();
257 return NameOverride;
258 }
259 std::string llvmName() const override {
260 if (Kind == ScalarTypeKind::Float) {
261 if (Bits == 16)
262 return "HalfTy";
263 if (Bits == 32)
264 return "FloatTy";
265 if (Bits == 64)
266 return "DoubleTy";
267 PrintFatalError("bad size for floating type");
268 }
269 return "Int" + utostr(Bits) + "Ty";
270 }
271 std::string acleSuffix(std::string overrideLetter) const override {
272 return "_" + (overrideLetter.size() ? overrideLetter : toLetter(Kind))
273 + utostr(Bits);
274 }
275 bool isInteger() const { return Kind != ScalarTypeKind::Float; }
276 bool requiresFloat() const override { return !isInteger(); }
277 bool hasNonstandardName() const { return !NameOverride.empty(); }
278
279 static bool classof(const Type *T) {
280 return T->typeKind() == TypeKind::Scalar;
281 }
282};
283
284class VectorType : public CRegularNamedType {
285 const ScalarType *Element;
286 unsigned Lanes;
287
288public:
289 VectorType(const ScalarType *Element, unsigned Lanes)
290 : CRegularNamedType(TypeKind::Vector), Element(Element), Lanes(Lanes) {}
291 unsigned sizeInBits() const override { return Lanes * Element->sizeInBits(); }
292 unsigned lanes() const { return Lanes; }
293 bool requiresFloat() const override { return Element->requiresFloat(); }
294 std::string cNameBase() const override {
295 return Element->cNameBase() + "x" + utostr(Lanes);
296 }
297 std::string llvmName() const override {
298 return "llvm::VectorType::get(" + Element->llvmName() + ", " +
299 utostr(Lanes) + ")";
300 }
301
302 static bool classof(const Type *T) {
303 return T->typeKind() == TypeKind::Vector;
304 }
305};
306
307class MultiVectorType : public CRegularNamedType {
308 const VectorType *Element;
309 unsigned Registers;
310
311public:
312 MultiVectorType(unsigned Registers, const VectorType *Element)
313 : CRegularNamedType(TypeKind::MultiVector), Element(Element),
314 Registers(Registers) {}
315 unsigned sizeInBits() const override {
316 return Registers * Element->sizeInBits();
317 }
318 unsigned registers() const { return Registers; }
319 bool requiresFloat() const override { return Element->requiresFloat(); }
320 std::string cNameBase() const override {
321 return Element->cNameBase() + "x" + utostr(Registers);
322 }
323
324 // MultiVectorType doesn't override llvmName, because we don't expect to do
325 // automatic code generation for the MVE intrinsics that use it: the {vld2,
326 // vld4, vst2, vst4} family are the only ones that use these types, so it was
327 // easier to hand-write the codegen for dealing with these structs than to
328 // build in lots of extra automatic machinery that would only be used once.
329
330 static bool classof(const Type *T) {
331 return T->typeKind() == TypeKind::MultiVector;
332 }
333};
334
335class PredicateType : public CRegularNamedType {
336 unsigned Lanes;
337
338public:
339 PredicateType(unsigned Lanes)
340 : CRegularNamedType(TypeKind::Predicate), Lanes(Lanes) {}
341 unsigned sizeInBits() const override { return 16; }
342 std::string cNameBase() const override { return "mve_pred16"; }
343 bool requiresFloat() const override { return false; };
344 std::string llvmName() const override {
345 // Use <4 x i1> instead of <2 x i1> for two-lane vector types. See
346 // the comment in llvm/lib/Target/ARM/ARMInstrMVE.td for further
347 // explanation.
348 unsigned ModifiedLanes = (Lanes == 2 ? 4 : Lanes);
349
350 return "llvm::VectorType::get(Builder.getInt1Ty(), " +
351 utostr(ModifiedLanes) + ")";
352 }
353
354 static bool classof(const Type *T) {
355 return T->typeKind() == TypeKind::Predicate;
356 }
357};
358
359// -----------------------------------------------------------------------------
360// Class to facilitate merging together the code generation for many intrinsics
361// by means of varying a few constant or type parameters.
362//
363// Most obviously, the intrinsics in a single parametrised family will have
364// code generation sequences that only differ in a type or two, e.g. vaddq_s8
365// and vaddq_u16 will look the same apart from putting a different vector type
366// in the call to CGM.getIntrinsic(). But also, completely different intrinsics
367// will often code-generate in the same way, with only a different choice of
368// _which_ IR intrinsic they lower to (e.g. vaddq_m_s8 and vmulq_m_s8), but
369// marshalling the arguments and return values of the IR intrinsic in exactly
370// the same way. And others might differ only in some other kind of constant,
371// such as a lane index.
372//
373// So, when we generate the IR-building code for all these intrinsics, we keep
374// track of every value that could possibly be pulled out of the code and
375// stored ahead of time in a local variable. Then we group together intrinsics
376// by textual equivalence of the code that would result if _all_ those
377// parameters were stored in local variables. That gives us maximal sets that
378// can be implemented by a single piece of IR-building code by changing
379// parameter values ahead of time.
380//
381// After we've done that, we do a second pass in which we only allocate _some_
382// of the parameters into local variables, by tracking which ones have the same
383// values as each other (so that a single variable can be reused) and which
384// ones are the same across the whole set (so that no variable is needed at
385// all).
386//
387// Hence the class below. Its allocParam method is invoked during code
388// generation by every method of a Result subclass (see below) that wants to
389// give it the opportunity to pull something out into a switchable parameter.
390// It returns a variable name for the parameter, or (if it's being used in the
391// second pass once we've decided that some parameters don't need to be stored
392// in variables after all) it might just return the input expression unchanged.
393
394struct CodeGenParamAllocator {
395 // Accumulated during code generation
396 std::vector<std::string> *ParamTypes = nullptr;
397 std::vector<std::string> *ParamValues = nullptr;
398
399 // Provided ahead of time in pass 2, to indicate which parameters are being
400 // assigned to what. This vector contains an entry for each call to
401 // allocParam expected during code gen (which we counted up in pass 1), and
402 // indicates the number of the parameter variable that should be returned, or
403 // -1 if this call shouldn't allocate a parameter variable at all.
404 //
405 // We rely on the recursive code generation working identically in passes 1
406 // and 2, so that the same list of calls to allocParam happen in the same
407 // order. That guarantees that the parameter numbers recorded in pass 1 will
408 // match the entries in this vector that store what MveEmitter::EmitBuiltinCG
409 // decided to do about each one in pass 2.
410 std::vector<int> *ParamNumberMap = nullptr;
411
412 // Internally track how many things we've allocated
413 unsigned nparams = 0;
414
415 std::string allocParam(StringRef Type, StringRef Value) {
416 unsigned ParamNumber;
417
418 if (!ParamNumberMap) {
419 // In pass 1, unconditionally assign a new parameter variable to every
420 // value we're asked to process.
421 ParamNumber = nparams++;
422 } else {
423 // In pass 2, consult the map provided by the caller to find out which
424 // variable we should be keeping things in.
425 int MapValue = (*ParamNumberMap)[nparams++];
426 if (MapValue < 0)
427 return std::string(Value);
428 ParamNumber = MapValue;
429 }
430
431 // If we've allocated a new parameter variable for the first time, store
432 // its type and value to be retrieved after codegen.
433 if (ParamTypes && ParamTypes->size() == ParamNumber)
434 ParamTypes->push_back(std::string(Type));
435 if (ParamValues && ParamValues->size() == ParamNumber)
436 ParamValues->push_back(std::string(Value));
437
438 // Unimaginative naming scheme for parameter variables.
439 return "Param" + utostr(ParamNumber);
440 }
441};
442
443// -----------------------------------------------------------------------------
444// System of classes that represent all the intermediate values used during
445// code-generation for an intrinsic.
446//
447// The base class 'Result' can represent a value of the LLVM type 'Value', or
448// sometimes 'Address' (for loads/stores, including an alignment requirement).
449//
450// In the case where the Tablegen provides a value in the codegen dag as a
451// plain integer literal, the Result object we construct here will be one that
452// returns true from hasIntegerConstantValue(). This allows the generated C++
453// code to use the constant directly in contexts which can take a literal
454// integer, such as Builder.CreateExtractValue(thing, 1), without going to the
455// effort of calling llvm::ConstantInt::get() and then pulling the constant
456// back out of the resulting llvm:Value later.
457
458class Result {
459public:
460 // Convenient shorthand for the pointer type we'll be using everywhere.
461 using Ptr = std::shared_ptr<Result>;
462
463private:
464 Ptr Predecessor;
465 std::string VarName;
466 bool VarNameUsed = false;
467 unsigned Visited = 0;
468
469public:
470 virtual ~Result() = default;
471 using Scope = std::map<std::string, Ptr>;
472 virtual void genCode(raw_ostream &OS, CodeGenParamAllocator &) const = 0;
473 virtual bool hasIntegerConstantValue() const { return false; }
474 virtual uint32_t integerConstantValue() const { return 0; }
475 virtual bool hasIntegerValue() const { return false; }
476 virtual std::string getIntegerValue(const std::string &) {
477 llvm_unreachable("non-working Result::getIntegerValue called")::llvm::llvm_unreachable_internal("non-working Result::getIntegerValue called"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen/MveEmitter.cpp"
, 477)
;
478 }
479 virtual std::string typeName() const { return "Value *"; }
480
481 // Mostly, when a code-generation operation has a dependency on prior
482 // operations, it's because it uses the output values of those operations as
483 // inputs. But there's one exception, which is the use of 'seq' in Tablegen
484 // to indicate that operations have to be performed in sequence regardless of
485 // whether they use each others' output values.
486 //
487 // So, the actual generation of code is done by depth-first search, using the
488 // prerequisites() method to get a list of all the other Results that have to
489 // be computed before this one. That method divides into the 'predecessor',
490 // set by setPredecessor() while processing a 'seq' dag node, and the list
491 // returned by 'morePrerequisites', which each subclass implements to return
492 // a list of the Results it uses as input to whatever its own computation is
493 // doing.
494
495 virtual void morePrerequisites(std::vector<Ptr> &output) const {}
496 std::vector<Ptr> prerequisites() const {
497 std::vector<Ptr> ToRet;
498 if (Predecessor)
499 ToRet.push_back(Predecessor);
500 morePrerequisites(ToRet);
501 return ToRet;
502 }
503
504 void setPredecessor(Ptr p) {
505 // If the user has nested one 'seq' node inside another, and this
506 // method is called on the return value of the inner 'seq' (i.e.
507 // the final item inside it), then we can't link _this_ node to p,
508 // because it already has a predecessor. Instead, walk the chain
509 // until we find the first item in the inner seq, and link that to
510 // p, so that nesting seqs has the obvious effect of linking
511 // everything together into one long sequential chain.
512 Result *r = this;
513 while (r->Predecessor)
514 r = r->Predecessor.get();
515 r->Predecessor = p;
516 }
517
518 // Each Result will be assigned a variable name in the output code, but not
519 // all those variable names will actually be used (e.g. the return value of
520 // Builder.CreateStore has void type, so nobody will want to refer to it). To
521 // prevent annoying compiler warnings, we track whether each Result's
522 // variable name was ever actually mentioned in subsequent statements, so
523 // that it can be left out of the final generated code.
524 std::string varname() {
525 VarNameUsed = true;
526 return VarName;
527 }
528 void setVarname(const StringRef s) { VarName = std::string(s); }
529 bool varnameUsed() const { return VarNameUsed; }
530
531 // Emit code to generate this result as a Value *.
532 virtual std::string asValue() {
533 return varname();
534 }
535
536 // Code generation happens in multiple passes. This method tracks whether a
537 // Result has yet been visited in a given pass, without the need for a
538 // tedious loop in between passes that goes through and resets a 'visited'
539 // flag back to false: you just set Pass=1 the first time round, and Pass=2
540 // the second time.
541 bool needsVisiting(unsigned Pass) {
542 bool ToRet = Visited < Pass;
543 Visited = Pass;
544 return ToRet;
545 }
546};
547
548// Result subclass that retrieves one of the arguments to the clang builtin
549// function. In cases where the argument has pointer type, we call
550// EmitPointerWithAlignment and store the result in a variable of type Address,
551// so that load and store IR nodes can know the right alignment. Otherwise, we
552// call EmitScalarExpr.
553//
554// There are aggregate parameters in the MVE intrinsics API, but we don't deal
555// with them in this Tablegen back end: they only arise in the vld2q/vld4q and
556// vst2q/vst4q family, which is few enough that we just write the code by hand
557// for those in CGBuiltin.cpp.
558class BuiltinArgResult : public Result {
559public:
560 unsigned ArgNum;
561 bool AddressType;
562 bool Immediate;
563 BuiltinArgResult(unsigned ArgNum, bool AddressType, bool Immediate)
564 : ArgNum(ArgNum), AddressType(AddressType), Immediate(Immediate) {}
565 void genCode(raw_ostream &OS, CodeGenParamAllocator &) const override {
566 OS << (AddressType ? "EmitPointerWithAlignment" : "EmitScalarExpr")
567 << "(E->getArg(" << ArgNum << "))";
568 }
569 std::string typeName() const override {
570 return AddressType ? "Address" : Result::typeName();
571 }
572 // Emit code to generate this result as a Value *.
573 std::string asValue() override {
574 if (AddressType)
575 return "(" + varname() + ".getPointer())";
576 return Result::asValue();
577 }
578 bool hasIntegerValue() const override { return Immediate; }
579 std::string getIntegerValue(const std::string &IntType) override {
580 return "GetIntegerConstantValue<" + IntType + ">(E->getArg(" +
581 utostr(ArgNum) + "), getContext())";
582 }
583};
584
585// Result subclass for an integer literal appearing in Tablegen. This may need
586// to be turned into an llvm::Result by means of llvm::ConstantInt::get(), or
587// it may be used directly as an integer, depending on which IRBuilder method
588// it's being passed to.
589class IntLiteralResult : public Result {
590public:
591 const ScalarType *IntegerType;
592 uint32_t IntegerValue;
593 IntLiteralResult(const ScalarType *IntegerType, uint32_t IntegerValue)
594 : IntegerType(IntegerType), IntegerValue(IntegerValue) {}
595 void genCode(raw_ostream &OS,
596 CodeGenParamAllocator &ParamAlloc) const override {
597 OS << "llvm::ConstantInt::get("
598 << ParamAlloc.allocParam("llvm::Type *", IntegerType->llvmName())
599 << ", ";
600 OS << ParamAlloc.allocParam(IntegerType->cName(), utostr(IntegerValue))
601 << ")";
602 }
603 bool hasIntegerConstantValue() const override { return true; }
604 uint32_t integerConstantValue() const override { return IntegerValue; }
605};
606
607// Result subclass representing a cast between different integer types. We use
608// our own ScalarType abstraction as the representation of the target type,
609// which gives both size and signedness.
610class IntCastResult : public Result {
611public:
612 const ScalarType *IntegerType;
613 Ptr V;
614 IntCastResult(const ScalarType *IntegerType, Ptr V)
615 : IntegerType(IntegerType), V(V) {}
616 void genCode(raw_ostream &OS,
617 CodeGenParamAllocator &ParamAlloc) const override {
618 OS << "Builder.CreateIntCast(" << V->varname() << ", "
619 << ParamAlloc.allocParam("llvm::Type *", IntegerType->llvmName()) << ", "
620 << ParamAlloc.allocParam("bool",
621 IntegerType->kind() == ScalarTypeKind::SignedInt
622 ? "true"
623 : "false")
624 << ")";
625 }
626 void morePrerequisites(std::vector<Ptr> &output) const override {
627 output.push_back(V);
628 }
629};
630
631// Result subclass representing a cast between different pointer types.
632class PointerCastResult : public Result {
633public:
634 const PointerType *PtrType;
635 Ptr V;
636 PointerCastResult(const PointerType *PtrType, Ptr V)
637 : PtrType(PtrType), V(V) {}
638 void genCode(raw_ostream &OS,
639 CodeGenParamAllocator &ParamAlloc) const override {
640 OS << "Builder.CreatePointerCast(" << V->asValue() << ", "
641 << ParamAlloc.allocParam("llvm::Type *", PtrType->llvmName()) << ")";
642 }
643 void morePrerequisites(std::vector<Ptr> &output) const override {
644 output.push_back(V);
645 }
646};
647
648// Result subclass representing a call to an IRBuilder method. Each IRBuilder
649// method we want to use will have a Tablegen record giving the method name and
650// describing any important details of how to call it, such as whether a
651// particular argument should be an integer constant instead of an llvm::Value.
652class IRBuilderResult : public Result {
653public:
654 StringRef CallPrefix;
655 std::vector<Ptr> Args;
656 std::set<unsigned> AddressArgs;
657 std::map<unsigned, std::string> IntegerArgs;
658 IRBuilderResult(StringRef CallPrefix, std::vector<Ptr> Args,
659 std::set<unsigned> AddressArgs,
660 std::map<unsigned, std::string> IntegerArgs)
661 : CallPrefix(CallPrefix), Args(Args), AddressArgs(AddressArgs),
662 IntegerArgs(IntegerArgs) {}
663 void genCode(raw_ostream &OS,
664 CodeGenParamAllocator &ParamAlloc) const override {
665 OS << CallPrefix;
666 const char *Sep = "";
667 for (unsigned i = 0, e = Args.size(); i < e; ++i) {
668 Ptr Arg = Args[i];
669 auto it = IntegerArgs.find(i);
670
671 OS << Sep;
672 Sep = ", ";
673
674 if (it != IntegerArgs.end()) {
675 if (Arg->hasIntegerConstantValue())
676 OS << "static_cast<" << it->second << ">("
677 << ParamAlloc.allocParam(it->second,
678 utostr(Arg->integerConstantValue()))
679 << ")";
680 else if (Arg->hasIntegerValue())
681 OS << ParamAlloc.allocParam(it->second,
682 Arg->getIntegerValue(it->second));
683 } else {
684 OS << Arg->varname();
685 }
686 }
687 OS << ")";
688 }
689 void morePrerequisites(std::vector<Ptr> &output) const override {
690 for (unsigned i = 0, e = Args.size(); i < e; ++i) {
691 Ptr Arg = Args[i];
692 if (IntegerArgs.find(i) != IntegerArgs.end())
693 continue;
694 output.push_back(Arg);
695 }
696 }
697};
698
699// Result subclass representing making an Address out of a Value.
700class AddressResult : public Result {
701public:
702 Ptr Arg;
703 unsigned Align;
704 AddressResult(Ptr Arg, unsigned Align) : Arg(Arg), Align(Align) {}
705 void genCode(raw_ostream &OS,
706 CodeGenParamAllocator &ParamAlloc) const override {
707 OS << "Address(" << Arg->varname() << ", CharUnits::fromQuantity("
708 << Align << "))";
709 }
710 std::string typeName() const override {
711 return "Address";
712 }
713 void morePrerequisites(std::vector<Ptr> &output) const override {
714 output.push_back(Arg);
715 }
716};
717
718// Result subclass representing a call to an IR intrinsic, which we first have
719// to look up using an Intrinsic::ID constant and an array of types.
720class IRIntrinsicResult : public Result {
721public:
722 std::string IntrinsicID;
723 std::vector<const Type *> ParamTypes;
724 std::vector<Ptr> Args;
725 IRIntrinsicResult(StringRef IntrinsicID, std::vector<const Type *> ParamTypes,
726 std::vector<Ptr> Args)
727 : IntrinsicID(std::string(IntrinsicID)), ParamTypes(ParamTypes),
728 Args(Args) {}
729 void genCode(raw_ostream &OS,
730 CodeGenParamAllocator &ParamAlloc) const override {
731 std::string IntNo = ParamAlloc.allocParam(
732 "Intrinsic::ID", "Intrinsic::" + IntrinsicID);
733 OS << "Builder.CreateCall(CGM.getIntrinsic(" << IntNo;
734 if (!ParamTypes.empty()) {
735 OS << ", llvm::SmallVector<llvm::Type *, " << ParamTypes.size() << "> {";
736 const char *Sep = "";
737 for (auto T : ParamTypes) {
738 OS << Sep << ParamAlloc.allocParam("llvm::Type *", T->llvmName());
739 Sep = ", ";
740 }
741 OS << "}";
742 }
743 OS << "), llvm::SmallVector<Value *, " << Args.size() << "> {";
744 const char *Sep = "";
745 for (auto Arg : Args) {
746 OS << Sep << Arg->asValue();
747 Sep = ", ";
748 }
749 OS << "})";
750 }
751 void morePrerequisites(std::vector<Ptr> &output) const override {
752 output.insert(output.end(), Args.begin(), Args.end());
753 }
754};
755
756// Result subclass that specifies a type, for use in IRBuilder operations such
757// as CreateBitCast that take a type argument.
758class TypeResult : public Result {
759public:
760 const Type *T;
761 TypeResult(const Type *T) : T(T) {}
762 void genCode(raw_ostream &OS, CodeGenParamAllocator &) const override {
763 OS << T->llvmName();
764 }
765 std::string typeName() const override {
766 return "llvm::Type *";
767 }
768};
769
770// -----------------------------------------------------------------------------
771// Class that describes a single ACLE intrinsic.
772//
773// A Tablegen record will typically describe more than one ACLE intrinsic, by
774// means of setting the 'list<Type> Params' field to a list of multiple
775// parameter types, so as to define vaddq_{s8,u8,...,f16,f32} all in one go.
776// We'll end up with one instance of ACLEIntrinsic for *each* parameter type,
777// rather than a single one for all of them. Hence, the constructor takes both
778// a Tablegen record and the current value of the parameter type.
779
780class ACLEIntrinsic {
781 // Structure documenting that one of the intrinsic's arguments is required to
782 // be a compile-time constant integer, and what constraints there are on its
783 // value. Used when generating Sema checking code.
784 struct ImmediateArg {
785 enum class BoundsType { ExplicitRange, UInt };
786 BoundsType boundsType;
787 int64_t i1, i2;
788 StringRef ExtraCheckType, ExtraCheckArgs;
789 const Type *ArgType;
790 };
791
792 // For polymorphic intrinsics, FullName is the explicit name that uniquely
793 // identifies this variant of the intrinsic, and ShortName is the name it
794 // shares with at least one other intrinsic.
795 std::string ShortName, FullName;
796
797 // A very small number of intrinsics _only_ have a polymorphic
798 // variant (vuninitializedq taking an unevaluated argument).
799 bool PolymorphicOnly;
800
801 // Another rarely-used flag indicating that the builtin doesn't
802 // evaluate its argument(s) at all.
803 bool NonEvaluating;
804
805 const Type *ReturnType;
806 std::vector<const Type *> ArgTypes;
807 std::map<unsigned, ImmediateArg> ImmediateArgs;
808 Result::Ptr Code;
809
810 std::map<std::string, std::string> CustomCodeGenArgs;
811
812 // Recursive function that does the internals of code generation.
813 void genCodeDfs(Result::Ptr V, std::list<Result::Ptr> &Used,
814 unsigned Pass) const {
815 if (!V->needsVisiting(Pass))
816 return;
817
818 for (Result::Ptr W : V->prerequisites())
819 genCodeDfs(W, Used, Pass);
820
821 Used.push_back(V);
822 }
823
824public:
825 const std::string &shortName() const { return ShortName; }
826 const std::string &fullName() const { return FullName; }
827 const Type *returnType() const { return ReturnType; }
828 const std::vector<const Type *> &argTypes() const { return ArgTypes; }
829 bool requiresFloat() const {
830 if (ReturnType->requiresFloat())
831 return true;
832 for (const Type *T : ArgTypes)
833 if (T->requiresFloat())
834 return true;
835 return false;
836 }
837 bool polymorphic() const { return ShortName != FullName; }
838 bool polymorphicOnly() const { return PolymorphicOnly; }
839 bool nonEvaluating() const { return NonEvaluating; }
840
841 // External entry point for code generation, called from MveEmitter.
842 void genCode(raw_ostream &OS, CodeGenParamAllocator &ParamAlloc,
843 unsigned Pass) const {
844 if (!hasCode()) {
845 for (auto kv : CustomCodeGenArgs)
846 OS << " " << kv.first << " = " << kv.second << ";\n";
847 OS << " break; // custom code gen\n";
848 return;
849 }
850 std::list<Result::Ptr> Used;
851 genCodeDfs(Code, Used, Pass);
852
853 unsigned varindex = 0;
854 for (Result::Ptr V : Used)
855 if (V->varnameUsed())
856 V->setVarname("Val" + utostr(varindex++));
857
858 for (Result::Ptr V : Used) {
859 OS << " ";
860 if (V == Used.back()) {
861 assert(!V->varnameUsed())((!V->varnameUsed()) ? static_cast<void> (0) : __assert_fail
("!V->varnameUsed()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen/MveEmitter.cpp"
, 861, __PRETTY_FUNCTION__))
;
862 OS << "return "; // FIXME: what if the top-level thing is void?
863 } else if (V->varnameUsed()) {
864 std::string Type = V->typeName();
865 OS << V->typeName();
866 if (!StringRef(Type).endswith("*"))
867 OS << " ";
868 OS << V->varname() << " = ";
869 }
870 V->genCode(OS, ParamAlloc);
871 OS << ";\n";
872 }
873 }
874 bool hasCode() const { return Code != nullptr; }
875
876 static std::string signedHexLiteral(const llvm::APInt &iOrig) {
877 llvm::APInt i = iOrig.trunc(64);
878 SmallString<40> s;
879 i.toString(s, 16, true, true);
880 return std::string(s.str());
881 }
882
883 std::string genSema() const {
884 std::vector<std::string> SemaChecks;
885
886 for (const auto &kv : ImmediateArgs) {
887 const ImmediateArg &IA = kv.second;
888
889 llvm::APInt lo(128, 0), hi(128, 0);
890 switch (IA.boundsType) {
891 case ImmediateArg::BoundsType::ExplicitRange:
892 lo = IA.i1;
893 hi = IA.i2;
894 break;
895 case ImmediateArg::BoundsType::UInt:
896 lo = 0;
897 hi = llvm::APInt::getMaxValue(IA.i1).zext(128);
898 break;
899 }
900
901 std::string Index = utostr(kv.first);
902
903 // Emit a range check if the legal range of values for the
904 // immediate is smaller than the _possible_ range of values for
905 // its type.
906 unsigned ArgTypeBits = IA.ArgType->sizeInBits();
907 llvm::APInt ArgTypeRange = llvm::APInt::getMaxValue(ArgTypeBits).zext(128);
908 llvm::APInt ActualRange = (hi-lo).trunc(64).sext(128);
909 if (ActualRange.ult(ArgTypeRange))
910 SemaChecks.push_back("SemaBuiltinConstantArgRange(TheCall, " + Index +
911 ", " + signedHexLiteral(lo) + ", " +
912 signedHexLiteral(hi) + ")");
913
914 if (!IA.ExtraCheckType.empty()) {
915 std::string Suffix;
916 if (!IA.ExtraCheckArgs.empty()) {
917 std::string tmp;
918 StringRef Arg = IA.ExtraCheckArgs;
919 if (Arg == "!lanesize") {
920 tmp = utostr(IA.ArgType->sizeInBits());
921 Arg = tmp;
922 }
923 Suffix = (Twine(", ") + Arg).str();
924 }
925 SemaChecks.push_back((Twine("SemaBuiltinConstantArg") +
926 IA.ExtraCheckType + "(TheCall, " + Index +
927 Suffix + ")")
928 .str());
929 }
930
931 assert(!SemaChecks.empty())((!SemaChecks.empty()) ? static_cast<void> (0) : __assert_fail
("!SemaChecks.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/utils/TableGen/MveEmitter.cpp"
, 931, __PRETTY_FUNCTION__))
;
932 }
933 if (SemaChecks.empty())
934 return "";
935 return (Twine(" return ") +
936 join(std::begin(SemaChecks), std::end(SemaChecks),
937 " ||\n ") +
938 ";\n")
939 .str();
940 }
941
942 ACLEIntrinsic(MveEmitter &ME, Record *R, const Type *Param);
943};
944
945// -----------------------------------------------------------------------------
946// The top-level class that holds all the state from analyzing the entire
947// Tablegen input.
948
949class MveEmitter {
950 // MveEmitter holds a collection of all the types we've instantiated.
951 VoidType Void;
952 std::map<std::string, std::unique_ptr<ScalarType>> ScalarTypes;
953 std::map<std::tuple<ScalarTypeKind, unsigned, unsigned>,
954 std::unique_ptr<VectorType>>
955 VectorTypes;
956 std::map<std::pair<std::string, unsigned>, std::unique_ptr<MultiVectorType>>
957 MultiVectorTypes;
958 std::map<unsigned, std::unique_ptr<PredicateType>> PredicateTypes;
959 std::map<std::string, std::unique_ptr<PointerType>> PointerTypes;
960
961 // And all the ACLEIntrinsic instances we've created.
962 std::map<std::string, std::unique_ptr<ACLEIntrinsic>> ACLEIntrinsics;
963
964public:
965 // Methods to create a Type object, or return the right existing one from the
966 // maps stored in this object.
967 const VoidType *getVoidType() { return &Void; }
968 const ScalarType *getScalarType(StringRef Name) {
969 return ScalarTypes[std::string(Name)].get();
970 }
971 const ScalarType *getScalarType(Record *R) {
972 return getScalarType(R->getName());
973 }
974 const VectorType *getVectorType(const ScalarType *ST, unsigned Lanes) {
975 std::tuple<ScalarTypeKind, unsigned, unsigned> key(ST->kind(),
976 ST->sizeInBits(), Lanes);
977 if (VectorTypes.find(key) == VectorTypes.end())
978 VectorTypes[key] = std::make_unique<VectorType>(ST, Lanes);
979 return VectorTypes[key].get();
980 }
981 const VectorType *getVectorType(const ScalarType *ST) {
982 return getVectorType(ST, 128 / ST->sizeInBits());
983 }
984 const MultiVectorType *getMultiVectorType(unsigned Registers,
985 const VectorType *VT) {
986 std::pair<std::string, unsigned> key(VT->cNameBase(), Registers);
987 if (MultiVectorTypes.find(key) == MultiVectorTypes.end())
988 MultiVectorTypes[key] = std::make_unique<MultiVectorType>(Registers, VT);
989 return MultiVectorTypes[key].get();
990 }
991 const PredicateType *getPredicateType(unsigned Lanes) {
992 unsigned key = Lanes;
993 if (PredicateTypes.find(key) == PredicateTypes.end())
994 PredicateTypes[key] = std::make_unique<PredicateType>(Lanes);
995 return PredicateTypes[key].get();
996 }
997 const PointerType *getPointerType(const Type *T, bool Const) {
998 PointerType PT(T, Const);
999 std::string key = PT.cName();
1000 if (PointerTypes.find(key) == PointerTypes.end())
1001 PointerTypes[key] = std::make_unique<PointerType>(PT);
1002 return PointerTypes[key].get();
1003 }
1004
1005 // Methods to construct a type from various pieces of Tablegen. These are
1006 // always called in the context of setting up a particular ACLEIntrinsic, so
1007 // there's always an ambient parameter type (because we're iterating through
1008 // the Params list in the Tablegen record for the intrinsic), which is used
1009 // to expand Tablegen classes like 'Vector' which mean something different in
1010 // each member of a parametric family.
1011 const Type *getType(Record *R, const Type *Param);
1012 const Type *getType(DagInit *D, const Type *Param);
1013 const Type *getType(Init *I, const Type *Param);
1014
1015 // Functions that translate the Tablegen representation of an intrinsic's
1016 // code generation into a collection of Value objects (which will then be
1017 // reprocessed to read out the actual C++ code included by CGBuiltin.cpp).
1018 Result::Ptr getCodeForDag(DagInit *D, const Result::Scope &Scope,
1019 const Type *Param);
1020 Result::Ptr getCodeForDagArg(DagInit *D, unsigned ArgNum,
1021 const Result::Scope &Scope, const Type *Param);
1022 Result::Ptr getCodeForArg(unsigned ArgNum, const Type *ArgType, bool Promote,
1023 bool Immediate);
1024
1025 // Constructor and top-level functions.
1026
1027 MveEmitter(RecordKeeper &Records);
1028
1029 void EmitHeader(raw_ostream &OS);
1030 void EmitBuiltinDef(raw_ostream &OS);
1031 void EmitBuiltinSema(raw_ostream &OS);
1032 void EmitBuiltinCG(raw_ostream &OS);
1033 void EmitBuiltinAliases(raw_ostream &OS);
1034};
1035
1036const Type *MveEmitter::getType(Init *I, const Type *Param) {
1037 if (auto Dag = dyn_cast<DagInit>(I))
1038 return getType(Dag, Param);
1039 if (auto Def = dyn_cast<DefInit>(I))
1040 return getType(Def->getDef(), Param);
1041
1042 PrintFatalError("Could not convert this value into a type");
1043}
1044
1045const Type *MveEmitter::getType(Record *R, const Type *Param) {
1046 // Pass to a subfield of any wrapper records. We don't expect more than one
1047 // of these: immediate operands are used as plain numbers rather than as
1048 // llvm::Value, so it's meaningless to promote their type anyway.
1049 if (R->isSubClassOf("Immediate"))
3
Taking false branch
1050 R = R->getValueAsDef("type");
1051 else if (R->isSubClassOf("unpromoted"))
4
Taking false branch
1052 R = R->getValueAsDef("underlying_type");
1053
1054 if (R->getName() == "Void")
5
Assuming the condition is false
6
Taking false branch
1055 return getVoidType();
1056 if (R->isSubClassOf("PrimitiveType"))
7
Taking false branch
1057 return getScalarType(R);
1058 if (R->isSubClassOf("ComplexType"))
8
Taking true branch
1059 return getType(R->getValueAsDag("spec"), Param);
9
Calling 'MveEmitter::getType'
1060
1061 PrintFatalError(R->getLoc(), "Could not convert this record into a type");
1062}
1063
1064const Type *MveEmitter::getType(DagInit *D, const Type *Param) {
1065 // The meat of the getType system: types in the Tablegen are represented by a
1066 // dag whose operators select sub-cases of this function.
1067
1068 Record *Op = cast<DefInit>(D->getOperator())->getDef();
10
The object is a 'DefInit'
1069 if (!Op->isSubClassOf("ComplexTypeOp"))
11
Taking false branch
1070 PrintFatalError(
1071 "Expected ComplexTypeOp as dag operator in type expression");
1072
1073 if (Op->getName() == "CTO_Parameter") {
12
Assuming the condition is false
13
Taking false branch
1074 if (isa<VoidType>(Param))
1075 PrintFatalError("Parametric type in unparametrised context");
1076 return Param;
1077 }
1078
1079 if (Op->getName() == "CTO_Vec") {
14
Assuming the condition is false
15
Taking false branch
1080 const Type *Element = getType(D->getArg(0), Param);
1081 if (D->getNumArgs() == 1) {
1082 return getVectorType(cast<ScalarType>(Element));
1083 } else {
1084 const Type *ExistingVector = getType(D->getArg(1), Param);
1085 return getVectorType(cast<ScalarType>(Element),
1086 cast<VectorType>(ExistingVector)->lanes());
1087 }
1088 }
1089
1090 if (Op->getName() == "CTO_Pred") {
16
Assuming the condition is true
17
Taking true branch
1091 const Type *Element = getType(D->getArg(0), Param);
1092 return getPredicateType(128 / Element->sizeInBits());
18
Calling 'VoidType::sizeInBits'
20
Returning from 'VoidType::sizeInBits'
21
Division by zero
1093 }
1094
1095 if (Op->isSubClassOf("CTO_Tuple")) {
1096 unsigned Registers = Op->getValueAsInt("n");
1097 const Type *Element = getType(D->getArg(0), Param);
1098 return getMultiVectorType(Registers, cast<VectorType>(Element));
1099 }
1100
1101 if (Op->isSubClassOf("CTO_Pointer")) {
1102 const Type *Pointee = getType(D->getArg(0), Param);
1103 return getPointerType(Pointee, Op->getValueAsBit("const"));
1104 }
1105
1106 if (Op->getName() == "CTO_CopyKind") {
1107 const ScalarType *STSize = cast<ScalarType>(getType(D->getArg(0), Param));
1108 const ScalarType *STKind = cast<ScalarType>(getType(D->getArg(1), Param));
1109 for (const auto &kv : ScalarTypes) {
1110 const ScalarType *RT = kv.second.get();
1111 if (RT->kind() == STKind->kind() && RT->sizeInBits() == STSize->sizeInBits())
1112 return RT;
1113 }
1114 PrintFatalError("Cannot find a type to satisfy CopyKind");
1115 }
1116
1117 if (Op->isSubClassOf("CTO_ScaleSize")) {
1118 const ScalarType *STKind = cast<ScalarType>(getType(D->getArg(0), Param));
1119 int Num = Op->getValueAsInt("num"), Denom = Op->getValueAsInt("denom");
1120 unsigned DesiredSize = STKind->sizeInBits() * Num / Denom;
1121 for (const auto &kv : ScalarTypes) {
1122 const ScalarType *RT = kv.second.get();
1123 if (RT->kind() == STKind->kind() && RT->sizeInBits() == DesiredSize)
1124 return RT;
1125 }
1126 PrintFatalError("Cannot find a type to satisfy ScaleSize");
1127 }
1128
1129 PrintFatalError("Bad operator in type dag expression");
1130}
1131
1132Result::Ptr MveEmitter::getCodeForDag(DagInit *D, const Result::Scope &Scope,
1133 const Type *Param) {
1134 Record *Op = cast<DefInit>(D->getOperator())->getDef();
1135
1136 if (Op->getName() == "seq") {
1137 Result::Scope SubScope = Scope;
1138 Result::Ptr PrevV = nullptr;
1139 for (unsigned i = 0, e = D->getNumArgs(); i < e; ++i) {
1140 // We don't use getCodeForDagArg here, because the argument name
1141 // has different semantics in a seq
1142 Result::Ptr V =
1143 getCodeForDag(cast<DagInit>(D->getArg(i)), SubScope, Param);
1144 StringRef ArgName = D->getArgNameStr(i);
1145 if (!ArgName.empty())
1146 SubScope[std::string(ArgName)] = V;
1147 if (PrevV)
1148 V->setPredecessor(PrevV);
1149 PrevV = V;
1150 }
1151 return PrevV;
1152 } else if (Op->isSubClassOf("Type")) {
1153 if (D->getNumArgs() != 1)
1154 PrintFatalError("Type casts should have exactly one argument");
1155 const Type *CastType = getType(Op, Param);
1156 Result::Ptr Arg = getCodeForDagArg(D, 0, Scope, Param);
1157 if (const auto *ST = dyn_cast<ScalarType>(CastType)) {
1158 if (!ST->requiresFloat()) {
1159 if (Arg->hasIntegerConstantValue())
1160 return std::make_shared<IntLiteralResult>(
1161 ST, Arg->integerConstantValue());
1162 else
1163 return std::make_shared<IntCastResult>(ST, Arg);
1164 }
1165 } else if (const auto *PT = dyn_cast<PointerType>(CastType)) {
1166 return std::make_shared<PointerCastResult>(PT, Arg);
1167 }
1168 PrintFatalError("Unsupported type cast");
1169 } else if (Op->getName() == "address") {
1170 if (D->getNumArgs() != 2)
1171 PrintFatalError("'address' should have two arguments");
1172 Result::Ptr Arg = getCodeForDagArg(D, 0, Scope, Param);
1173 unsigned Alignment;
1174 if (auto *II = dyn_cast<IntInit>(D->getArg(1))) {
1175 Alignment = II->getValue();
1176 } else {
1177 PrintFatalError("'address' alignment argument should be an integer");
1178 }
1179 return std::make_shared<AddressResult>(Arg, Alignment);
1180 } else if (Op->getName() == "unsignedflag") {
1181 if (D->getNumArgs() != 1)
1182 PrintFatalError("unsignedflag should have exactly one argument");
1183 Record *TypeRec = cast<DefInit>(D->getArg(0))->getDef();
1184 if (!TypeRec->isSubClassOf("Type"))
1185 PrintFatalError("unsignedflag's argument should be a type");
1186 if (const auto *ST = dyn_cast<ScalarType>(getType(TypeRec, Param))) {
1187 return std::make_shared<IntLiteralResult>(
1188 getScalarType("u32"), ST->kind() == ScalarTypeKind::UnsignedInt);
1189 } else {
1190 PrintFatalError("unsignedflag's argument should be a scalar type");
1191 }
1192 } else if (Op->getName() == "bitsize") {
1193 if (D->getNumArgs() != 1)
1194 PrintFatalError("bitsize should have exactly one argument");
1195 Record *TypeRec = cast<DefInit>(D->getArg(0))->getDef();
1196 if (!TypeRec->isSubClassOf("Type"))
1197 PrintFatalError("bitsize's argument should be a type");
1198 if (const auto *ST = dyn_cast<ScalarType>(getType(TypeRec, Param))) {
1199 return std::make_shared<IntLiteralResult>(getScalarType("u32"),
1200 ST->sizeInBits());
1201 } else {
1202 PrintFatalError("bitsize's argument should be a scalar type");
1203 }
1204 } else {
1205 std::vector<Result::Ptr> Args;
1206 for (unsigned i = 0, e = D->getNumArgs(); i < e; ++i)
1207 Args.push_back(getCodeForDagArg(D, i, Scope, Param));
1208 if (Op->isSubClassOf("IRBuilderBase")) {
1209 std::set<unsigned> AddressArgs;
1210 std::map<unsigned, std::string> IntegerArgs;
1211 for (Record *sp : Op->getValueAsListOfDefs("special_params")) {
1212 unsigned Index = sp->getValueAsInt("index");
1213 if (sp->isSubClassOf("IRBuilderAddrParam")) {
1214 AddressArgs.insert(Index);
1215 } else if (sp->isSubClassOf("IRBuilderIntParam")) {
1216 IntegerArgs[Index] = std::string(sp->getValueAsString("type"));
1217 }
1218 }
1219 return std::make_shared<IRBuilderResult>(Op->getValueAsString("prefix"),
1220 Args, AddressArgs, IntegerArgs);
1221 } else if (Op->isSubClassOf("IRIntBase")) {
1222 std::vector<const Type *> ParamTypes;
1223 for (Record *RParam : Op->getValueAsListOfDefs("params"))
1224 ParamTypes.push_back(getType(RParam, Param));
1225 std::string IntName = std::string(Op->getValueAsString("intname"));
1226 if (Op->getValueAsBit("appendKind"))
1227 IntName += "_" + toLetter(cast<ScalarType>(Param)->kind());
1228 return std::make_shared<IRIntrinsicResult>(IntName, ParamTypes, Args);
1229 } else {
1230 PrintFatalError("Unsupported dag node " + Op->getName());
1231 }
1232 }
1233}
1234
1235Result::Ptr MveEmitter::getCodeForDagArg(DagInit *D, unsigned ArgNum,
1236 const Result::Scope &Scope,
1237 const Type *Param) {
1238 Init *Arg = D->getArg(ArgNum);
1239 StringRef Name = D->getArgNameStr(ArgNum);
1240
1241 if (!Name.empty()) {
1242 if (!isa<UnsetInit>(Arg))
1243 PrintFatalError(
1244 "dag operator argument should not have both a value and a name");
1245 auto it = Scope.find(std::string(Name));
1246 if (it == Scope.end())
1247 PrintFatalError("unrecognized variable name '" + Name + "'");
1248 return it->second;
1249 }
1250
1251 if (auto *II = dyn_cast<IntInit>(Arg))
1252 return std::make_shared<IntLiteralResult>(getScalarType("u32"),
1253 II->getValue());
1254
1255 if (auto *DI = dyn_cast<DagInit>(Arg))
1256 return getCodeForDag(DI, Scope, Param);
1257
1258 if (auto *DI = dyn_cast<DefInit>(Arg)) {
1259 Record *Rec = DI->getDef();
1260 if (Rec->isSubClassOf("Type")) {
1261 const Type *T = getType(Rec, Param);
1262 return std::make_shared<TypeResult>(T);
1263 }
1264 }
1265
1266 PrintFatalError("bad dag argument type for code generation");
1267}
1268
1269Result::Ptr MveEmitter::getCodeForArg(unsigned ArgNum, const Type *ArgType,
1270 bool Promote, bool Immediate) {
1271 Result::Ptr V = std::make_shared<BuiltinArgResult>(
1272 ArgNum, isa<PointerType>(ArgType), Immediate);
1273
1274 if (Promote) {
1275 if (const auto *ST = dyn_cast<ScalarType>(ArgType)) {
1276 if (ST->isInteger() && ST->sizeInBits() < 32)
1277 V = std::make_shared<IntCastResult>(getScalarType("u32"), V);
1278 } else if (const auto *PT = dyn_cast<PredicateType>(ArgType)) {
1279 V = std::make_shared<IntCastResult>(getScalarType("u32"), V);
1280 V = std::make_shared<IRIntrinsicResult>("arm_mve_pred_i2v",
1281 std::vector<const Type *>{PT},
1282 std::vector<Result::Ptr>{V});
1283 }
1284 }
1285
1286 return V;
1287}
1288
1289ACLEIntrinsic::ACLEIntrinsic(MveEmitter &ME, Record *R, const Type *Param)
1290 : ReturnType(ME.getType(R->getValueAsDef("ret"), Param)) {
1291 // Derive the intrinsic's full name, by taking the name of the
1292 // Tablegen record (or override) and appending the suffix from its
1293 // parameter type. (If the intrinsic is unparametrised, its
1294 // parameter type will be given as Void, which returns the empty
1295 // string for acleSuffix.)
1296 StringRef BaseName =
1297 (R->isSubClassOf("NameOverride") ? R->getValueAsString("basename")
1298 : R->getName());
1299 StringRef overrideLetter = R->getValueAsString("overrideKindLetter");
1300 FullName =
1301 (Twine(BaseName) + Param->acleSuffix(std::string(overrideLetter))).str();
1302
1303 // Derive the intrinsic's polymorphic name, by removing components from the
1304 // full name as specified by its 'pnt' member ('polymorphic name type'),
1305 // which indicates how many type suffixes to remove, and any other piece of
1306 // the name that should be removed.
1307 Record *PolymorphicNameType = R->getValueAsDef("pnt");
1308 SmallVector<StringRef, 8> NameParts;
1309 StringRef(FullName).split(NameParts, '_');
1310 for (unsigned i = 0, e = PolymorphicNameType->getValueAsInt(
1311 "NumTypeSuffixesToDiscard");
1312 i < e; ++i)
1313 NameParts.pop_back();
1314 if (!PolymorphicNameType->isValueUnset("ExtraSuffixToDiscard")) {
1315 StringRef ExtraSuffix =
1316 PolymorphicNameType->getValueAsString("ExtraSuffixToDiscard");
1317 auto it = NameParts.end();
1318 while (it != NameParts.begin()) {
1319 --it;
1320 if (*it == ExtraSuffix) {
1321 NameParts.erase(it);
1322 break;
1323 }
1324 }
1325 }
1326 ShortName = join(std::begin(NameParts), std::end(NameParts), "_");
1327
1328 PolymorphicOnly = R->getValueAsBit("polymorphicOnly");
1329 NonEvaluating = R->getValueAsBit("nonEvaluating");
1330
1331 // Process the intrinsic's argument list.
1332 DagInit *ArgsDag = R->getValueAsDag("args");
1333 Result::Scope Scope;
1334 for (unsigned i = 0, e = ArgsDag->getNumArgs(); i < e; ++i) {
1335 Init *TypeInit = ArgsDag->getArg(i);
1336
1337 bool Promote = true;
1338 if (auto TypeDI = dyn_cast<DefInit>(TypeInit))
1339 if (TypeDI->getDef()->isSubClassOf("unpromoted"))
1340 Promote = false;
1341
1342 // Work out the type of the argument, for use in the function prototype in
1343 // the header file.
1344 const Type *ArgType = ME.getType(TypeInit, Param);
1345 ArgTypes.push_back(ArgType);
1346
1347 // If the argument is a subclass of Immediate, record the details about
1348 // what values it can take, for Sema checking.
1349 bool Immediate = false;
1350 if (auto TypeDI = dyn_cast<DefInit>(TypeInit)) {
1351 Record *TypeRec = TypeDI->getDef();
1352 if (TypeRec->isSubClassOf("Immediate")) {
1353 Immediate = true;
1354
1355 Record *Bounds = TypeRec->getValueAsDef("bounds");
1356 ImmediateArg &IA = ImmediateArgs[i];
1357 if (Bounds->isSubClassOf("IB_ConstRange")) {
1358 IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1359 IA.i1 = Bounds->getValueAsInt("lo");
1360 IA.i2 = Bounds->getValueAsInt("hi");
1361 } else if (Bounds->getName() == "IB_UEltValue") {
1362 IA.boundsType = ImmediateArg::BoundsType::UInt;
1363 IA.i1 = Param->sizeInBits();
1364 } else if (Bounds->getName() == "IB_LaneIndex") {
1365 IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1366 IA.i1 = 0;
1367 IA.i2 = 128 / Param->sizeInBits() - 1;
1368 } else if (Bounds->isSubClassOf("IB_EltBit")) {
1369 IA.boundsType = ImmediateArg::BoundsType::ExplicitRange;
1370 IA.i1 = Bounds->getValueAsInt("base");
1371 const Type *T = ME.getType(Bounds->getValueAsDef("type"), Param);
1372 IA.i2 = IA.i1 + T->sizeInBits() - 1;
1373 } else {
1374 PrintFatalError("unrecognised ImmediateBounds subclass");
1375 }
1376
1377 IA.ArgType = ArgType;
1378
1379 if (!TypeRec->isValueUnset("extra")) {
1380 IA.ExtraCheckType = TypeRec->getValueAsString("extra");
1381 if (!TypeRec->isValueUnset("extraarg"))
1382 IA.ExtraCheckArgs = TypeRec->getValueAsString("extraarg");
1383 }
1384 }
1385 }
1386
1387 // The argument will usually have a name in the arguments dag, which goes
1388 // into the variable-name scope that the code gen will refer to.
1389 StringRef ArgName = ArgsDag->getArgNameStr(i);
1390 if (!ArgName.empty())
1391 Scope[std::string(ArgName)] =
1392 ME.getCodeForArg(i, ArgType, Promote, Immediate);
1393 }
1394
1395 // Finally, go through the codegen dag and translate it into a Result object
1396 // (with an arbitrary DAG of depended-on Results hanging off it).
1397 DagInit *CodeDag = R->getValueAsDag("codegen");
1398 Record *MainOp = cast<DefInit>(CodeDag->getOperator())->getDef();
1399 if (MainOp->isSubClassOf("CustomCodegen")) {
1400 // Or, if it's the special case of CustomCodegen, just accumulate
1401 // a list of parameters we're going to assign to variables before
1402 // breaking from the loop.
1403 CustomCodeGenArgs["CustomCodeGenType"] =
1404 (Twine("CustomCodeGen::") + MainOp->getValueAsString("type")).str();
1405 for (unsigned i = 0, e = CodeDag->getNumArgs(); i < e; ++i) {
1406 StringRef Name = CodeDag->getArgNameStr(i);
1407 if (Name.empty()) {
1408 PrintFatalError("Operands to CustomCodegen should have names");
1409 } else if (auto *II = dyn_cast<IntInit>(CodeDag->getArg(i))) {
1410 CustomCodeGenArgs[std::string(Name)] = itostr(II->getValue());
1411 } else if (auto *SI = dyn_cast<StringInit>(CodeDag->getArg(i))) {
1412 CustomCodeGenArgs[std::string(Name)] = std::string(SI->getValue());
1413 } else {
1414 PrintFatalError("Operands to CustomCodegen should be integers");
1415 }
1416 }
1417 } else {
1418 Code = ME.getCodeForDag(CodeDag, Scope, Param);
1419 }
1420}
1421
1422MveEmitter::MveEmitter(RecordKeeper &Records) {
1423 // Construct the whole MveEmitter.
1424
1425 // First, look up all the instances of PrimitiveType. This gives us the list
1426 // of vector typedefs we have to put in arm_mve.h, and also allows us to
1427 // collect all the useful ScalarType instances into a big list so that we can
1428 // use it for operations such as 'find the unsigned version of this signed
1429 // integer type'.
1430 for (Record *R : Records.getAllDerivedDefinitions("PrimitiveType"))
1431 ScalarTypes[std::string(R->getName())] = std::make_unique<ScalarType>(R);
1432
1433 // Now go through the instances of Intrinsic, and for each one, iterate
1434 // through its list of type parameters making an ACLEIntrinsic for each one.
1435 for (Record *R : Records.getAllDerivedDefinitions("Intrinsic")) {
1436 for (Record *RParam : R->getValueAsListOfDefs("params")) {
1437 const Type *Param = getType(RParam, getVoidType());
2
Calling 'MveEmitter::getType'
1438 auto Intrinsic = std::make_unique<ACLEIntrinsic>(*this, R, Param);
1439 ACLEIntrinsics[Intrinsic->fullName()] = std::move(Intrinsic);
1440 }
1441 }
1442}
1443
1444/// A wrapper on raw_string_ostream that contains its own buffer rather than
1445/// having to point it at one elsewhere. (In other words, it works just like
1446/// std::ostringstream; also, this makes it convenient to declare a whole array
1447/// of them at once.)
1448///
1449/// We have to set this up using multiple inheritance, to ensure that the
1450/// string member has been constructed before raw_string_ostream's constructor
1451/// is given a pointer to it.
1452class string_holder {
1453protected:
1454 std::string S;
1455};
1456class raw_self_contained_string_ostream : private string_holder,
1457 public raw_string_ostream {
1458public:
1459 raw_self_contained_string_ostream()
1460 : string_holder(), raw_string_ostream(S) {}
1461};
1462
1463void MveEmitter::EmitHeader(raw_ostream &OS) {
1464 // Accumulate pieces of the header file that will be enabled under various
1465 // different combinations of #ifdef. The index into parts[] is made up of
1466 // the following bit flags.
1467 constexpr unsigned Float = 1;
1468 constexpr unsigned UseUserNamespace = 2;
1469
1470 constexpr unsigned NumParts = 4;
1471 raw_self_contained_string_ostream parts[NumParts];
1472
1473 // Write typedefs for all the required vector types, and a few scalar
1474 // types that don't already have the name we want them to have.
1475
1476 parts[0] << "typedef uint16_t mve_pred16_t;\n";
1477 parts[Float] << "typedef __fp16 float16_t;\n"
1478 "typedef float float32_t;\n";
1479 for (const auto &kv : ScalarTypes) {
1480 const ScalarType *ST = kv.second.get();
1481 if (ST->hasNonstandardName())
1482 continue;
1483 raw_ostream &OS = parts[ST->requiresFloat() ? Float : 0];
1484 const VectorType *VT = getVectorType(ST);
1485
1486 OS << "typedef __attribute__((__neon_vector_type__(" << VT->lanes()
1487 << "), __clang_arm_mve_strict_polymorphism)) " << ST->cName() << " "
1488 << VT->cName() << ";\n";
1489
1490 // Every vector type also comes with a pair of multi-vector types for
1491 // the VLD2 and VLD4 instructions.
1492 for (unsigned n = 2; n <= 4; n += 2) {
1493 const MultiVectorType *MT = getMultiVectorType(n, VT);
1494 OS << "typedef struct { " << VT->cName() << " val[" << n << "]; } "
1495 << MT->cName() << ";\n";
1496 }
1497 }
1498 parts[0] << "\n";
1499 parts[Float] << "\n";
1500
1501 // Write declarations for all the intrinsics.
1502
1503 for (const auto &kv : ACLEIntrinsics) {
1504 const ACLEIntrinsic &Int = *kv.second;
1505
1506 // We generate each intrinsic twice, under its full unambiguous
1507 // name and its shorter polymorphic name (if the latter exists).
1508 for (bool Polymorphic : {false, true}) {
1509 if (Polymorphic && !Int.polymorphic())
1510 continue;
1511 if (!Polymorphic && Int.polymorphicOnly())
1512 continue;
1513
1514 // We also generate each intrinsic under a name like __arm_vfooq
1515 // (which is in C language implementation namespace, so it's
1516 // safe to define in any conforming user program) and a shorter
1517 // one like vfooq (which is in user namespace, so a user might
1518 // reasonably have used it for something already). If so, they
1519 // can #define __ARM_MVE_PRESERVE_USER_NAMESPACE before
1520 // including the header, which will suppress the shorter names
1521 // and leave only the implementation-namespace ones. Then they
1522 // have to write __arm_vfooq everywhere, of course.
1523
1524 for (bool UserNamespace : {false, true}) {
1525 raw_ostream &OS = parts[(Int.requiresFloat() ? Float : 0) |
1526 (UserNamespace ? UseUserNamespace : 0)];
1527
1528 // Make the name of the function in this declaration.
1529
1530 std::string FunctionName =
1531 Polymorphic ? Int.shortName() : Int.fullName();
1532 if (!UserNamespace)
1533 FunctionName = "__arm_" + FunctionName;
1534
1535 // Make strings for the types involved in the function's
1536 // prototype.
1537
1538 std::string RetTypeName = Int.returnType()->cName();
1539 if (!StringRef(RetTypeName).endswith("*"))
1540 RetTypeName += " ";
1541
1542 std::vector<std::string> ArgTypeNames;
1543 for (const Type *ArgTypePtr : Int.argTypes())
1544 ArgTypeNames.push_back(ArgTypePtr->cName());
1545 std::string ArgTypesString =
1546 join(std::begin(ArgTypeNames), std::end(ArgTypeNames), ", ");
1547
1548 // Emit the actual declaration. All these functions are
1549 // declared 'static inline' without a body, which is fine
1550 // provided clang recognizes them as builtins, and has the
1551 // effect that this type signature is used in place of the one
1552 // that Builtins.def didn't provide. That's how we can get
1553 // structure types that weren't defined until this header was
1554 // included to be part of the type signature of a builtin that
1555 // was known to clang already.
1556 //
1557 // The declarations use __attribute__(__clang_arm_mve_alias),
1558 // so that each function declared will be recognized as the
1559 // appropriate MVE builtin in spite of its user-facing name.
1560 //
1561 // (That's better than making them all wrapper functions,
1562 // partly because it avoids any compiler error message citing
1563 // the wrapper function definition instead of the user's code,
1564 // and mostly because some MVE intrinsics have arguments
1565 // required to be compile-time constants, and that property
1566 // can't be propagated through a wrapper function. It can be
1567 // propagated through a macro, but macros can't be overloaded
1568 // on argument types very easily - you have to use _Generic,
1569 // which makes error messages very confusing when the user
1570 // gets it wrong.)
1571 //
1572 // Finally, the polymorphic versions of the intrinsics are
1573 // also defined with __attribute__(overloadable), so that when
1574 // the same name is defined with several type signatures, the
1575 // right thing happens. Each one of the overloaded
1576 // declarations is given a different builtin id, which
1577 // has exactly the effect we want: first clang resolves the
1578 // overload to the right function, then it knows which builtin
1579 // it's referring to, and then the Sema checking for that
1580 // builtin can check further things like the constant
1581 // arguments.
1582 //
1583 // One more subtlety is the newline just before the return
1584 // type name. That's a cosmetic tweak to make the error
1585 // messages legible if the user gets the types wrong in a call
1586 // to a polymorphic function: this way, clang will print just
1587 // the _final_ line of each declaration in the header, to show
1588 // the type signatures that would have been legal. So all the
1589 // confusing machinery with __attribute__ is left out of the
1590 // error message, and the user sees something that's more or
1591 // less self-documenting: "here's a list of actually readable
1592 // type signatures for vfooq(), and here's why each one didn't
1593 // match your call".
1594
1595 OS << "static __inline__ __attribute__(("
1596 << (Polymorphic ? "overloadable, " : "")
1597 << "__clang_arm_mve_alias(__builtin_arm_mve_" << Int.fullName()
1598 << ")))\n"
1599 << RetTypeName << FunctionName << "(" << ArgTypesString << ");\n";
1600 }
1601 }
1602 }
1603 for (auto &part : parts)
1604 part << "\n";
1605
1606 // Now we've finished accumulating bits and pieces into the parts[] array.
1607 // Put it all together to write the final output file.
1608
1609 OS << "/*===---- arm_mve.h - ARM MVE intrinsics "
1610 "-----------------------------------===\n"
1611 " *\n"
1612 " *\n"
1613 " * Part of the LLVM Project, under the Apache License v2.0 with LLVM "
1614 "Exceptions.\n"
1615 " * See https://llvm.org/LICENSE.txt for license information.\n"
1616 " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
1617 " *\n"
1618 " *===-------------------------------------------------------------"
1619 "----"
1620 "------===\n"
1621 " */\n"
1622 "\n"
1623 "#ifndef __ARM_MVE_H\n"
1624 "#define __ARM_MVE_H\n"
1625 "\n"
1626 "#if !__ARM_FEATURE_MVE\n"
1627 "#error \"MVE support not enabled\"\n"
1628 "#endif\n"
1629 "\n"
1630 "#include <stdint.h>\n"
1631 "\n"
1632 "#ifdef __cplusplus\n"
1633 "extern \"C\" {\n"
1634 "#endif\n"
1635 "\n";
1636
1637 for (size_t i = 0; i < NumParts; ++i) {
1638 std::vector<std::string> conditions;
1639 if (i & Float)
1640 conditions.push_back("(__ARM_FEATURE_MVE & 2)");
1641 if (i & UseUserNamespace)
1642 conditions.push_back("(!defined __ARM_MVE_PRESERVE_USER_NAMESPACE)");
1643
1644 std::string condition =
1645 join(std::begin(conditions), std::end(conditions), " && ");
1646 if (!condition.empty())
1647 OS << "#if " << condition << "\n\n";
1648 OS << parts[i].str();
1649 if (!condition.empty())
1650 OS << "#endif /* " << condition << " */\n\n";
1651 }
1652
1653 OS << "#ifdef __cplusplus\n"
1654 "} /* extern \"C\" */\n"
1655 "#endif\n"
1656 "\n"
1657 "#endif /* __ARM_MVE_H */\n";
1658}
1659
1660void MveEmitter::EmitBuiltinDef(raw_ostream &OS) {
1661 for (const auto &kv : ACLEIntrinsics) {
1662 const ACLEIntrinsic &Int = *kv.second;
1663 OS << "TARGET_HEADER_BUILTIN(__builtin_arm_mve_" << Int.fullName()
1664 << ", \"\", \"n\", \"arm_mve.h\", ALL_LANGUAGES, \"\")\n";
1665 }
1666
1667 std::set<std::string> ShortNamesSeen;
1668
1669 for (const auto &kv : ACLEIntrinsics) {
1670 const ACLEIntrinsic &Int = *kv.second;
1671 if (Int.polymorphic()) {
1672 StringRef Name = Int.shortName();
1673 if (ShortNamesSeen.find(std::string(Name)) == ShortNamesSeen.end()) {
1674 OS << "BUILTIN(__builtin_arm_mve_" << Name << ", \"vi.\", \"nt";
1675 if (Int.nonEvaluating())
1676 OS << "u"; // indicate that this builtin doesn't evaluate its args
1677 OS << "\")\n";
1678 ShortNamesSeen.insert(std::string(Name));
1679 }
1680 }
1681 }
1682}
1683
1684void MveEmitter::EmitBuiltinSema(raw_ostream &OS) {
1685 std::map<std::string, std::set<std::string>> Checks;
1686
1687 for (const auto &kv : ACLEIntrinsics) {
1688 const ACLEIntrinsic &Int = *kv.second;
1689 std::string Check = Int.genSema();
1690 if (!Check.empty())
1691 Checks[Check].insert(Int.fullName());
1692 }
1693
1694 for (const auto &kv : Checks) {
1695 for (StringRef Name : kv.second)
1696 OS << "case ARM::BI__builtin_arm_mve_" << Name << ":\n";
1697 OS << kv.first;
1698 }
1699}
1700
1701// Machinery for the grouping of intrinsics by similar codegen.
1702//
1703// The general setup is that 'MergeableGroup' stores the things that a set of
1704// similarly shaped intrinsics have in common: the text of their code
1705// generation, and the number and type of their parameter variables.
1706// MergeableGroup is the key in a std::map whose value is a set of
1707// OutputIntrinsic, which stores the ways in which a particular intrinsic
1708// specializes the MergeableGroup's generic description: the function name and
1709// the _values_ of the parameter variables.
1710
1711struct ComparableStringVector : std::vector<std::string> {
1712 // Infrastructure: a derived class of vector<string> which comes with an
1713 // ordering, so that it can be used as a key in maps and an element in sets.
1714 // There's no requirement on the ordering beyond being deterministic.
1715 bool operator<(const ComparableStringVector &rhs) const {
1716 if (size() != rhs.size())
1717 return size() < rhs.size();
1718 for (size_t i = 0, e = size(); i < e; ++i)
1719 if ((*this)[i] != rhs[i])
1720 return (*this)[i] < rhs[i];
1721 return false;
1722 }
1723};
1724
1725struct OutputIntrinsic {
1726 const ACLEIntrinsic *Int;
1727 std::string Name;
1728 ComparableStringVector ParamValues;
1729 bool operator<(const OutputIntrinsic &rhs) const {
1730 if (Name != rhs.Name)
1731 return Name < rhs.Name;
1732 return ParamValues < rhs.ParamValues;
1733 }
1734};
1735struct MergeableGroup {
1736 std::string Code;
1737 ComparableStringVector ParamTypes;
1738 bool operator<(const MergeableGroup &rhs) const {
1739 if (Code != rhs.Code)
1740 return Code < rhs.Code;
1741 return ParamTypes < rhs.ParamTypes;
1742 }
1743};
1744
1745void MveEmitter::EmitBuiltinCG(raw_ostream &OS) {
1746 // Pass 1: generate code for all the intrinsics as if every type or constant
1747 // that can possibly be abstracted out into a parameter variable will be.
1748 // This identifies the sets of intrinsics we'll group together into a single
1749 // piece of code generation.
1750
1751 std::map<MergeableGroup, std::set<OutputIntrinsic>> MergeableGroupsPrelim;
1752
1753 for (const auto &kv : ACLEIntrinsics) {
1754 const ACLEIntrinsic &Int = *kv.second;
1755
1756 MergeableGroup MG;
1757 OutputIntrinsic OI;
1758
1759 OI.Int = &Int;
1760 OI.Name = Int.fullName();
1761 CodeGenParamAllocator ParamAllocPrelim{&MG.ParamTypes, &OI.ParamValues};
1762 raw_string_ostream OS(MG.Code);
1763 Int.genCode(OS, ParamAllocPrelim, 1);
1764 OS.flush();
1765
1766 MergeableGroupsPrelim[MG].insert(OI);
1767 }
1768
1769 // Pass 2: for each of those groups, optimize the parameter variable set by
1770 // eliminating 'parameters' that are the same for all intrinsics in the
1771 // group, and merging together pairs of parameter variables that take the
1772 // same values as each other for all intrinsics in the group.
1773
1774 std::map<MergeableGroup, std::set<OutputIntrinsic>> MergeableGroups;
1775
1776 for (const auto &kv : MergeableGroupsPrelim) {
1777 const MergeableGroup &MG = kv.first;
1778 std::vector<int> ParamNumbers;
1779 std::map<ComparableStringVector, int> ParamNumberMap;
1780
1781 // Loop over the parameters for this group.
1782 for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i) {
1783 // Is this parameter the same for all intrinsics in the group?
1784 const OutputIntrinsic &OI_first = *kv.second.begin();
1785 bool Constant = all_of(kv.second, [&](const OutputIntrinsic &OI) {
1786 return OI.ParamValues[i] == OI_first.ParamValues[i];
1787 });
1788
1789 // If so, record it as -1, meaning 'no parameter variable needed'. Then
1790 // the corresponding call to allocParam in pass 2 will not generate a
1791 // variable at all, and just use the value inline.
1792 if (Constant) {
1793 ParamNumbers.push_back(-1);
1794 continue;
1795 }
1796
1797 // Otherwise, make a list of the values this parameter takes for each
1798 // intrinsic, and see if that value vector matches anything we already
1799 // have. We also record the parameter type, so that we don't accidentally
1800 // match up two parameter variables with different types. (Not that
1801 // there's much chance of them having textually equivalent values, but in
1802 // _principle_ it could happen.)
1803 ComparableStringVector key;
1804 key.push_back(MG.ParamTypes[i]);
1805 for (const auto &OI : kv.second)
1806 key.push_back(OI.ParamValues[i]);
1807
1808 auto Found = ParamNumberMap.find(key);
1809 if (Found != ParamNumberMap.end()) {
1810 // Yes, an existing parameter variable can be reused for this.
1811 ParamNumbers.push_back(Found->second);
1812 continue;
1813 }
1814
1815 // No, we need a new parameter variable.
1816 int ExistingIndex = ParamNumberMap.size();
1817 ParamNumberMap[key] = ExistingIndex;
1818 ParamNumbers.push_back(ExistingIndex);
1819 }
1820
1821 // Now we're ready to do the pass 2 code generation, which will emit the
1822 // reduced set of parameter variables we've just worked out.
1823
1824 for (const auto &OI_prelim : kv.second) {
1825 const ACLEIntrinsic *Int = OI_prelim.Int;
1826
1827 MergeableGroup MG;
1828 OutputIntrinsic OI;
1829
1830 OI.Int = OI_prelim.Int;
1831 OI.Name = OI_prelim.Name;
1832 CodeGenParamAllocator ParamAlloc{&MG.ParamTypes, &OI.ParamValues,
1833 &ParamNumbers};
1834 raw_string_ostream OS(MG.Code);
1835 Int->genCode(OS, ParamAlloc, 2);
1836 OS.flush();
1837
1838 MergeableGroups[MG].insert(OI);
1839 }
1840 }
1841
1842 // Output the actual C++ code.
1843
1844 for (const auto &kv : MergeableGroups) {
1845 const MergeableGroup &MG = kv.first;
1846
1847 // List of case statements in the main switch on BuiltinID, and an open
1848 // brace.
1849 const char *prefix = "";
1850 for (const auto &OI : kv.second) {
1851 OS << prefix << "case ARM::BI__builtin_arm_mve_" << OI.Name << ":";
1852 prefix = "\n";
1853 }
1854 OS << " {\n";
1855
1856 if (!MG.ParamTypes.empty()) {
1857 // If we've got some parameter variables, then emit their declarations...
1858 for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i) {
1859 StringRef Type = MG.ParamTypes[i];
1860 OS << " " << Type;
1861 if (!Type.endswith("*"))
1862 OS << " ";
1863 OS << " Param" << utostr(i) << ";\n";
1864 }
1865
1866 // ... and an inner switch on BuiltinID that will fill them in with each
1867 // individual intrinsic's values.
1868 OS << " switch (BuiltinID) {\n";
1869 for (const auto &OI : kv.second) {
1870 OS << " case ARM::BI__builtin_arm_mve_" << OI.Name << ":\n";
1871 for (size_t i = 0, e = MG.ParamTypes.size(); i < e; ++i)
1872 OS << " Param" << utostr(i) << " = " << OI.ParamValues[i] << ";\n";
1873 OS << " break;\n";
1874 }
1875 OS << " }\n";
1876 }
1877
1878 // And finally, output the code, and close the outer pair of braces. (The
1879 // code will always end with a 'return' statement, so we need not insert a
1880 // 'break' here.)
1881 OS << MG.Code << "}\n";
1882 }
1883}
1884
1885void MveEmitter::EmitBuiltinAliases(raw_ostream &OS) {
1886 // Build a sorted table of:
1887 // - intrinsic id number
1888 // - full name
1889 // - polymorphic name or -1
1890 StringToOffsetTable StringTable;
1891 OS << "struct IntrinToName {\n"
1892 " uint32_t Id;\n"
1893 " int32_t FullName;\n"
1894 " int32_t ShortName;\n"
1895 "};\n";
1896 OS << "static const IntrinToName Map[] = {\n";
1897 for (const auto &kv : ACLEIntrinsics) {
1898 const ACLEIntrinsic &Int = *kv.second;
1899 int32_t ShortNameOffset =
1900 Int.polymorphic() ? StringTable.GetOrAddStringOffset(Int.shortName())
1901 : -1;
1902 OS << " { ARM::BI__builtin_arm_mve_" << Int.fullName() << ", "
1903 << StringTable.GetOrAddStringOffset(Int.fullName()) << ", "
1904 << ShortNameOffset << "},\n";
1905 }
1906 OS << "};\n\n";
1907
1908 OS << "static const char IntrinNames[] = {\n";
1909 StringTable.EmitString(OS);
1910 OS << "};\n\n";
1911
1912 OS << "auto It = std::lower_bound(std::begin(Map), "
1913 "std::end(Map), BuiltinID,\n"
1914 " [](const IntrinToName &L, unsigned Id) {\n"
1915 " return L.Id < Id;\n"
1916 " });\n";
1917 OS << "if (It == std::end(Map) || It->Id != BuiltinID)\n"
1918 " return false;\n";
1919 OS << "StringRef FullName(&IntrinNames[It->FullName]);\n";
1920 OS << "if (AliasName == FullName)\n"
1921 " return true;\n";
1922 OS << "if (It->ShortName == -1)\n"
1923 " return false;\n";
1924 OS << "StringRef ShortName(&IntrinNames[It->ShortName]);\n";
1925 OS << "return AliasName == ShortName;\n";
1926}
1927
1928} // namespace
1929
1930namespace clang {
1931
1932void EmitMveHeader(RecordKeeper &Records, raw_ostream &OS) {
1933 MveEmitter(Records).EmitHeader(OS);
1934}
1935
1936void EmitMveBuiltinDef(RecordKeeper &Records, raw_ostream &OS) {
1937 MveEmitter(Records).EmitBuiltinDef(OS);
1938}
1939
1940void EmitMveBuiltinSema(RecordKeeper &Records, raw_ostream &OS) {
1941 MveEmitter(Records).EmitBuiltinSema(OS);
1942}
1943
1944void EmitMveBuiltinCG(RecordKeeper &Records, raw_ostream &OS) {
1945 MveEmitter(Records).EmitBuiltinCG(OS);
1946}
1947
1948void EmitMveBuiltinAliases(RecordKeeper &Records, raw_ostream &OS) {
1949 MveEmitter(Records).EmitBuiltinAliases(OS);
1
Calling constructor for 'MveEmitter'
1950}
1951
1952} // end namespace clang