1 //===-- MveEmitter.cpp - Generate arm_mve.h for use with clang ------------===//
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
7 //===----------------------------------------------------------------------===//
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.
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.
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.
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.
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.
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
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.
59 //===----------------------------------------------------------------------===//
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"
86 // -----------------------------------------------------------------------------
87 // A system of classes to represent all the types we'll need to deal with in
88 // the prototypes of intrinsics.
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.
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.
107 // Scalar is used for ordinary int and float types of all sizes.
110 // Vector is used for anything that occupies exactly one MVE vector
111 // register, i.e. {uint,int,float}NxM_t.
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.
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.
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
134 const TypeKind TKind
;
137 Type(TypeKind K
) : TKind(K
) {}
140 TypeKind
typeKind() const { return TKind
; }
141 virtual ~Type() = default;
142 virtual bool requiresFloat() const = 0;
143 virtual bool requiresMVE() const = 0;
144 virtual unsigned sizeInBits() const = 0;
145 virtual std::string
cName() const = 0;
146 virtual std::string
llvmName() const {
147 PrintFatalError("no LLVM type name available for type " + cName());
149 virtual std::string
acleSuffix(std::string
) const {
150 PrintFatalError("no ACLE suffix available for this type");
154 enum class ScalarTypeKind
{ SignedInt
, UnsignedInt
, Float
};
155 inline std::string
toLetter(ScalarTypeKind kind
) {
157 case ScalarTypeKind::SignedInt
:
159 case ScalarTypeKind::UnsignedInt
:
161 case ScalarTypeKind::Float
:
164 llvm_unreachable("Unhandled ScalarTypeKind enum");
166 inline std::string
toCPrefix(ScalarTypeKind kind
) {
168 case ScalarTypeKind::SignedInt
:
170 case ScalarTypeKind::UnsignedInt
:
172 case ScalarTypeKind::Float
:
175 llvm_unreachable("Unhandled ScalarTypeKind enum");
178 class VoidType
: public Type
{
180 VoidType() : Type(TypeKind::Void
) {}
181 unsigned sizeInBits() const override
{ return 0; }
182 bool requiresFloat() const override
{ return false; }
183 bool requiresMVE() const override
{ return false; }
184 std::string
cName() const override
{ return "void"; }
186 static bool classof(const Type
*T
) { return T
->typeKind() == TypeKind::Void
; }
187 std::string
acleSuffix(std::string
) const override
{ return ""; }
190 class PointerType
: public Type
{
195 PointerType(const Type
*Pointee
, bool Const
)
196 : Type(TypeKind::Pointer
), Pointee(Pointee
), Const(Const
) {}
197 unsigned sizeInBits() const override
{ return 32; }
198 bool requiresFloat() const override
{ return Pointee
->requiresFloat(); }
199 bool requiresMVE() const override
{ return Pointee
->requiresMVE(); }
200 std::string
cName() const override
{
201 std::string Name
= Pointee
->cName();
203 // The syntax for a pointer in C is different when the pointee is
204 // itself a pointer. The MVE intrinsics don't contain any double
205 // pointers, so we don't need to worry about that wrinkle.
206 assert(!isa
<PointerType
>(Pointee
) && "Pointer to pointer not supported");
209 Name
= "const " + Name
;
212 std::string
llvmName() const override
{
213 return "llvm::PointerType::getUnqual(" + Pointee
->llvmName() + ")";
215 const Type
*getPointeeType() const { return Pointee
; }
217 static bool classof(const Type
*T
) {
218 return T
->typeKind() == TypeKind::Pointer
;
222 // Base class for all the types that have a name of the form
223 // [prefix][numbers]_t, like int32_t, uint16x8_t, float32x4x2_t.
225 // For this sub-hierarchy we invent a cNameBase() method which returns the
226 // whole name except for the trailing "_t", so that Vector and MultiVector can
227 // append an extra "x2" or whatever to their element type's cNameBase(). Then
228 // the main cName() query method puts "_t" on the end for the final type name.
230 class CRegularNamedType
: public Type
{
232 virtual std::string
cNameBase() const = 0;
235 std::string
cName() const override
{ return cNameBase() + "_t"; }
238 class ScalarType
: public CRegularNamedType
{
241 std::string NameOverride
;
244 ScalarType(const Record
*Record
) : CRegularNamedType(TypeKind::Scalar
) {
245 Kind
= StringSwitch
<ScalarTypeKind
>(Record
->getValueAsString("kind"))
246 .Case("s", ScalarTypeKind::SignedInt
)
247 .Case("u", ScalarTypeKind::UnsignedInt
)
248 .Case("f", ScalarTypeKind::Float
);
249 Bits
= Record
->getValueAsInt("size");
250 NameOverride
= std::string(Record
->getValueAsString("nameOverride"));
252 unsigned sizeInBits() const override
{ return Bits
; }
253 ScalarTypeKind
kind() const { return Kind
; }
254 std::string
suffix() const { return toLetter(Kind
) + utostr(Bits
); }
255 std::string
cNameBase() const override
{
256 return toCPrefix(Kind
) + utostr(Bits
);
258 std::string
cName() const override
{
259 if (NameOverride
.empty())
260 return CRegularNamedType::cName();
263 std::string
llvmName() const override
{
264 if (Kind
== ScalarTypeKind::Float
) {
271 PrintFatalError("bad size for floating type");
273 return "Int" + utostr(Bits
) + "Ty";
275 std::string
acleSuffix(std::string overrideLetter
) const override
{
276 return "_" + (overrideLetter
.size() ? overrideLetter
: toLetter(Kind
))
279 bool isInteger() const { return Kind
!= ScalarTypeKind::Float
; }
280 bool requiresFloat() const override
{ return !isInteger(); }
281 bool requiresMVE() const override
{ return false; }
282 bool hasNonstandardName() const { return !NameOverride
.empty(); }
284 static bool classof(const Type
*T
) {
285 return T
->typeKind() == TypeKind::Scalar
;
289 class VectorType
: public CRegularNamedType
{
290 const ScalarType
*Element
;
294 VectorType(const ScalarType
*Element
, unsigned Lanes
)
295 : CRegularNamedType(TypeKind::Vector
), Element(Element
), Lanes(Lanes
) {}
296 unsigned sizeInBits() const override
{ return Lanes
* Element
->sizeInBits(); }
297 unsigned lanes() const { return Lanes
; }
298 bool requiresFloat() const override
{ return Element
->requiresFloat(); }
299 bool requiresMVE() const override
{ return true; }
300 std::string
cNameBase() const override
{
301 return Element
->cNameBase() + "x" + utostr(Lanes
);
303 std::string
llvmName() const override
{
304 return "llvm::FixedVectorType::get(" + Element
->llvmName() + ", " +
308 static bool classof(const Type
*T
) {
309 return T
->typeKind() == TypeKind::Vector
;
313 class MultiVectorType
: public CRegularNamedType
{
314 const VectorType
*Element
;
318 MultiVectorType(unsigned Registers
, const VectorType
*Element
)
319 : CRegularNamedType(TypeKind::MultiVector
), Element(Element
),
320 Registers(Registers
) {}
321 unsigned sizeInBits() const override
{
322 return Registers
* Element
->sizeInBits();
324 unsigned registers() const { return Registers
; }
325 bool requiresFloat() const override
{ return Element
->requiresFloat(); }
326 bool requiresMVE() const override
{ return true; }
327 std::string
cNameBase() const override
{
328 return Element
->cNameBase() + "x" + utostr(Registers
);
331 // MultiVectorType doesn't override llvmName, because we don't expect to do
332 // automatic code generation for the MVE intrinsics that use it: the {vld2,
333 // vld4, vst2, vst4} family are the only ones that use these types, so it was
334 // easier to hand-write the codegen for dealing with these structs than to
335 // build in lots of extra automatic machinery that would only be used once.
337 static bool classof(const Type
*T
) {
338 return T
->typeKind() == TypeKind::MultiVector
;
342 class PredicateType
: public CRegularNamedType
{
346 PredicateType(unsigned Lanes
)
347 : CRegularNamedType(TypeKind::Predicate
), Lanes(Lanes
) {}
348 unsigned sizeInBits() const override
{ return 16; }
349 std::string
cNameBase() const override
{ return "mve_pred16"; }
350 bool requiresFloat() const override
{ return false; };
351 bool requiresMVE() const override
{ return true; }
352 std::string
llvmName() const override
{
353 return "llvm::FixedVectorType::get(Builder.getInt1Ty(), " + utostr(Lanes
) +
357 static bool classof(const Type
*T
) {
358 return T
->typeKind() == TypeKind::Predicate
;
362 // -----------------------------------------------------------------------------
363 // Class to facilitate merging together the code generation for many intrinsics
364 // by means of varying a few constant or type parameters.
366 // Most obviously, the intrinsics in a single parametrised family will have
367 // code generation sequences that only differ in a type or two, e.g. vaddq_s8
368 // and vaddq_u16 will look the same apart from putting a different vector type
369 // in the call to CGM.getIntrinsic(). But also, completely different intrinsics
370 // will often code-generate in the same way, with only a different choice of
371 // _which_ IR intrinsic they lower to (e.g. vaddq_m_s8 and vmulq_m_s8), but
372 // marshalling the arguments and return values of the IR intrinsic in exactly
373 // the same way. And others might differ only in some other kind of constant,
374 // such as a lane index.
376 // So, when we generate the IR-building code for all these intrinsics, we keep
377 // track of every value that could possibly be pulled out of the code and
378 // stored ahead of time in a local variable. Then we group together intrinsics
379 // by textual equivalence of the code that would result if _all_ those
380 // parameters were stored in local variables. That gives us maximal sets that
381 // can be implemented by a single piece of IR-building code by changing
382 // parameter values ahead of time.
384 // After we've done that, we do a second pass in which we only allocate _some_
385 // of the parameters into local variables, by tracking which ones have the same
386 // values as each other (so that a single variable can be reused) and which
387 // ones are the same across the whole set (so that no variable is needed at
390 // Hence the class below. Its allocParam method is invoked during code
391 // generation by every method of a Result subclass (see below) that wants to
392 // give it the opportunity to pull something out into a switchable parameter.
393 // It returns a variable name for the parameter, or (if it's being used in the
394 // second pass once we've decided that some parameters don't need to be stored
395 // in variables after all) it might just return the input expression unchanged.
397 struct CodeGenParamAllocator
{
398 // Accumulated during code generation
399 std::vector
<std::string
> *ParamTypes
= nullptr;
400 std::vector
<std::string
> *ParamValues
= nullptr;
402 // Provided ahead of time in pass 2, to indicate which parameters are being
403 // assigned to what. This vector contains an entry for each call to
404 // allocParam expected during code gen (which we counted up in pass 1), and
405 // indicates the number of the parameter variable that should be returned, or
406 // -1 if this call shouldn't allocate a parameter variable at all.
408 // We rely on the recursive code generation working identically in passes 1
409 // and 2, so that the same list of calls to allocParam happen in the same
410 // order. That guarantees that the parameter numbers recorded in pass 1 will
411 // match the entries in this vector that store what EmitterBase::EmitBuiltinCG
412 // decided to do about each one in pass 2.
413 std::vector
<int> *ParamNumberMap
= nullptr;
415 // Internally track how many things we've allocated
416 unsigned nparams
= 0;
418 std::string
allocParam(StringRef Type
, StringRef Value
) {
419 unsigned ParamNumber
;
421 if (!ParamNumberMap
) {
422 // In pass 1, unconditionally assign a new parameter variable to every
423 // value we're asked to process.
424 ParamNumber
= nparams
++;
426 // In pass 2, consult the map provided by the caller to find out which
427 // variable we should be keeping things in.
428 int MapValue
= (*ParamNumberMap
)[nparams
++];
430 return std::string(Value
);
431 ParamNumber
= MapValue
;
434 // If we've allocated a new parameter variable for the first time, store
435 // its type and value to be retrieved after codegen.
436 if (ParamTypes
&& ParamTypes
->size() == ParamNumber
)
437 ParamTypes
->push_back(std::string(Type
));
438 if (ParamValues
&& ParamValues
->size() == ParamNumber
)
439 ParamValues
->push_back(std::string(Value
));
441 // Unimaginative naming scheme for parameter variables.
442 return "Param" + utostr(ParamNumber
);
446 // -----------------------------------------------------------------------------
447 // System of classes that represent all the intermediate values used during
448 // code-generation for an intrinsic.
450 // The base class 'Result' can represent a value of the LLVM type 'Value', or
451 // sometimes 'Address' (for loads/stores, including an alignment requirement).
453 // In the case where the Tablegen provides a value in the codegen dag as a
454 // plain integer literal, the Result object we construct here will be one that
455 // returns true from hasIntegerConstantValue(). This allows the generated C++
456 // code to use the constant directly in contexts which can take a literal
457 // integer, such as Builder.CreateExtractValue(thing, 1), without going to the
458 // effort of calling llvm::ConstantInt::get() and then pulling the constant
459 // back out of the resulting llvm:Value later.
463 // Convenient shorthand for the pointer type we'll be using everywhere.
464 using Ptr
= std::shared_ptr
<Result
>;
469 bool VarNameUsed
= false;
470 unsigned Visited
= 0;
473 virtual ~Result() = default;
474 using Scope
= std::map
<std::string
, Ptr
, std::less
<>>;
475 virtual void genCode(raw_ostream
&OS
, CodeGenParamAllocator
&) const = 0;
476 virtual bool hasIntegerConstantValue() const { return false; }
477 virtual uint32_t integerConstantValue() const { return 0; }
478 virtual bool hasIntegerValue() const { return false; }
479 virtual std::string
getIntegerValue(const std::string
&) {
480 llvm_unreachable("non-working Result::getIntegerValue called");
482 virtual std::string
typeName() const { return "Value *"; }
484 // Mostly, when a code-generation operation has a dependency on prior
485 // operations, it's because it uses the output values of those operations as
486 // inputs. But there's one exception, which is the use of 'seq' in Tablegen
487 // to indicate that operations have to be performed in sequence regardless of
488 // whether they use each others' output values.
490 // So, the actual generation of code is done by depth-first search, using the
491 // prerequisites() method to get a list of all the other Results that have to
492 // be computed before this one. That method divides into the 'predecessor',
493 // set by setPredecessor() while processing a 'seq' dag node, and the list
494 // returned by 'morePrerequisites', which each subclass implements to return
495 // a list of the Results it uses as input to whatever its own computation is
498 virtual void morePrerequisites(std::vector
<Ptr
> &output
) const {}
499 std::vector
<Ptr
> prerequisites() const {
500 std::vector
<Ptr
> ToRet
;
502 ToRet
.push_back(Predecessor
);
503 morePrerequisites(ToRet
);
507 void setPredecessor(Ptr p
) {
508 // If the user has nested one 'seq' node inside another, and this
509 // method is called on the return value of the inner 'seq' (i.e.
510 // the final item inside it), then we can't link _this_ node to p,
511 // because it already has a predecessor. Instead, walk the chain
512 // until we find the first item in the inner seq, and link that to
513 // p, so that nesting seqs has the obvious effect of linking
514 // everything together into one long sequential chain.
516 while (r
->Predecessor
)
517 r
= r
->Predecessor
.get();
521 // Each Result will be assigned a variable name in the output code, but not
522 // all those variable names will actually be used (e.g. the return value of
523 // Builder.CreateStore has void type, so nobody will want to refer to it). To
524 // prevent annoying compiler warnings, we track whether each Result's
525 // variable name was ever actually mentioned in subsequent statements, so
526 // that it can be left out of the final generated code.
527 std::string
varname() {
531 void setVarname(const StringRef s
) { VarName
= std::string(s
); }
532 bool varnameUsed() const { return VarNameUsed
; }
534 // Emit code to generate this result as a Value *.
535 virtual std::string
asValue() {
539 // Code generation happens in multiple passes. This method tracks whether a
540 // Result has yet been visited in a given pass, without the need for a
541 // tedious loop in between passes that goes through and resets a 'visited'
542 // flag back to false: you just set Pass=1 the first time round, and Pass=2
544 bool needsVisiting(unsigned Pass
) {
545 bool ToRet
= Visited
< Pass
;
551 // Result subclass that retrieves one of the arguments to the clang builtin
552 // function. In cases where the argument has pointer type, we call
553 // EmitPointerWithAlignment and store the result in a variable of type Address,
554 // so that load and store IR nodes can know the right alignment. Otherwise, we
555 // call EmitScalarExpr.
557 // There are aggregate parameters in the MVE intrinsics API, but we don't deal
558 // with them in this Tablegen back end: they only arise in the vld2q/vld4q and
559 // vst2q/vst4q family, which is few enough that we just write the code by hand
560 // for those in CGBuiltin.cpp.
561 class BuiltinArgResult
: public Result
{
566 BuiltinArgResult(unsigned ArgNum
, bool AddressType
, bool Immediate
)
567 : ArgNum(ArgNum
), AddressType(AddressType
), Immediate(Immediate
) {}
568 void genCode(raw_ostream
&OS
, CodeGenParamAllocator
&) const override
{
569 OS
<< (AddressType
? "EmitPointerWithAlignment" : "EmitScalarExpr")
570 << "(E->getArg(" << ArgNum
<< "))";
572 std::string
typeName() const override
{
573 return AddressType
? "Address" : Result::typeName();
575 // Emit code to generate this result as a Value *.
576 std::string
asValue() override
{
578 return "(" + varname() + ".emitRawPointer(*this))";
579 return Result::asValue();
581 bool hasIntegerValue() const override
{ return Immediate
; }
582 std::string
getIntegerValue(const std::string
&IntType
) override
{
583 return "GetIntegerConstantValue<" + IntType
+ ">(E->getArg(" +
584 utostr(ArgNum
) + "), getContext())";
588 // Result subclass for an integer literal appearing in Tablegen. This may need
589 // to be turned into an llvm::Result by means of llvm::ConstantInt::get(), or
590 // it may be used directly as an integer, depending on which IRBuilder method
591 // it's being passed to.
592 class IntLiteralResult
: public Result
{
594 const ScalarType
*IntegerType
;
595 uint32_t IntegerValue
;
596 IntLiteralResult(const ScalarType
*IntegerType
, uint32_t IntegerValue
)
597 : IntegerType(IntegerType
), IntegerValue(IntegerValue
) {}
598 void genCode(raw_ostream
&OS
,
599 CodeGenParamAllocator
&ParamAlloc
) const override
{
600 OS
<< "llvm::ConstantInt::get("
601 << ParamAlloc
.allocParam("llvm::Type *", IntegerType
->llvmName())
603 OS
<< ParamAlloc
.allocParam(IntegerType
->cName(), utostr(IntegerValue
))
606 bool hasIntegerConstantValue() const override
{ return true; }
607 uint32_t integerConstantValue() const override
{ return IntegerValue
; }
610 // Result subclass representing a cast between different integer types. We use
611 // our own ScalarType abstraction as the representation of the target type,
612 // which gives both size and signedness.
613 class IntCastResult
: public Result
{
615 const ScalarType
*IntegerType
;
617 IntCastResult(const ScalarType
*IntegerType
, Ptr V
)
618 : IntegerType(IntegerType
), V(V
) {}
619 void genCode(raw_ostream
&OS
,
620 CodeGenParamAllocator
&ParamAlloc
) const override
{
621 OS
<< "Builder.CreateIntCast(" << V
->varname() << ", "
622 << ParamAlloc
.allocParam("llvm::Type *", IntegerType
->llvmName()) << ", "
623 << ParamAlloc
.allocParam("bool",
624 IntegerType
->kind() == ScalarTypeKind::SignedInt
629 void morePrerequisites(std::vector
<Ptr
> &output
) const override
{
634 // Result subclass representing a cast between different pointer types.
635 class PointerCastResult
: public Result
{
637 const PointerType
*PtrType
;
639 PointerCastResult(const PointerType
*PtrType
, Ptr V
)
640 : PtrType(PtrType
), V(V
) {}
641 void genCode(raw_ostream
&OS
,
642 CodeGenParamAllocator
&ParamAlloc
) const override
{
643 OS
<< "Builder.CreatePointerCast(" << V
->asValue() << ", "
644 << ParamAlloc
.allocParam("llvm::Type *", PtrType
->llvmName()) << ")";
646 void morePrerequisites(std::vector
<Ptr
> &output
) const override
{
651 // Result subclass representing a call to an IRBuilder method. Each IRBuilder
652 // method we want to use will have a Tablegen record giving the method name and
653 // describing any important details of how to call it, such as whether a
654 // particular argument should be an integer constant instead of an llvm::Value.
655 class IRBuilderResult
: public Result
{
657 StringRef CallPrefix
;
658 std::vector
<Ptr
> Args
;
659 std::set
<unsigned> AddressArgs
;
660 std::map
<unsigned, std::string
> IntegerArgs
;
661 IRBuilderResult(StringRef CallPrefix
, const std::vector
<Ptr
> &Args
,
662 const std::set
<unsigned> &AddressArgs
,
663 const std::map
<unsigned, std::string
> &IntegerArgs
)
664 : CallPrefix(CallPrefix
), Args(Args
), AddressArgs(AddressArgs
),
665 IntegerArgs(IntegerArgs
) {}
666 void genCode(raw_ostream
&OS
,
667 CodeGenParamAllocator
&ParamAlloc
) const override
{
669 const char *Sep
= "";
670 for (unsigned i
= 0, e
= Args
.size(); i
< e
; ++i
) {
672 auto it
= IntegerArgs
.find(i
);
677 if (it
!= IntegerArgs
.end()) {
678 if (Arg
->hasIntegerConstantValue())
679 OS
<< "static_cast<" << it
->second
<< ">("
680 << ParamAlloc
.allocParam(it
->second
,
681 utostr(Arg
->integerConstantValue()))
683 else if (Arg
->hasIntegerValue())
684 OS
<< ParamAlloc
.allocParam(it
->second
,
685 Arg
->getIntegerValue(it
->second
));
687 OS
<< Arg
->varname();
692 void morePrerequisites(std::vector
<Ptr
> &output
) const override
{
693 for (unsigned i
= 0, e
= Args
.size(); i
< e
; ++i
) {
695 if (IntegerArgs
.find(i
) != IntegerArgs
.end())
697 output
.push_back(Arg
);
702 // Result subclass representing making an Address out of a Value.
703 class AddressResult
: public Result
{
708 AddressResult(Ptr Arg
, const Type
*Ty
, unsigned Align
)
709 : Arg(Arg
), Ty(Ty
), Align(Align
) {}
710 void genCode(raw_ostream
&OS
,
711 CodeGenParamAllocator
&ParamAlloc
) const override
{
712 OS
<< "Address(" << Arg
->varname() << ", " << Ty
->llvmName()
713 << ", CharUnits::fromQuantity(" << Align
<< "))";
715 std::string
typeName() const override
{
718 void morePrerequisites(std::vector
<Ptr
> &output
) const override
{
719 output
.push_back(Arg
);
723 // Result subclass representing a call to an IR intrinsic, which we first have
724 // to look up using an Intrinsic::ID constant and an array of types.
725 class IRIntrinsicResult
: public Result
{
727 std::string IntrinsicID
;
728 std::vector
<const Type
*> ParamTypes
;
729 std::vector
<Ptr
> Args
;
730 IRIntrinsicResult(StringRef IntrinsicID
,
731 const std::vector
<const Type
*> &ParamTypes
,
732 const std::vector
<Ptr
> &Args
)
733 : IntrinsicID(std::string(IntrinsicID
)), ParamTypes(ParamTypes
),
735 void genCode(raw_ostream
&OS
,
736 CodeGenParamAllocator
&ParamAlloc
) const override
{
737 std::string IntNo
= ParamAlloc
.allocParam(
738 "Intrinsic::ID", "Intrinsic::" + IntrinsicID
);
739 OS
<< "Builder.CreateCall(CGM.getIntrinsic(" << IntNo
;
740 if (!ParamTypes
.empty()) {
742 const char *Sep
= "";
743 for (auto T
: ParamTypes
) {
744 OS
<< Sep
<< ParamAlloc
.allocParam("llvm::Type *", T
->llvmName());
750 const char *Sep
= "";
751 for (auto Arg
: Args
) {
752 OS
<< Sep
<< Arg
->asValue();
757 void morePrerequisites(std::vector
<Ptr
> &output
) const override
{
758 output
.insert(output
.end(), Args
.begin(), Args
.end());
762 // Result subclass that specifies a type, for use in IRBuilder operations such
763 // as CreateBitCast that take a type argument.
764 class TypeResult
: public Result
{
767 TypeResult(const Type
*T
) : T(T
) {}
768 void genCode(raw_ostream
&OS
, CodeGenParamAllocator
&) const override
{
771 std::string
typeName() const override
{
772 return "llvm::Type *";
776 // -----------------------------------------------------------------------------
777 // Class that describes a single ACLE intrinsic.
779 // A Tablegen record will typically describe more than one ACLE intrinsic, by
780 // means of setting the 'list<Type> Params' field to a list of multiple
781 // parameter types, so as to define vaddq_{s8,u8,...,f16,f32} all in one go.
782 // We'll end up with one instance of ACLEIntrinsic for *each* parameter type,
783 // rather than a single one for all of them. Hence, the constructor takes both
784 // a Tablegen record and the current value of the parameter type.
786 class ACLEIntrinsic
{
787 // Structure documenting that one of the intrinsic's arguments is required to
788 // be a compile-time constant integer, and what constraints there are on its
789 // value. Used when generating Sema checking code.
790 struct ImmediateArg
{
791 enum class BoundsType
{ ExplicitRange
, UInt
};
792 BoundsType boundsType
;
794 StringRef ExtraCheckType
, ExtraCheckArgs
;
798 // For polymorphic intrinsics, FullName is the explicit name that uniquely
799 // identifies this variant of the intrinsic, and ShortName is the name it
800 // shares with at least one other intrinsic.
801 std::string ShortName
, FullName
;
803 // Name of the architecture extension, used in the Clang builtin name
804 StringRef BuiltinExtension
;
806 // A very small number of intrinsics _only_ have a polymorphic
807 // variant (vuninitializedq taking an unevaluated argument).
808 bool PolymorphicOnly
;
810 // Another rarely-used flag indicating that the builtin doesn't
811 // evaluate its argument(s) at all.
814 // True if the intrinsic needs only the C header part (no codegen, semantic
815 // checks, etc). Used for redeclaring MVE intrinsics in the arm_cde.h header.
818 const Type
*ReturnType
;
819 std::vector
<const Type
*> ArgTypes
;
820 std::map
<unsigned, ImmediateArg
> ImmediateArgs
;
823 std::map
<std::string
, std::string
> CustomCodeGenArgs
;
825 // Recursive function that does the internals of code generation.
826 void genCodeDfs(Result::Ptr V
, std::list
<Result::Ptr
> &Used
,
827 unsigned Pass
) const {
828 if (!V
->needsVisiting(Pass
))
831 for (Result::Ptr W
: V
->prerequisites())
832 genCodeDfs(W
, Used
, Pass
);
838 const std::string
&shortName() const { return ShortName
; }
839 const std::string
&fullName() const { return FullName
; }
840 StringRef
builtinExtension() const { return BuiltinExtension
; }
841 const Type
*returnType() const { return ReturnType
; }
842 const std::vector
<const Type
*> &argTypes() const { return ArgTypes
; }
843 bool requiresFloat() const {
844 if (ReturnType
->requiresFloat())
846 for (const Type
*T
: ArgTypes
)
847 if (T
->requiresFloat())
851 bool requiresMVE() const {
852 return ReturnType
->requiresMVE() ||
853 any_of(ArgTypes
, [](const Type
*T
) { return T
->requiresMVE(); });
855 bool polymorphic() const { return ShortName
!= FullName
; }
856 bool polymorphicOnly() const { return PolymorphicOnly
; }
857 bool nonEvaluating() const { return NonEvaluating
; }
858 bool headerOnly() const { return HeaderOnly
; }
860 // External entry point for code generation, called from EmitterBase.
861 void genCode(raw_ostream
&OS
, CodeGenParamAllocator
&ParamAlloc
,
862 unsigned Pass
) const {
863 assert(!headerOnly() && "Called genCode for header-only intrinsic");
865 for (auto kv
: CustomCodeGenArgs
)
866 OS
<< " " << kv
.first
<< " = " << kv
.second
<< ";\n";
867 OS
<< " break; // custom code gen\n";
870 std::list
<Result::Ptr
> Used
;
871 genCodeDfs(Code
, Used
, Pass
);
873 unsigned varindex
= 0;
874 for (Result::Ptr V
: Used
)
875 if (V
->varnameUsed())
876 V
->setVarname("Val" + utostr(varindex
++));
878 for (Result::Ptr V
: Used
) {
880 if (V
== Used
.back()) {
881 assert(!V
->varnameUsed());
882 OS
<< "return "; // FIXME: what if the top-level thing is void?
883 } else if (V
->varnameUsed()) {
884 std::string Type
= V
->typeName();
886 if (!StringRef(Type
).ends_with("*"))
888 OS
<< V
->varname() << " = ";
890 V
->genCode(OS
, ParamAlloc
);
894 bool hasCode() const { return Code
!= nullptr; }
896 static std::string
signedHexLiteral(const APInt
&iOrig
) {
897 APInt i
= iOrig
.trunc(64);
899 i
.toString(s
, 16, true, true);
900 return std::string(s
);
903 std::string
genSema() const {
904 assert(!headerOnly() && "Called genSema for header-only intrinsic");
905 std::vector
<std::string
> SemaChecks
;
907 for (const auto &kv
: ImmediateArgs
) {
908 const ImmediateArg
&IA
= kv
.second
;
910 APInt
lo(128, 0), hi(128, 0);
911 switch (IA
.boundsType
) {
912 case ImmediateArg::BoundsType::ExplicitRange
:
916 case ImmediateArg::BoundsType::UInt
:
918 hi
= APInt::getMaxValue(IA
.i1
).zext(128);
922 std::string Index
= utostr(kv
.first
);
924 // Emit a range check if the legal range of values for the
925 // immediate is smaller than the _possible_ range of values for
927 unsigned ArgTypeBits
= IA
.ArgType
->sizeInBits();
928 APInt ArgTypeRange
= APInt::getMaxValue(ArgTypeBits
).zext(128);
929 APInt ActualRange
= (hi
- lo
).trunc(64).sext(128);
930 if (ActualRange
.ult(ArgTypeRange
))
931 SemaChecks
.push_back("SemaRef.BuiltinConstantArgRange(TheCall, " +
932 Index
+ ", " + signedHexLiteral(lo
) + ", " +
933 signedHexLiteral(hi
) + ")");
935 if (!IA
.ExtraCheckType
.empty()) {
937 if (!IA
.ExtraCheckArgs
.empty()) {
939 StringRef Arg
= IA
.ExtraCheckArgs
;
940 if (Arg
== "!lanesize") {
941 tmp
= utostr(IA
.ArgType
->sizeInBits());
944 Suffix
= (Twine(", ") + Arg
).str();
946 SemaChecks
.push_back((Twine("SemaRef.BuiltinConstantArg") +
947 IA
.ExtraCheckType
+ "(TheCall, " + Index
+
952 assert(!SemaChecks
.empty());
954 if (SemaChecks
.empty())
956 return join(std::begin(SemaChecks
), std::end(SemaChecks
),
961 ACLEIntrinsic(EmitterBase
&ME
, const Record
*R
, const Type
*Param
);
964 // -----------------------------------------------------------------------------
965 // The top-level class that holds all the state from analyzing the entire
970 // EmitterBase holds a collection of all the types we've instantiated.
972 std::map
<std::string
, std::unique_ptr
<ScalarType
>> ScalarTypes
;
973 std::map
<std::tuple
<ScalarTypeKind
, unsigned, unsigned>,
974 std::unique_ptr
<VectorType
>>
976 std::map
<std::pair
<std::string
, unsigned>, std::unique_ptr
<MultiVectorType
>>
978 std::map
<unsigned, std::unique_ptr
<PredicateType
>> PredicateTypes
;
979 std::map
<std::string
, std::unique_ptr
<PointerType
>> PointerTypes
;
981 // And all the ACLEIntrinsic instances we've created.
982 std::map
<std::string
, std::unique_ptr
<ACLEIntrinsic
>> ACLEIntrinsics
;
985 // Methods to create a Type object, or return the right existing one from the
986 // maps stored in this object.
987 const VoidType
*getVoidType() { return &Void
; }
988 const ScalarType
*getScalarType(StringRef Name
) {
989 return ScalarTypes
[std::string(Name
)].get();
991 const ScalarType
*getScalarType(const Record
*R
) {
992 return getScalarType(R
->getName());
994 const VectorType
*getVectorType(const ScalarType
*ST
, unsigned Lanes
) {
995 std::tuple
<ScalarTypeKind
, unsigned, unsigned> key(ST
->kind(),
996 ST
->sizeInBits(), Lanes
);
997 auto [It
, Inserted
] = VectorTypes
.try_emplace(key
);
999 It
->second
= std::make_unique
<VectorType
>(ST
, Lanes
);
1000 return It
->second
.get();
1002 const VectorType
*getVectorType(const ScalarType
*ST
) {
1003 return getVectorType(ST
, 128 / ST
->sizeInBits());
1005 const MultiVectorType
*getMultiVectorType(unsigned Registers
,
1006 const VectorType
*VT
) {
1007 std::pair
<std::string
, unsigned> key(VT
->cNameBase(), Registers
);
1008 auto [It
, Inserted
] = MultiVectorTypes
.try_emplace(key
);
1010 It
->second
= std::make_unique
<MultiVectorType
>(Registers
, VT
);
1011 return It
->second
.get();
1013 const PredicateType
*getPredicateType(unsigned Lanes
) {
1014 unsigned key
= Lanes
;
1015 auto [It
, Inserted
] = PredicateTypes
.try_emplace(key
);
1017 It
->second
= std::make_unique
<PredicateType
>(Lanes
);
1018 return It
->second
.get();
1020 const PointerType
*getPointerType(const Type
*T
, bool Const
) {
1021 PointerType
PT(T
, Const
);
1022 std::string key
= PT
.cName();
1023 auto [It
, Inserted
] = PointerTypes
.try_emplace(key
);
1025 It
->second
= std::make_unique
<PointerType
>(PT
);
1026 return It
->second
.get();
1029 // Methods to construct a type from various pieces of Tablegen. These are
1030 // always called in the context of setting up a particular ACLEIntrinsic, so
1031 // there's always an ambient parameter type (because we're iterating through
1032 // the Params list in the Tablegen record for the intrinsic), which is used
1033 // to expand Tablegen classes like 'Vector' which mean something different in
1034 // each member of a parametric family.
1035 const Type
*getType(const Record
*R
, const Type
*Param
);
1036 const Type
*getType(const DagInit
*D
, const Type
*Param
);
1037 const Type
*getType(const Init
*I
, const Type
*Param
);
1039 // Functions that translate the Tablegen representation of an intrinsic's
1040 // code generation into a collection of Value objects (which will then be
1041 // reprocessed to read out the actual C++ code included by CGBuiltin.cpp).
1042 Result::Ptr
getCodeForDag(const DagInit
*D
, const Result::Scope
&Scope
,
1044 Result::Ptr
getCodeForDagArg(const DagInit
*D
, unsigned ArgNum
,
1045 const Result::Scope
&Scope
, const Type
*Param
);
1046 Result::Ptr
getCodeForArg(unsigned ArgNum
, const Type
*ArgType
, bool Promote
,
1049 void GroupSemaChecks(std::map
<std::string
, std::set
<std::string
>> &Checks
);
1051 // Constructor and top-level functions.
1053 EmitterBase(const RecordKeeper
&Records
);
1054 virtual ~EmitterBase() = default;
1056 virtual void EmitHeader(raw_ostream
&OS
) = 0;
1057 virtual void EmitBuiltinDef(raw_ostream
&OS
) = 0;
1058 virtual void EmitBuiltinSema(raw_ostream
&OS
) = 0;
1059 void EmitBuiltinCG(raw_ostream
&OS
);
1060 void EmitBuiltinAliases(raw_ostream
&OS
);
1063 const Type
*EmitterBase::getType(const Init
*I
, const Type
*Param
) {
1064 if (const auto *Dag
= dyn_cast
<DagInit
>(I
))
1065 return getType(Dag
, Param
);
1066 if (const auto *Def
= dyn_cast
<DefInit
>(I
))
1067 return getType(Def
->getDef(), Param
);
1069 PrintFatalError("Could not convert this value into a type");
1072 const Type
*EmitterBase::getType(const Record
*R
, const Type
*Param
) {
1073 // Pass to a subfield of any wrapper records. We don't expect more than one
1074 // of these: immediate operands are used as plain numbers rather than as
1075 // llvm::Value, so it's meaningless to promote their type anyway.
1076 if (R
->isSubClassOf("Immediate"))
1077 R
= R
->getValueAsDef("type");
1078 else if (R
->isSubClassOf("unpromoted"))
1079 R
= R
->getValueAsDef("underlying_type");
1081 if (R
->getName() == "Void")
1082 return getVoidType();
1083 if (R
->isSubClassOf("PrimitiveType"))
1084 return getScalarType(R
);
1085 if (R
->isSubClassOf("ComplexType"))
1086 return getType(R
->getValueAsDag("spec"), Param
);
1088 PrintFatalError(R
->getLoc(), "Could not convert this record into a type");
1091 const Type
*EmitterBase::getType(const DagInit
*D
, const Type
*Param
) {
1092 // The meat of the getType system: types in the Tablegen are represented by a
1093 // dag whose operators select sub-cases of this function.
1095 const Record
*Op
= cast
<DefInit
>(D
->getOperator())->getDef();
1096 if (!Op
->isSubClassOf("ComplexTypeOp"))
1098 "Expected ComplexTypeOp as dag operator in type expression");
1100 if (Op
->getName() == "CTO_Parameter") {
1101 if (isa
<VoidType
>(Param
))
1102 PrintFatalError("Parametric type in unparametrised context");
1106 if (Op
->getName() == "CTO_Vec") {
1107 const Type
*Element
= getType(D
->getArg(0), Param
);
1108 if (D
->getNumArgs() == 1) {
1109 return getVectorType(cast
<ScalarType
>(Element
));
1111 const Type
*ExistingVector
= getType(D
->getArg(1), Param
);
1112 return getVectorType(cast
<ScalarType
>(Element
),
1113 cast
<VectorType
>(ExistingVector
)->lanes());
1117 if (Op
->getName() == "CTO_Pred") {
1118 const Type
*Element
= getType(D
->getArg(0), Param
);
1119 return getPredicateType(128 / Element
->sizeInBits());
1122 if (Op
->isSubClassOf("CTO_Tuple")) {
1123 unsigned Registers
= Op
->getValueAsInt("n");
1124 const Type
*Element
= getType(D
->getArg(0), Param
);
1125 return getMultiVectorType(Registers
, cast
<VectorType
>(Element
));
1128 if (Op
->isSubClassOf("CTO_Pointer")) {
1129 const Type
*Pointee
= getType(D
->getArg(0), Param
);
1130 return getPointerType(Pointee
, Op
->getValueAsBit("const"));
1133 if (Op
->getName() == "CTO_CopyKind") {
1134 const ScalarType
*STSize
= cast
<ScalarType
>(getType(D
->getArg(0), Param
));
1135 const ScalarType
*STKind
= cast
<ScalarType
>(getType(D
->getArg(1), Param
));
1136 for (const auto &kv
: ScalarTypes
) {
1137 const ScalarType
*RT
= kv
.second
.get();
1138 if (RT
->kind() == STKind
->kind() && RT
->sizeInBits() == STSize
->sizeInBits())
1141 PrintFatalError("Cannot find a type to satisfy CopyKind");
1144 if (Op
->isSubClassOf("CTO_ScaleSize")) {
1145 const ScalarType
*STKind
= cast
<ScalarType
>(getType(D
->getArg(0), Param
));
1146 int Num
= Op
->getValueAsInt("num"), Denom
= Op
->getValueAsInt("denom");
1147 unsigned DesiredSize
= STKind
->sizeInBits() * Num
/ Denom
;
1148 for (const auto &kv
: ScalarTypes
) {
1149 const ScalarType
*RT
= kv
.second
.get();
1150 if (RT
->kind() == STKind
->kind() && RT
->sizeInBits() == DesiredSize
)
1153 PrintFatalError("Cannot find a type to satisfy ScaleSize");
1156 PrintFatalError("Bad operator in type dag expression");
1159 Result::Ptr
EmitterBase::getCodeForDag(const DagInit
*D
,
1160 const Result::Scope
&Scope
,
1161 const Type
*Param
) {
1162 const Record
*Op
= cast
<DefInit
>(D
->getOperator())->getDef();
1164 if (Op
->getName() == "seq") {
1165 Result::Scope SubScope
= Scope
;
1166 Result::Ptr PrevV
= nullptr;
1167 for (unsigned i
= 0, e
= D
->getNumArgs(); i
< e
; ++i
) {
1168 // We don't use getCodeForDagArg here, because the argument name
1169 // has different semantics in a seq
1171 getCodeForDag(cast
<DagInit
>(D
->getArg(i
)), SubScope
, Param
);
1172 StringRef ArgName
= D
->getArgNameStr(i
);
1173 if (!ArgName
.empty())
1174 SubScope
[std::string(ArgName
)] = V
;
1176 V
->setPredecessor(PrevV
);
1180 } else if (Op
->isSubClassOf("Type")) {
1181 if (D
->getNumArgs() != 1)
1182 PrintFatalError("Type casts should have exactly one argument");
1183 const Type
*CastType
= getType(Op
, Param
);
1184 Result::Ptr Arg
= getCodeForDagArg(D
, 0, Scope
, Param
);
1185 if (const auto *ST
= dyn_cast
<ScalarType
>(CastType
)) {
1186 if (!ST
->requiresFloat()) {
1187 if (Arg
->hasIntegerConstantValue())
1188 return std::make_shared
<IntLiteralResult
>(
1189 ST
, Arg
->integerConstantValue());
1191 return std::make_shared
<IntCastResult
>(ST
, Arg
);
1193 } else if (const auto *PT
= dyn_cast
<PointerType
>(CastType
)) {
1194 return std::make_shared
<PointerCastResult
>(PT
, Arg
);
1196 PrintFatalError("Unsupported type cast");
1197 } else if (Op
->getName() == "address") {
1198 if (D
->getNumArgs() != 2)
1199 PrintFatalError("'address' should have two arguments");
1200 Result::Ptr Arg
= getCodeForDagArg(D
, 0, Scope
, Param
);
1202 const Type
*Ty
= nullptr;
1203 if (const auto *DI
= dyn_cast
<DagInit
>(D
->getArg(0)))
1204 if (auto *PTy
= dyn_cast
<PointerType
>(getType(DI
->getOperator(), Param
)))
1205 Ty
= PTy
->getPointeeType();
1207 PrintFatalError("'address' pointer argument should be a pointer");
1210 if (const auto *II
= dyn_cast
<IntInit
>(D
->getArg(1))) {
1211 Alignment
= II
->getValue();
1213 PrintFatalError("'address' alignment argument should be an integer");
1215 return std::make_shared
<AddressResult
>(Arg
, Ty
, Alignment
);
1216 } else if (Op
->getName() == "unsignedflag") {
1217 if (D
->getNumArgs() != 1)
1218 PrintFatalError("unsignedflag should have exactly one argument");
1219 const Record
*TypeRec
= cast
<DefInit
>(D
->getArg(0))->getDef();
1220 if (!TypeRec
->isSubClassOf("Type"))
1221 PrintFatalError("unsignedflag's argument should be a type");
1222 if (const auto *ST
= dyn_cast
<ScalarType
>(getType(TypeRec
, Param
))) {
1223 return std::make_shared
<IntLiteralResult
>(
1224 getScalarType("u32"), ST
->kind() == ScalarTypeKind::UnsignedInt
);
1226 PrintFatalError("unsignedflag's argument should be a scalar type");
1228 } else if (Op
->getName() == "bitsize") {
1229 if (D
->getNumArgs() != 1)
1230 PrintFatalError("bitsize should have exactly one argument");
1231 const Record
*TypeRec
= cast
<DefInit
>(D
->getArg(0))->getDef();
1232 if (!TypeRec
->isSubClassOf("Type"))
1233 PrintFatalError("bitsize's argument should be a type");
1234 if (const auto *ST
= dyn_cast
<ScalarType
>(getType(TypeRec
, Param
))) {
1235 return std::make_shared
<IntLiteralResult
>(getScalarType("u32"),
1238 PrintFatalError("bitsize's argument should be a scalar type");
1241 std::vector
<Result::Ptr
> Args
;
1242 for (unsigned i
= 0, e
= D
->getNumArgs(); i
< e
; ++i
)
1243 Args
.push_back(getCodeForDagArg(D
, i
, Scope
, Param
));
1244 if (Op
->isSubClassOf("IRBuilderBase")) {
1245 std::set
<unsigned> AddressArgs
;
1246 std::map
<unsigned, std::string
> IntegerArgs
;
1247 for (const Record
*sp
: Op
->getValueAsListOfDefs("special_params")) {
1248 unsigned Index
= sp
->getValueAsInt("index");
1249 if (sp
->isSubClassOf("IRBuilderAddrParam")) {
1250 AddressArgs
.insert(Index
);
1251 } else if (sp
->isSubClassOf("IRBuilderIntParam")) {
1252 IntegerArgs
[Index
] = std::string(sp
->getValueAsString("type"));
1255 return std::make_shared
<IRBuilderResult
>(Op
->getValueAsString("prefix"),
1256 Args
, AddressArgs
, IntegerArgs
);
1257 } else if (Op
->isSubClassOf("IRIntBase")) {
1258 std::vector
<const Type
*> ParamTypes
;
1259 for (const Record
*RParam
: Op
->getValueAsListOfDefs("params"))
1260 ParamTypes
.push_back(getType(RParam
, Param
));
1261 std::string IntName
= std::string(Op
->getValueAsString("intname"));
1262 if (Op
->getValueAsBit("appendKind"))
1263 IntName
+= "_" + toLetter(cast
<ScalarType
>(Param
)->kind());
1264 return std::make_shared
<IRIntrinsicResult
>(IntName
, ParamTypes
, Args
);
1266 PrintFatalError("Unsupported dag node " + Op
->getName());
1271 Result::Ptr
EmitterBase::getCodeForDagArg(const DagInit
*D
, unsigned ArgNum
,
1272 const Result::Scope
&Scope
,
1273 const Type
*Param
) {
1274 const Init
*Arg
= D
->getArg(ArgNum
);
1275 StringRef Name
= D
->getArgNameStr(ArgNum
);
1277 if (!Name
.empty()) {
1278 if (!isa
<UnsetInit
>(Arg
))
1280 "dag operator argument should not have both a value and a name");
1281 auto it
= Scope
.find(Name
);
1282 if (it
== Scope
.end())
1283 PrintFatalError("unrecognized variable name '" + Name
+ "'");
1287 // Sometimes the Arg is a bit. Prior to multiclass template argument
1288 // checking, integers would sneak through the bit declaration,
1289 // but now they really are bits.
1290 if (const auto *BI
= dyn_cast
<BitInit
>(Arg
))
1291 return std::make_shared
<IntLiteralResult
>(getScalarType("u32"),
1294 if (const auto *II
= dyn_cast
<IntInit
>(Arg
))
1295 return std::make_shared
<IntLiteralResult
>(getScalarType("u32"),
1298 if (const auto *DI
= dyn_cast
<DagInit
>(Arg
))
1299 return getCodeForDag(DI
, Scope
, Param
);
1301 if (const auto *DI
= dyn_cast
<DefInit
>(Arg
)) {
1302 const Record
*Rec
= DI
->getDef();
1303 if (Rec
->isSubClassOf("Type")) {
1304 const Type
*T
= getType(Rec
, Param
);
1305 return std::make_shared
<TypeResult
>(T
);
1309 PrintError("bad DAG argument type for code generation");
1310 PrintNote("DAG: " + D
->getAsString());
1311 if (const auto *Typed
= dyn_cast
<TypedInit
>(Arg
))
1312 PrintNote("argument type: " + Typed
->getType()->getAsString());
1313 PrintFatalNote("argument number " + Twine(ArgNum
) + ": " + Arg
->getAsString());
1316 Result::Ptr
EmitterBase::getCodeForArg(unsigned ArgNum
, const Type
*ArgType
,
1317 bool Promote
, bool Immediate
) {
1318 Result::Ptr V
= std::make_shared
<BuiltinArgResult
>(
1319 ArgNum
, isa
<PointerType
>(ArgType
), Immediate
);
1322 if (const auto *ST
= dyn_cast
<ScalarType
>(ArgType
)) {
1323 if (ST
->isInteger() && ST
->sizeInBits() < 32)
1324 V
= std::make_shared
<IntCastResult
>(getScalarType("u32"), V
);
1325 } else if (const auto *PT
= dyn_cast
<PredicateType
>(ArgType
)) {
1326 V
= std::make_shared
<IntCastResult
>(getScalarType("u32"), V
);
1327 V
= std::make_shared
<IRIntrinsicResult
>("arm_mve_pred_i2v",
1328 std::vector
<const Type
*>{PT
},
1329 std::vector
<Result::Ptr
>{V
});
1336 ACLEIntrinsic::ACLEIntrinsic(EmitterBase
&ME
, const Record
*R
,
1338 : ReturnType(ME
.getType(R
->getValueAsDef("ret"), Param
)) {
1339 // Derive the intrinsic's full name, by taking the name of the
1340 // Tablegen record (or override) and appending the suffix from its
1341 // parameter type. (If the intrinsic is unparametrised, its
1342 // parameter type will be given as Void, which returns the empty
1343 // string for acleSuffix.)
1344 StringRef BaseName
=
1345 (R
->isSubClassOf("NameOverride") ? R
->getValueAsString("basename")
1347 StringRef overrideLetter
= R
->getValueAsString("overrideKindLetter");
1349 (Twine(BaseName
) + Param
->acleSuffix(std::string(overrideLetter
))).str();
1351 // Derive the intrinsic's polymorphic name, by removing components from the
1352 // full name as specified by its 'pnt' member ('polymorphic name type'),
1353 // which indicates how many type suffixes to remove, and any other piece of
1354 // the name that should be removed.
1355 const Record
*PolymorphicNameType
= R
->getValueAsDef("pnt");
1356 SmallVector
<StringRef
, 8> NameParts
;
1357 StringRef(FullName
).split(NameParts
, '_');
1358 for (unsigned i
= 0, e
= PolymorphicNameType
->getValueAsInt(
1359 "NumTypeSuffixesToDiscard");
1361 NameParts
.pop_back();
1362 if (!PolymorphicNameType
->isValueUnset("ExtraSuffixToDiscard")) {
1363 StringRef ExtraSuffix
=
1364 PolymorphicNameType
->getValueAsString("ExtraSuffixToDiscard");
1365 auto it
= NameParts
.end();
1366 while (it
!= NameParts
.begin()) {
1368 if (*it
== ExtraSuffix
) {
1369 NameParts
.erase(it
);
1374 ShortName
= join(std::begin(NameParts
), std::end(NameParts
), "_");
1376 BuiltinExtension
= R
->getValueAsString("builtinExtension");
1378 PolymorphicOnly
= R
->getValueAsBit("polymorphicOnly");
1379 NonEvaluating
= R
->getValueAsBit("nonEvaluating");
1380 HeaderOnly
= R
->getValueAsBit("headerOnly");
1382 // Process the intrinsic's argument list.
1383 const DagInit
*ArgsDag
= R
->getValueAsDag("args");
1384 Result::Scope Scope
;
1385 for (unsigned i
= 0, e
= ArgsDag
->getNumArgs(); i
< e
; ++i
) {
1386 const Init
*TypeInit
= ArgsDag
->getArg(i
);
1388 bool Promote
= true;
1389 if (const auto *TypeDI
= dyn_cast
<DefInit
>(TypeInit
))
1390 if (TypeDI
->getDef()->isSubClassOf("unpromoted"))
1393 // Work out the type of the argument, for use in the function prototype in
1395 const Type
*ArgType
= ME
.getType(TypeInit
, Param
);
1396 ArgTypes
.push_back(ArgType
);
1398 // If the argument is a subclass of Immediate, record the details about
1399 // what values it can take, for Sema checking.
1400 bool Immediate
= false;
1401 if (const auto *TypeDI
= dyn_cast
<DefInit
>(TypeInit
)) {
1402 const Record
*TypeRec
= TypeDI
->getDef();
1403 if (TypeRec
->isSubClassOf("Immediate")) {
1406 const Record
*Bounds
= TypeRec
->getValueAsDef("bounds");
1407 ImmediateArg
&IA
= ImmediateArgs
[i
];
1408 if (Bounds
->isSubClassOf("IB_ConstRange")) {
1409 IA
.boundsType
= ImmediateArg::BoundsType::ExplicitRange
;
1410 IA
.i1
= Bounds
->getValueAsInt("lo");
1411 IA
.i2
= Bounds
->getValueAsInt("hi");
1412 } else if (Bounds
->getName() == "IB_UEltValue") {
1413 IA
.boundsType
= ImmediateArg::BoundsType::UInt
;
1414 IA
.i1
= Param
->sizeInBits();
1415 } else if (Bounds
->getName() == "IB_LaneIndex") {
1416 IA
.boundsType
= ImmediateArg::BoundsType::ExplicitRange
;
1418 IA
.i2
= 128 / Param
->sizeInBits() - 1;
1419 } else if (Bounds
->isSubClassOf("IB_EltBit")) {
1420 IA
.boundsType
= ImmediateArg::BoundsType::ExplicitRange
;
1421 IA
.i1
= Bounds
->getValueAsInt("base");
1422 const Type
*T
= ME
.getType(Bounds
->getValueAsDef("type"), Param
);
1423 IA
.i2
= IA
.i1
+ T
->sizeInBits() - 1;
1425 PrintFatalError("unrecognised ImmediateBounds subclass");
1428 IA
.ArgType
= ArgType
;
1430 if (!TypeRec
->isValueUnset("extra")) {
1431 IA
.ExtraCheckType
= TypeRec
->getValueAsString("extra");
1432 if (!TypeRec
->isValueUnset("extraarg"))
1433 IA
.ExtraCheckArgs
= TypeRec
->getValueAsString("extraarg");
1438 // The argument will usually have a name in the arguments dag, which goes
1439 // into the variable-name scope that the code gen will refer to.
1440 StringRef ArgName
= ArgsDag
->getArgNameStr(i
);
1441 if (!ArgName
.empty())
1442 Scope
[std::string(ArgName
)] =
1443 ME
.getCodeForArg(i
, ArgType
, Promote
, Immediate
);
1446 // Finally, go through the codegen dag and translate it into a Result object
1447 // (with an arbitrary DAG of depended-on Results hanging off it).
1448 const DagInit
*CodeDag
= R
->getValueAsDag("codegen");
1449 const Record
*MainOp
= cast
<DefInit
>(CodeDag
->getOperator())->getDef();
1450 if (MainOp
->isSubClassOf("CustomCodegen")) {
1451 // Or, if it's the special case of CustomCodegen, just accumulate
1452 // a list of parameters we're going to assign to variables before
1453 // breaking from the loop.
1454 CustomCodeGenArgs
["CustomCodeGenType"] =
1455 (Twine("CustomCodeGen::") + MainOp
->getValueAsString("type")).str();
1456 for (unsigned i
= 0, e
= CodeDag
->getNumArgs(); i
< e
; ++i
) {
1457 StringRef Name
= CodeDag
->getArgNameStr(i
);
1459 PrintFatalError("Operands to CustomCodegen should have names");
1460 } else if (const auto *II
= dyn_cast
<IntInit
>(CodeDag
->getArg(i
))) {
1461 CustomCodeGenArgs
[std::string(Name
)] = itostr(II
->getValue());
1462 } else if (const auto *SI
= dyn_cast
<StringInit
>(CodeDag
->getArg(i
))) {
1463 CustomCodeGenArgs
[std::string(Name
)] = std::string(SI
->getValue());
1465 PrintFatalError("Operands to CustomCodegen should be integers");
1469 Code
= ME
.getCodeForDag(CodeDag
, Scope
, Param
);
1473 EmitterBase::EmitterBase(const RecordKeeper
&Records
) {
1474 // Construct the whole EmitterBase.
1476 // First, look up all the instances of PrimitiveType. This gives us the list
1477 // of vector typedefs we have to put in arm_mve.h, and also allows us to
1478 // collect all the useful ScalarType instances into a big list so that we can
1479 // use it for operations such as 'find the unsigned version of this signed
1481 for (const Record
*R
: Records
.getAllDerivedDefinitions("PrimitiveType"))
1482 ScalarTypes
[std::string(R
->getName())] = std::make_unique
<ScalarType
>(R
);
1484 // Now go through the instances of Intrinsic, and for each one, iterate
1485 // through its list of type parameters making an ACLEIntrinsic for each one.
1486 for (const Record
*R
: Records
.getAllDerivedDefinitions("Intrinsic")) {
1487 for (const Record
*RParam
: R
->getValueAsListOfDefs("params")) {
1488 const Type
*Param
= getType(RParam
, getVoidType());
1489 auto Intrinsic
= std::make_unique
<ACLEIntrinsic
>(*this, R
, Param
);
1490 ACLEIntrinsics
[Intrinsic
->fullName()] = std::move(Intrinsic
);
1495 /// A wrapper on raw_string_ostream that contains its own buffer rather than
1496 /// having to point it at one elsewhere. (In other words, it works just like
1497 /// std::ostringstream; also, this makes it convenient to declare a whole array
1498 /// of them at once.)
1500 /// We have to set this up using multiple inheritance, to ensure that the
1501 /// string member has been constructed before raw_string_ostream's constructor
1502 /// is given a pointer to it.
1503 class string_holder
{
1507 class raw_self_contained_string_ostream
: private string_holder
,
1508 public raw_string_ostream
{
1510 raw_self_contained_string_ostream() : raw_string_ostream(S
) {}
1513 const char LLVMLicenseHeader
[] =
1516 " * Part of the LLVM Project, under the Apache License v2.0 with LLVM"
1518 " * See https://llvm.org/LICENSE.txt for license information.\n"
1519 " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
1521 " *===-----------------------------------------------------------------"
1526 // Machinery for the grouping of intrinsics by similar codegen.
1528 // The general setup is that 'MergeableGroup' stores the things that a set of
1529 // similarly shaped intrinsics have in common: the text of their code
1530 // generation, and the number and type of their parameter variables.
1531 // MergeableGroup is the key in a std::map whose value is a set of
1532 // OutputIntrinsic, which stores the ways in which a particular intrinsic
1533 // specializes the MergeableGroup's generic description: the function name and
1534 // the _values_ of the parameter variables.
1536 struct ComparableStringVector
: std::vector
<std::string
> {
1537 // Infrastructure: a derived class of vector<string> which comes with an
1538 // ordering, so that it can be used as a key in maps and an element in sets.
1539 // There's no requirement on the ordering beyond being deterministic.
1540 bool operator<(const ComparableStringVector
&rhs
) const {
1541 if (size() != rhs
.size())
1542 return size() < rhs
.size();
1543 for (size_t i
= 0, e
= size(); i
< e
; ++i
)
1544 if ((*this)[i
] != rhs
[i
])
1545 return (*this)[i
] < rhs
[i
];
1550 struct OutputIntrinsic
{
1551 const ACLEIntrinsic
*Int
;
1553 ComparableStringVector ParamValues
;
1554 bool operator<(const OutputIntrinsic
&rhs
) const {
1555 if (Name
!= rhs
.Name
)
1556 return Name
< rhs
.Name
;
1557 return ParamValues
< rhs
.ParamValues
;
1560 struct MergeableGroup
{
1562 ComparableStringVector ParamTypes
;
1563 bool operator<(const MergeableGroup
&rhs
) const {
1564 if (Code
!= rhs
.Code
)
1565 return Code
< rhs
.Code
;
1566 return ParamTypes
< rhs
.ParamTypes
;
1570 void EmitterBase::EmitBuiltinCG(raw_ostream
&OS
) {
1571 // Pass 1: generate code for all the intrinsics as if every type or constant
1572 // that can possibly be abstracted out into a parameter variable will be.
1573 // This identifies the sets of intrinsics we'll group together into a single
1574 // piece of code generation.
1576 std::map
<MergeableGroup
, std::set
<OutputIntrinsic
>> MergeableGroupsPrelim
;
1578 for (const auto &kv
: ACLEIntrinsics
) {
1579 const ACLEIntrinsic
&Int
= *kv
.second
;
1580 if (Int
.headerOnly())
1587 OI
.Name
= Int
.fullName();
1588 CodeGenParamAllocator ParamAllocPrelim
{&MG
.ParamTypes
, &OI
.ParamValues
};
1589 raw_string_ostream
OS(MG
.Code
);
1590 Int
.genCode(OS
, ParamAllocPrelim
, 1);
1592 MergeableGroupsPrelim
[MG
].insert(OI
);
1595 // Pass 2: for each of those groups, optimize the parameter variable set by
1596 // eliminating 'parameters' that are the same for all intrinsics in the
1597 // group, and merging together pairs of parameter variables that take the
1598 // same values as each other for all intrinsics in the group.
1600 std::map
<MergeableGroup
, std::set
<OutputIntrinsic
>> MergeableGroups
;
1602 for (const auto &kv
: MergeableGroupsPrelim
) {
1603 const MergeableGroup
&MG
= kv
.first
;
1604 std::vector
<int> ParamNumbers
;
1605 std::map
<ComparableStringVector
, int> ParamNumberMap
;
1607 // Loop over the parameters for this group.
1608 for (size_t i
= 0, e
= MG
.ParamTypes
.size(); i
< e
; ++i
) {
1609 // Is this parameter the same for all intrinsics in the group?
1610 const OutputIntrinsic
&OI_first
= *kv
.second
.begin();
1611 bool Constant
= all_of(kv
.second
, [&](const OutputIntrinsic
&OI
) {
1612 return OI
.ParamValues
[i
] == OI_first
.ParamValues
[i
];
1615 // If so, record it as -1, meaning 'no parameter variable needed'. Then
1616 // the corresponding call to allocParam in pass 2 will not generate a
1617 // variable at all, and just use the value inline.
1619 ParamNumbers
.push_back(-1);
1623 // Otherwise, make a list of the values this parameter takes for each
1624 // intrinsic, and see if that value vector matches anything we already
1625 // have. We also record the parameter type, so that we don't accidentally
1626 // match up two parameter variables with different types. (Not that
1627 // there's much chance of them having textually equivalent values, but in
1628 // _principle_ it could happen.)
1629 ComparableStringVector key
;
1630 key
.push_back(MG
.ParamTypes
[i
]);
1631 for (const auto &OI
: kv
.second
)
1632 key
.push_back(OI
.ParamValues
[i
]);
1634 auto Found
= ParamNumberMap
.find(key
);
1635 if (Found
!= ParamNumberMap
.end()) {
1636 // Yes, an existing parameter variable can be reused for this.
1637 ParamNumbers
.push_back(Found
->second
);
1641 // No, we need a new parameter variable.
1642 int ExistingIndex
= ParamNumberMap
.size();
1643 ParamNumberMap
[key
] = ExistingIndex
;
1644 ParamNumbers
.push_back(ExistingIndex
);
1647 // Now we're ready to do the pass 2 code generation, which will emit the
1648 // reduced set of parameter variables we've just worked out.
1650 for (const auto &OI_prelim
: kv
.second
) {
1651 const ACLEIntrinsic
*Int
= OI_prelim
.Int
;
1656 OI
.Int
= OI_prelim
.Int
;
1657 OI
.Name
= OI_prelim
.Name
;
1658 CodeGenParamAllocator ParamAlloc
{&MG
.ParamTypes
, &OI
.ParamValues
,
1660 raw_string_ostream
OS(MG
.Code
);
1661 Int
->genCode(OS
, ParamAlloc
, 2);
1663 MergeableGroups
[MG
].insert(OI
);
1667 // Output the actual C++ code.
1669 for (const auto &kv
: MergeableGroups
) {
1670 const MergeableGroup
&MG
= kv
.first
;
1672 // List of case statements in the main switch on BuiltinID, and an open
1674 const char *prefix
= "";
1675 for (const auto &OI
: kv
.second
) {
1676 OS
<< prefix
<< "case ARM::BI__builtin_arm_" << OI
.Int
->builtinExtension()
1677 << "_" << OI
.Name
<< ":";
1683 if (!MG
.ParamTypes
.empty()) {
1684 // If we've got some parameter variables, then emit their declarations...
1685 for (size_t i
= 0, e
= MG
.ParamTypes
.size(); i
< e
; ++i
) {
1686 StringRef Type
= MG
.ParamTypes
[i
];
1688 if (!Type
.ends_with("*"))
1690 OS
<< " Param" << utostr(i
) << ";\n";
1693 // ... and an inner switch on BuiltinID that will fill them in with each
1694 // individual intrinsic's values.
1695 OS
<< " switch (BuiltinID) {\n";
1696 for (const auto &OI
: kv
.second
) {
1697 OS
<< " case ARM::BI__builtin_arm_" << OI
.Int
->builtinExtension()
1698 << "_" << OI
.Name
<< ":\n";
1699 for (size_t i
= 0, e
= MG
.ParamTypes
.size(); i
< e
; ++i
)
1700 OS
<< " Param" << utostr(i
) << " = " << OI
.ParamValues
[i
] << ";\n";
1706 // And finally, output the code, and close the outer pair of braces. (The
1707 // code will always end with a 'return' statement, so we need not insert a
1709 OS
<< MG
.Code
<< "}\n";
1713 void EmitterBase::EmitBuiltinAliases(raw_ostream
&OS
) {
1714 // Build a sorted table of:
1715 // - intrinsic id number
1717 // - polymorphic name or -1
1718 StringToOffsetTable StringTable
;
1719 OS
<< "static const IntrinToName MapData[] = {\n";
1720 for (const auto &kv
: ACLEIntrinsics
) {
1721 const ACLEIntrinsic
&Int
= *kv
.second
;
1722 if (Int
.headerOnly())
1724 int32_t ShortNameOffset
=
1725 Int
.polymorphic() ? StringTable
.GetOrAddStringOffset(Int
.shortName())
1727 OS
<< " { ARM::BI__builtin_arm_" << Int
.builtinExtension() << "_"
1728 << Int
.fullName() << ", "
1729 << StringTable
.GetOrAddStringOffset(Int
.fullName()) << ", "
1730 << ShortNameOffset
<< "},\n";
1734 OS
<< "ArrayRef<IntrinToName> Map(MapData);\n\n";
1736 OS
<< "static const char IntrinNames[] = {\n";
1737 StringTable
.EmitString(OS
);
1741 void EmitterBase::GroupSemaChecks(
1742 std::map
<std::string
, std::set
<std::string
>> &Checks
) {
1743 for (const auto &kv
: ACLEIntrinsics
) {
1744 const ACLEIntrinsic
&Int
= *kv
.second
;
1745 if (Int
.headerOnly())
1747 std::string Check
= Int
.genSema();
1749 Checks
[Check
].insert(Int
.fullName());
1753 // -----------------------------------------------------------------------------
1754 // The class used for generating arm_mve.h and related Clang bits
1757 class MveEmitter
: public EmitterBase
{
1759 MveEmitter(const RecordKeeper
&Records
) : EmitterBase(Records
) {}
1760 void EmitHeader(raw_ostream
&OS
) override
;
1761 void EmitBuiltinDef(raw_ostream
&OS
) override
;
1762 void EmitBuiltinSema(raw_ostream
&OS
) override
;
1765 void MveEmitter::EmitHeader(raw_ostream
&OS
) {
1766 // Accumulate pieces of the header file that will be enabled under various
1767 // different combinations of #ifdef. The index into parts[] is made up of
1768 // the following bit flags.
1769 constexpr unsigned Float
= 1;
1770 constexpr unsigned UseUserNamespace
= 2;
1772 constexpr unsigned NumParts
= 4;
1773 raw_self_contained_string_ostream parts
[NumParts
];
1775 // Write typedefs for all the required vector types, and a few scalar
1776 // types that don't already have the name we want them to have.
1778 parts
[0] << "typedef uint16_t mve_pred16_t;\n";
1779 parts
[Float
] << "typedef __fp16 float16_t;\n"
1780 "typedef float float32_t;\n";
1781 for (const auto &kv
: ScalarTypes
) {
1782 const ScalarType
*ST
= kv
.second
.get();
1783 if (ST
->hasNonstandardName())
1785 raw_ostream
&OS
= parts
[ST
->requiresFloat() ? Float
: 0];
1786 const VectorType
*VT
= getVectorType(ST
);
1788 OS
<< "typedef __attribute__((__neon_vector_type__(" << VT
->lanes()
1789 << "), __clang_arm_mve_strict_polymorphism)) " << ST
->cName() << " "
1790 << VT
->cName() << ";\n";
1792 // Every vector type also comes with a pair of multi-vector types for
1793 // the VLD2 and VLD4 instructions.
1794 for (unsigned n
= 2; n
<= 4; n
+= 2) {
1795 const MultiVectorType
*MT
= getMultiVectorType(n
, VT
);
1796 OS
<< "typedef struct { " << VT
->cName() << " val[" << n
<< "]; } "
1797 << MT
->cName() << ";\n";
1801 parts
[Float
] << "\n";
1803 // Write declarations for all the intrinsics.
1805 for (const auto &kv
: ACLEIntrinsics
) {
1806 const ACLEIntrinsic
&Int
= *kv
.second
;
1808 // We generate each intrinsic twice, under its full unambiguous
1809 // name and its shorter polymorphic name (if the latter exists).
1810 for (bool Polymorphic
: {false, true}) {
1811 if (Polymorphic
&& !Int
.polymorphic())
1813 if (!Polymorphic
&& Int
.polymorphicOnly())
1816 // We also generate each intrinsic under a name like __arm_vfooq
1817 // (which is in C language implementation namespace, so it's
1818 // safe to define in any conforming user program) and a shorter
1819 // one like vfooq (which is in user namespace, so a user might
1820 // reasonably have used it for something already). If so, they
1821 // can #define __ARM_MVE_PRESERVE_USER_NAMESPACE before
1822 // including the header, which will suppress the shorter names
1823 // and leave only the implementation-namespace ones. Then they
1824 // have to write __arm_vfooq everywhere, of course.
1826 for (bool UserNamespace
: {false, true}) {
1827 raw_ostream
&OS
= parts
[(Int
.requiresFloat() ? Float
: 0) |
1828 (UserNamespace
? UseUserNamespace
: 0)];
1830 // Make the name of the function in this declaration.
1832 std::string FunctionName
=
1833 Polymorphic
? Int
.shortName() : Int
.fullName();
1835 FunctionName
= "__arm_" + FunctionName
;
1837 // Make strings for the types involved in the function's
1840 std::string RetTypeName
= Int
.returnType()->cName();
1841 if (!StringRef(RetTypeName
).ends_with("*"))
1844 std::vector
<std::string
> ArgTypeNames
;
1845 for (const Type
*ArgTypePtr
: Int
.argTypes())
1846 ArgTypeNames
.push_back(ArgTypePtr
->cName());
1847 std::string ArgTypesString
=
1848 join(std::begin(ArgTypeNames
), std::end(ArgTypeNames
), ", ");
1850 // Emit the actual declaration. All these functions are
1851 // declared 'static inline' without a body, which is fine
1852 // provided clang recognizes them as builtins, and has the
1853 // effect that this type signature is used in place of the one
1854 // that Builtins.td didn't provide. That's how we can get
1855 // structure types that weren't defined until this header was
1856 // included to be part of the type signature of a builtin that
1857 // was known to clang already.
1859 // The declarations use __attribute__(__clang_arm_builtin_alias),
1860 // so that each function declared will be recognized as the
1861 // appropriate MVE builtin in spite of its user-facing name.
1863 // (That's better than making them all wrapper functions,
1864 // partly because it avoids any compiler error message citing
1865 // the wrapper function definition instead of the user's code,
1866 // and mostly because some MVE intrinsics have arguments
1867 // required to be compile-time constants, and that property
1868 // can't be propagated through a wrapper function. It can be
1869 // propagated through a macro, but macros can't be overloaded
1870 // on argument types very easily - you have to use _Generic,
1871 // which makes error messages very confusing when the user
1874 // Finally, the polymorphic versions of the intrinsics are
1875 // also defined with __attribute__(overloadable), so that when
1876 // the same name is defined with several type signatures, the
1877 // right thing happens. Each one of the overloaded
1878 // declarations is given a different builtin id, which
1879 // has exactly the effect we want: first clang resolves the
1880 // overload to the right function, then it knows which builtin
1881 // it's referring to, and then the Sema checking for that
1882 // builtin can check further things like the constant
1885 // One more subtlety is the newline just before the return
1886 // type name. That's a cosmetic tweak to make the error
1887 // messages legible if the user gets the types wrong in a call
1888 // to a polymorphic function: this way, clang will print just
1889 // the _final_ line of each declaration in the header, to show
1890 // the type signatures that would have been legal. So all the
1891 // confusing machinery with __attribute__ is left out of the
1892 // error message, and the user sees something that's more or
1893 // less self-documenting: "here's a list of actually readable
1894 // type signatures for vfooq(), and here's why each one didn't
1895 // match your call".
1897 OS
<< "static __inline__ __attribute__(("
1898 << (Polymorphic
? "__overloadable__, " : "")
1899 << "__clang_arm_builtin_alias(__builtin_arm_mve_" << Int
.fullName()
1901 << RetTypeName
<< FunctionName
<< "(" << ArgTypesString
<< ");\n";
1905 for (auto &part
: parts
)
1908 // Now we've finished accumulating bits and pieces into the parts[] array.
1909 // Put it all together to write the final output file.
1911 OS
<< "/*===---- arm_mve.h - ARM MVE intrinsics "
1912 "-----------------------------------===\n"
1913 << LLVMLicenseHeader
1914 << "#ifndef __ARM_MVE_H\n"
1915 "#define __ARM_MVE_H\n"
1917 "#if !__ARM_FEATURE_MVE\n"
1918 "#error \"MVE support not enabled\"\n"
1921 "#include <stdint.h>\n"
1923 "#ifdef __cplusplus\n"
1928 for (size_t i
= 0; i
< NumParts
; ++i
) {
1929 std::vector
<std::string
> conditions
;
1931 conditions
.push_back("(__ARM_FEATURE_MVE & 2)");
1932 if (i
& UseUserNamespace
)
1933 conditions
.push_back("(!defined __ARM_MVE_PRESERVE_USER_NAMESPACE)");
1935 std::string condition
=
1936 join(std::begin(conditions
), std::end(conditions
), " && ");
1937 if (!condition
.empty())
1938 OS
<< "#if " << condition
<< "\n\n";
1939 OS
<< parts
[i
].str();
1940 if (!condition
.empty())
1941 OS
<< "#endif /* " << condition
<< " */\n\n";
1944 OS
<< "#ifdef __cplusplus\n"
1945 "} /* extern \"C\" */\n"
1948 "#endif /* __ARM_MVE_H */\n";
1951 void MveEmitter::EmitBuiltinDef(raw_ostream
&OS
) {
1952 for (const auto &kv
: ACLEIntrinsics
) {
1953 const ACLEIntrinsic
&Int
= *kv
.second
;
1954 OS
<< "BUILTIN(__builtin_arm_mve_" << Int
.fullName()
1955 << ", \"\", \"n\")\n";
1958 std::set
<std::string
> ShortNamesSeen
;
1960 for (const auto &kv
: ACLEIntrinsics
) {
1961 const ACLEIntrinsic
&Int
= *kv
.second
;
1962 if (Int
.polymorphic()) {
1963 StringRef Name
= Int
.shortName();
1964 if (ShortNamesSeen
.find(std::string(Name
)) == ShortNamesSeen
.end()) {
1965 OS
<< "BUILTIN(__builtin_arm_mve_" << Name
<< ", \"vi.\", \"nt";
1966 if (Int
.nonEvaluating())
1967 OS
<< "u"; // indicate that this builtin doesn't evaluate its args
1969 ShortNamesSeen
.insert(std::string(Name
));
1975 void MveEmitter::EmitBuiltinSema(raw_ostream
&OS
) {
1976 std::map
<std::string
, std::set
<std::string
>> Checks
;
1977 GroupSemaChecks(Checks
);
1979 for (const auto &kv
: Checks
) {
1980 for (StringRef Name
: kv
.second
)
1981 OS
<< "case ARM::BI__builtin_arm_mve_" << Name
<< ":\n";
1982 OS
<< " return " << kv
.first
;
1986 // -----------------------------------------------------------------------------
1987 // Class that describes an ACLE intrinsic implemented as a macro.
1989 // This class is used when the intrinsic is polymorphic in 2 or 3 types, but we
1990 // want to avoid a combinatorial explosion by reinterpreting the arguments to
1993 class FunctionMacro
{
1994 std::vector
<StringRef
> Params
;
1995 StringRef Definition
;
1998 FunctionMacro(const Record
&R
);
2000 const std::vector
<StringRef
> &getParams() const { return Params
; }
2001 StringRef
getDefinition() const { return Definition
; }
2004 FunctionMacro::FunctionMacro(const Record
&R
) {
2005 Params
= R
.getValueAsListOfStrings("params");
2006 Definition
= R
.getValueAsString("definition");
2009 // -----------------------------------------------------------------------------
2010 // The class used for generating arm_cde.h and related Clang bits
2013 class CdeEmitter
: public EmitterBase
{
2014 std::map
<StringRef
, FunctionMacro
> FunctionMacros
;
2017 CdeEmitter(const RecordKeeper
&Records
);
2018 void EmitHeader(raw_ostream
&OS
) override
;
2019 void EmitBuiltinDef(raw_ostream
&OS
) override
;
2020 void EmitBuiltinSema(raw_ostream
&OS
) override
;
2023 CdeEmitter::CdeEmitter(const RecordKeeper
&Records
) : EmitterBase(Records
) {
2024 for (const Record
*R
: Records
.getAllDerivedDefinitions("FunctionMacro"))
2025 FunctionMacros
.emplace(R
->getName(), FunctionMacro(*R
));
2028 void CdeEmitter::EmitHeader(raw_ostream
&OS
) {
2029 // Accumulate pieces of the header file that will be enabled under various
2030 // different combinations of #ifdef. The index into parts[] is one of the
2032 constexpr unsigned None
= 0;
2033 constexpr unsigned MVE
= 1;
2034 constexpr unsigned MVEFloat
= 2;
2036 constexpr unsigned NumParts
= 3;
2037 raw_self_contained_string_ostream parts
[NumParts
];
2039 // Write typedefs for all the required vector types, and a few scalar
2040 // types that don't already have the name we want them to have.
2042 parts
[MVE
] << "typedef uint16_t mve_pred16_t;\n";
2043 parts
[MVEFloat
] << "typedef __fp16 float16_t;\n"
2044 "typedef float float32_t;\n";
2045 for (const auto &kv
: ScalarTypes
) {
2046 const ScalarType
*ST
= kv
.second
.get();
2047 if (ST
->hasNonstandardName())
2049 // We don't have float64x2_t
2050 if (ST
->kind() == ScalarTypeKind::Float
&& ST
->sizeInBits() == 64)
2052 raw_ostream
&OS
= parts
[ST
->requiresFloat() ? MVEFloat
: MVE
];
2053 const VectorType
*VT
= getVectorType(ST
);
2055 OS
<< "typedef __attribute__((__neon_vector_type__(" << VT
->lanes()
2056 << "), __clang_arm_mve_strict_polymorphism)) " << ST
->cName() << " "
2057 << VT
->cName() << ";\n";
2060 parts
[MVEFloat
] << "\n";
2062 // Write declarations for all the intrinsics.
2064 for (const auto &kv
: ACLEIntrinsics
) {
2065 const ACLEIntrinsic
&Int
= *kv
.second
;
2067 // We generate each intrinsic twice, under its full unambiguous
2068 // name and its shorter polymorphic name (if the latter exists).
2069 for (bool Polymorphic
: {false, true}) {
2070 if (Polymorphic
&& !Int
.polymorphic())
2072 if (!Polymorphic
&& Int
.polymorphicOnly())
2076 parts
[Int
.requiresFloat() ? MVEFloat
2077 : Int
.requiresMVE() ? MVE
: None
];
2079 // Make the name of the function in this declaration.
2080 std::string FunctionName
=
2081 "__arm_" + (Polymorphic
? Int
.shortName() : Int
.fullName());
2083 // Make strings for the types involved in the function's
2085 std::string RetTypeName
= Int
.returnType()->cName();
2086 if (!StringRef(RetTypeName
).ends_with("*"))
2089 std::vector
<std::string
> ArgTypeNames
;
2090 for (const Type
*ArgTypePtr
: Int
.argTypes())
2091 ArgTypeNames
.push_back(ArgTypePtr
->cName());
2092 std::string ArgTypesString
=
2093 join(std::begin(ArgTypeNames
), std::end(ArgTypeNames
), ", ");
2095 // Emit the actual declaration. See MveEmitter::EmitHeader for detailed
2097 OS
<< "static __inline__ __attribute__(("
2098 << (Polymorphic
? "__overloadable__, " : "")
2099 << "__clang_arm_builtin_alias(__builtin_arm_" << Int
.builtinExtension()
2100 << "_" << Int
.fullName() << ")))\n"
2101 << RetTypeName
<< FunctionName
<< "(" << ArgTypesString
<< ");\n";
2105 for (const auto &kv
: FunctionMacros
) {
2106 StringRef Name
= kv
.first
;
2107 const FunctionMacro
&FM
= kv
.second
;
2109 raw_ostream
&OS
= parts
[MVE
];
2111 << "__arm_" << Name
<< "(" << join(FM
.getParams(), ", ") << ") "
2112 << FM
.getDefinition() << "\n";
2115 for (auto &part
: parts
)
2118 // Now we've finished accumulating bits and pieces into the parts[] array.
2119 // Put it all together to write the final output file.
2121 OS
<< "/*===---- arm_cde.h - ARM CDE intrinsics "
2122 "-----------------------------------===\n"
2123 << LLVMLicenseHeader
2124 << "#ifndef __ARM_CDE_H\n"
2125 "#define __ARM_CDE_H\n"
2127 "#if !__ARM_FEATURE_CDE\n"
2128 "#error \"CDE support not enabled\"\n"
2131 "#include <stdint.h>\n"
2133 "#ifdef __cplusplus\n"
2138 for (size_t i
= 0; i
< NumParts
; ++i
) {
2139 std::string condition
;
2141 condition
= "__ARM_FEATURE_MVE & 2";
2143 condition
= "__ARM_FEATURE_MVE";
2145 if (!condition
.empty())
2146 OS
<< "#if " << condition
<< "\n\n";
2147 OS
<< parts
[i
].str();
2148 if (!condition
.empty())
2149 OS
<< "#endif /* " << condition
<< " */\n\n";
2152 OS
<< "#ifdef __cplusplus\n"
2153 "} /* extern \"C\" */\n"
2156 "#endif /* __ARM_CDE_H */\n";
2159 void CdeEmitter::EmitBuiltinDef(raw_ostream
&OS
) {
2160 for (const auto &kv
: ACLEIntrinsics
) {
2161 if (kv
.second
->headerOnly())
2163 const ACLEIntrinsic
&Int
= *kv
.second
;
2164 OS
<< "BUILTIN(__builtin_arm_cde_" << Int
.fullName()
2165 << ", \"\", \"ncU\")\n";
2169 void CdeEmitter::EmitBuiltinSema(raw_ostream
&OS
) {
2170 std::map
<std::string
, std::set
<std::string
>> Checks
;
2171 GroupSemaChecks(Checks
);
2173 for (const auto &kv
: Checks
) {
2174 for (StringRef Name
: kv
.second
)
2175 OS
<< "case ARM::BI__builtin_arm_cde_" << Name
<< ":\n";
2176 OS
<< " Err = " << kv
.first
<< " break;\n";
2186 void EmitMveHeader(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2187 MveEmitter(Records
).EmitHeader(OS
);
2190 void EmitMveBuiltinDef(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2191 MveEmitter(Records
).EmitBuiltinDef(OS
);
2194 void EmitMveBuiltinSema(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2195 MveEmitter(Records
).EmitBuiltinSema(OS
);
2198 void EmitMveBuiltinCG(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2199 MveEmitter(Records
).EmitBuiltinCG(OS
);
2202 void EmitMveBuiltinAliases(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2203 MveEmitter(Records
).EmitBuiltinAliases(OS
);
2208 void EmitCdeHeader(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2209 CdeEmitter(Records
).EmitHeader(OS
);
2212 void EmitCdeBuiltinDef(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2213 CdeEmitter(Records
).EmitBuiltinDef(OS
);
2216 void EmitCdeBuiltinSema(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2217 CdeEmitter(Records
).EmitBuiltinSema(OS
);
2220 void EmitCdeBuiltinCG(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2221 CdeEmitter(Records
).EmitBuiltinCG(OS
);
2224 void EmitCdeBuiltinAliases(const RecordKeeper
&Records
, raw_ostream
&OS
) {
2225 CdeEmitter(Records
).EmitBuiltinAliases(OS
);
2228 } // end namespace clang