blob: 1e01f611bfa27559b1b09765b14043bdd9c709bb [file] [log] [blame]
Sander de Smalen5087ace2020-03-15 14:29:45 +00001//===- SveEmitter.cpp - Generate arm_sve.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 tablegen backend is responsible for emitting arm_sve.h, which includes
10// a declaration and definition of each function specified by the ARM C/C++
11// Language Extensions (ACLE).
12//
13// For details, visit:
14// https://developer.arm.com/architectures/system-architectures/software-standards/acle
15//
16// Each SVE instruction is implemented in terms of 1 or more functions which
17// are suffixed with the element type of the input vectors. Functions may be
18// implemented in terms of generic vector operations such as +, *, -, etc. or
19// by calling a __builtin_-prefixed function which will be handled by clang's
20// CodeGen library.
21//
22// See also the documentation in include/clang/Basic/arm_sve.td.
23//
24//===----------------------------------------------------------------------===//
25
26#include "llvm/ADT/STLExtras.h"
Sander de Smalenc5b81462020-03-18 11:07:20 +000027#include "llvm/ADT/StringMap.h"
Sander de Smalen5087ace2020-03-15 14:29:45 +000028#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/TableGen/Record.h"
31#include "llvm/TableGen/Error.h"
32#include <string>
33#include <sstream>
34#include <set>
35#include <cctype>
Eric Fiselieraf2968e2020-04-16 18:35:31 -040036#include <tuple>
Sander de Smalen5087ace2020-03-15 14:29:45 +000037
38using namespace llvm;
39
Sander de Smalenc5b81462020-03-18 11:07:20 +000040enum ClassKind {
41 ClassNone,
42 ClassS, // signed/unsigned, e.g., "_s8", "_u8" suffix
43 ClassG, // Overloaded name without type suffix
44};
45
46using TypeSpec = std::string;
Sander de Smalen5087ace2020-03-15 14:29:45 +000047
48namespace {
49
Sander de Smalenc8a5b302020-04-14 15:56:36 +010050class ImmCheck {
51 unsigned Arg;
52 unsigned Kind;
53 unsigned ElementSizeInBits;
54
55public:
56 ImmCheck(unsigned Arg, unsigned Kind, unsigned ElementSizeInBits = 0)
57 : Arg(Arg), Kind(Kind), ElementSizeInBits(ElementSizeInBits) {}
58 ImmCheck(const ImmCheck &Other) = default;
59 ~ImmCheck() = default;
60
61 unsigned getArg() const { return Arg; }
62 unsigned getKind() const { return Kind; }
63 unsigned getElementSizeInBits() const { return ElementSizeInBits; }
64};
65
Sander de Smalenc5b81462020-03-18 11:07:20 +000066class SVEType {
67 TypeSpec TS;
68 bool Float, Signed, Immediate, Void, Constant, Pointer;
69 bool DefaultType, IsScalable, Predicate, PredicatePattern, PrefetchOp;
70 unsigned Bitwidth, ElementBitwidth, NumVectors;
71
Sander de Smalen8b409ea2020-03-16 10:14:05 +000072public:
Sander de Smalenc5b81462020-03-18 11:07:20 +000073 SVEType() : SVEType(TypeSpec(), 'v') {}
74
75 SVEType(TypeSpec TS, char CharMod)
76 : TS(TS), Float(false), Signed(true), Immediate(false), Void(false),
77 Constant(false), Pointer(false), DefaultType(false), IsScalable(true),
78 Predicate(false), PredicatePattern(false), PrefetchOp(false),
79 Bitwidth(128), ElementBitwidth(~0U), NumVectors(1) {
80 if (!TS.empty())
81 applyTypespec();
82 applyModifier(CharMod);
83 }
84
Sander de Smalenc5b81462020-03-18 11:07:20 +000085 bool isPointer() const { return Pointer; }
86 bool isVoidPointer() const { return Pointer && Void; }
87 bool isSigned() const { return Signed; }
88 bool isImmediate() const { return Immediate; }
89 bool isScalar() const { return NumVectors == 0; }
90 bool isVector() const { return NumVectors > 0; }
91 bool isScalableVector() const { return isVector() && IsScalable; }
92 bool isChar() const { return ElementBitwidth == 8; }
93 bool isVoid() const { return Void & !Pointer; }
94 bool isDefault() const { return DefaultType; }
95 bool isFloat() const { return Float; }
96 bool isInteger() const { return !Float && !Predicate; }
97 bool isScalarPredicate() const { return !Float && ElementBitwidth == 1; }
98 bool isPredicateVector() const { return Predicate; }
99 bool isPredicatePattern() const { return PredicatePattern; }
100 bool isPrefetchOp() const { return PrefetchOp; }
101 bool isConstant() const { return Constant; }
102 unsigned getElementSizeInBits() const { return ElementBitwidth; }
103 unsigned getNumVectors() const { return NumVectors; }
104
105 unsigned getNumElements() const {
106 assert(ElementBitwidth != ~0U);
107 return Bitwidth / ElementBitwidth;
108 }
109 unsigned getSizeInBits() const {
110 return Bitwidth;
111 }
112
113 /// Return the string representation of a type, which is an encoded
114 /// string for passing to the BUILTIN() macro in Builtins.def.
115 std::string builtin_str() const;
116
Sander de Smalen981f0802020-03-18 15:05:08 +0000117 /// Return the C/C++ string representation of a type for use in the
118 /// arm_sve.h header file.
119 std::string str() const;
120
Sander de Smalenc5b81462020-03-18 11:07:20 +0000121private:
122 /// Creates the type based on the typespec string in TS.
123 void applyTypespec();
124
125 /// Applies a prototype modifier to the type.
126 void applyModifier(char Mod);
127};
128
129
130class SVEEmitter;
131
132/// The main grunt class. This represents an instantiation of an intrinsic with
133/// a particular typespec and prototype.
134class Intrinsic {
135 /// The unmangled name.
136 std::string Name;
137
138 /// The name of the corresponding LLVM IR intrinsic.
139 std::string LLVMName;
140
141 /// Intrinsic prototype.
142 std::string Proto;
143
144 /// The base type spec for this intrinsic.
145 TypeSpec BaseTypeSpec;
146
147 /// The base class kind. Most intrinsics use ClassS, which has full type
148 /// info for integers (_s32/_u32), or ClassG which is used for overloaded
149 /// intrinsics.
150 ClassKind Class;
151
152 /// The architectural #ifdef guard.
153 std::string Guard;
154
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100155 // The merge suffix such as _m, _x or _z.
156 std::string MergeSuffix;
157
Sander de Smalenc5b81462020-03-18 11:07:20 +0000158 /// The types of return value [0] and parameters [1..].
159 std::vector<SVEType> Types;
160
161 /// The "base type", which is VarType('d', BaseTypeSpec).
162 SVEType BaseType;
163
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100164 uint64_t Flags;
Sander de Smalenc5b81462020-03-18 11:07:20 +0000165
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100166 SmallVector<ImmCheck, 2> ImmChecks;
167
Sander de Smalenc5b81462020-03-18 11:07:20 +0000168public:
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100169 Intrinsic(StringRef Name, StringRef Proto, uint64_t MergeTy,
170 StringRef MergeSuffix, uint64_t MemoryElementTy, StringRef LLVMName,
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100171 uint64_t Flags, ArrayRef<ImmCheck> ImmChecks, TypeSpec BT,
172 ClassKind Class, SVEEmitter &Emitter, StringRef Guard);
Sander de Smalenc5b81462020-03-18 11:07:20 +0000173
174 ~Intrinsic()=default;
175
176 std::string getName() const { return Name; }
177 std::string getLLVMName() const { return LLVMName; }
178 std::string getProto() const { return Proto; }
179 TypeSpec getBaseTypeSpec() const { return BaseTypeSpec; }
180 SVEType getBaseType() const { return BaseType; }
181
182 StringRef getGuard() const { return Guard; }
183 ClassKind getClassKind() const { return Class; }
Sander de Smalenc5b81462020-03-18 11:07:20 +0000184
185 SVEType getReturnType() const { return Types[0]; }
186 ArrayRef<SVEType> getTypes() const { return Types; }
187 SVEType getParamType(unsigned I) const { return Types[I + 1]; }
188 unsigned getNumParams() const { return Proto.size() - 1; }
189
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100190 uint64_t getFlags() const { return Flags; }
Sander de Smalenc5b81462020-03-18 11:07:20 +0000191 bool isFlagSet(uint64_t Flag) const { return Flags & Flag;}
192
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100193 ArrayRef<ImmCheck> getImmChecks() const { return ImmChecks; }
194
Sander de Smalenc5b81462020-03-18 11:07:20 +0000195 /// Return the type string for a BUILTIN() macro in Builtins.def.
196 std::string getBuiltinTypeStr();
197
198 /// Return the name, mangled with type information. The name is mangled for
199 /// ClassS, so will add type suffixes such as _u32/_s32.
200 std::string getMangledName() const { return mangleName(ClassS); }
201
202 /// Returns true if the intrinsic is overloaded, in that it should also generate
203 /// a short form without the type-specifiers, e.g. 'svld1(..)' instead of
204 /// 'svld1_u32(..)'.
205 static bool isOverloadedIntrinsic(StringRef Name) {
206 auto BrOpen = Name.find("[");
207 auto BrClose = Name.find(']');
208 return BrOpen != std::string::npos && BrClose != std::string::npos;
209 }
210
211 /// Emits the intrinsic declaration to the ostream.
212 void emitIntrinsic(raw_ostream &OS) const;
213
214private:
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100215 std::string getMergeSuffix() const { return MergeSuffix; }
Sander de Smalenc5b81462020-03-18 11:07:20 +0000216 std::string mangleName(ClassKind LocalCK) const;
217 std::string replaceTemplatedArgs(std::string Name, TypeSpec TS,
218 std::string Proto) const;
219};
220
221class SVEEmitter {
222private:
223 RecordKeeper &Records;
224 llvm::StringMap<uint64_t> EltTypes;
225 llvm::StringMap<uint64_t> MemEltTypes;
226 llvm::StringMap<uint64_t> FlagTypes;
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100227 llvm::StringMap<uint64_t> MergeTypes;
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100228 llvm::StringMap<uint64_t> ImmCheckTypes;
Sander de Smalenc5b81462020-03-18 11:07:20 +0000229
Sander de Smalenc5b81462020-03-18 11:07:20 +0000230public:
231 SVEEmitter(RecordKeeper &R) : Records(R) {
232 for (auto *RV : Records.getAllDerivedDefinitions("EltType"))
233 EltTypes[RV->getNameInitAsString()] = RV->getValueAsInt("Value");
234 for (auto *RV : Records.getAllDerivedDefinitions("MemEltType"))
235 MemEltTypes[RV->getNameInitAsString()] = RV->getValueAsInt("Value");
236 for (auto *RV : Records.getAllDerivedDefinitions("FlagType"))
237 FlagTypes[RV->getNameInitAsString()] = RV->getValueAsInt("Value");
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100238 for (auto *RV : Records.getAllDerivedDefinitions("MergeType"))
239 MergeTypes[RV->getNameInitAsString()] = RV->getValueAsInt("Value");
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100240 for (auto *RV : Records.getAllDerivedDefinitions("ImmCheckType"))
241 ImmCheckTypes[RV->getNameInitAsString()] = RV->getValueAsInt("Value");
242 }
243
244 /// Returns the enum value for the immcheck type
245 unsigned getEnumValueForImmCheck(StringRef C) const {
246 auto It = ImmCheckTypes.find(C);
247 if (It != ImmCheckTypes.end())
248 return It->getValue();
249 llvm_unreachable("Unsupported imm check");
Sander de Smalenc5b81462020-03-18 11:07:20 +0000250 }
251
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100252 // Returns the SVETypeFlags for a given value and mask.
253 uint64_t encodeFlag(uint64_t V, StringRef MaskName) const {
254 auto It = FlagTypes.find(MaskName);
255 if (It != FlagTypes.end()) {
256 uint64_t Mask = It->getValue();
257 unsigned Shift = llvm::countTrailingZeros(Mask);
258 return (V << Shift) & Mask;
259 }
260 llvm_unreachable("Unsupported flag");
261 }
262
263 // Returns the SVETypeFlags for the given element type.
264 uint64_t encodeEltType(StringRef EltName) {
265 auto It = EltTypes.find(EltName);
266 if (It != EltTypes.end())
267 return encodeFlag(It->getValue(), "EltTypeMask");
268 llvm_unreachable("Unsupported EltType");
269 }
270
271 // Returns the SVETypeFlags for the given memory element type.
272 uint64_t encodeMemoryElementType(uint64_t MT) {
273 return encodeFlag(MT, "MemEltTypeMask");
274 }
275
276 // Returns the SVETypeFlags for the given merge type.
277 uint64_t encodeMergeType(uint64_t MT) {
278 return encodeFlag(MT, "MergeTypeMask");
279 }
280
281 // Returns the SVETypeFlags value for the given SVEType.
282 uint64_t encodeTypeFlags(const SVEType &T);
283
Sander de Smalenc5b81462020-03-18 11:07:20 +0000284 /// Emit arm_sve.h.
285 void createHeader(raw_ostream &o);
286
287 /// Emit all the __builtin prototypes and code needed by Sema.
288 void createBuiltins(raw_ostream &o);
289
290 /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
291 void createCodeGenMap(raw_ostream &o);
292
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100293 /// Emit all the range checks for the immediates.
294 void createRangeChecks(raw_ostream &o);
295
Sander de Smalenc5b81462020-03-18 11:07:20 +0000296 /// Create the SVETypeFlags used in CGBuiltins
297 void createTypeFlags(raw_ostream &o);
298
299 /// Create intrinsic and add it to \p Out
300 void createIntrinsic(Record *R, SmallVectorImpl<std::unique_ptr<Intrinsic>> &Out);
Sander de Smalen5087ace2020-03-15 14:29:45 +0000301};
302
303} // end anonymous namespace
304
305
306//===----------------------------------------------------------------------===//
Sander de Smalenc5b81462020-03-18 11:07:20 +0000307// Type implementation
Sander de Smalen8b409ea2020-03-16 10:14:05 +0000308//===----------------------------------------------------------------------===//
Sander de Smalen8b409ea2020-03-16 10:14:05 +0000309
Sander de Smalenc5b81462020-03-18 11:07:20 +0000310std::string SVEType::builtin_str() const {
311 std::string S;
312 if (isVoid())
313 return "v";
314
315 if (isVoidPointer())
316 S += "v";
317 else if (!Float)
318 switch (ElementBitwidth) {
319 case 1: S += "b"; break;
320 case 8: S += "c"; break;
321 case 16: S += "s"; break;
322 case 32: S += "i"; break;
323 case 64: S += "Wi"; break;
324 case 128: S += "LLLi"; break;
325 default: llvm_unreachable("Unhandled case!");
326 }
327 else
328 switch (ElementBitwidth) {
329 case 16: S += "h"; break;
330 case 32: S += "f"; break;
331 case 64: S += "d"; break;
332 default: llvm_unreachable("Unhandled case!");
333 }
334
335 if (!isFloat()) {
336 if ((isChar() || isPointer()) && !isVoidPointer()) {
337 // Make chars and typed pointers explicitly signed.
338 if (Signed)
339 S = "S" + S;
340 else if (!Signed)
341 S = "U" + S;
342 } else if (!isVoidPointer() && !Signed) {
343 S = "U" + S;
344 }
345 }
346
347 // Constant indices are "int", but have the "constant expression" modifier.
348 if (isImmediate()) {
349 assert(!isFloat() && "fp immediates are not supported");
350 S = "I" + S;
351 }
352
353 if (isScalar()) {
354 if (Constant) S += "C";
355 if (Pointer) S += "*";
356 return S;
357 }
358
359 assert(isScalableVector() && "Unsupported type");
360 return "q" + utostr(getNumElements() * NumVectors) + S;
361}
362
Sander de Smalen981f0802020-03-18 15:05:08 +0000363std::string SVEType::str() const {
364 if (isPredicatePattern())
365 return "sv_pattern";
366
367 if (isPrefetchOp())
368 return "sv_prfop";
369
370 std::string S;
371 if (Void)
372 S += "void";
373 else {
374 if (isScalableVector())
375 S += "sv";
376 if (!Signed && !Float)
377 S += "u";
378
379 if (Float)
380 S += "float";
381 else if (isScalarPredicate())
382 S += "bool";
383 else
384 S += "int";
385
386 if (!isScalarPredicate())
387 S += utostr(ElementBitwidth);
388 if (!isScalableVector() && isVector())
389 S += "x" + utostr(getNumElements());
390 if (NumVectors > 1)
391 S += "x" + utostr(NumVectors);
392 S += "_t";
393 }
394
395 if (Constant)
396 S += " const";
397 if (Pointer)
398 S += " *";
399
400 return S;
401}
Sander de Smalenc5b81462020-03-18 11:07:20 +0000402void SVEType::applyTypespec() {
403 for (char I : TS) {
404 switch (I) {
405 case 'P':
406 Predicate = true;
407 ElementBitwidth = 1;
408 break;
409 case 'U':
410 Signed = false;
411 break;
412 case 'c':
413 ElementBitwidth = 8;
414 break;
415 case 's':
416 ElementBitwidth = 16;
417 break;
418 case 'i':
419 ElementBitwidth = 32;
420 break;
421 case 'l':
422 ElementBitwidth = 64;
423 break;
424 case 'h':
425 Float = true;
426 ElementBitwidth = 16;
427 break;
428 case 'f':
429 Float = true;
430 ElementBitwidth = 32;
431 break;
432 case 'd':
433 Float = true;
434 ElementBitwidth = 64;
435 break;
436 default:
437 llvm_unreachable("Unhandled type code!");
438 }
439 }
440 assert(ElementBitwidth != ~0U && "Bad element bitwidth!");
441}
442
443void SVEType::applyModifier(char Mod) {
444 switch (Mod) {
445 case 'v':
446 Void = true;
447 break;
448 case 'd':
449 DefaultType = true;
450 break;
451 case 'c':
452 Constant = true;
453 LLVM_FALLTHROUGH;
454 case 'p':
455 Pointer = true;
456 Bitwidth = ElementBitwidth;
457 NumVectors = 0;
458 break;
Sander de Smalenfc645392020-04-20 14:57:13 +0100459 case 'e':
460 Signed = false;
461 ElementBitwidth /= 2;
462 break;
Sander de Smalen515020c2020-04-20 14:41:58 +0100463 case 'h':
464 ElementBitwidth /= 2;
465 break;
Sander de Smalenfc645392020-04-20 14:57:13 +0100466 case 'q':
467 ElementBitwidth /= 4;
468 break;
469 case 'o':
470 ElementBitwidth *= 4;
471 break;
Sander de Smalenc5b81462020-03-18 11:07:20 +0000472 case 'P':
473 Signed = true;
474 Float = false;
475 Predicate = true;
476 Bitwidth = 16;
477 ElementBitwidth = 1;
478 break;
Sander de Smalen515020c2020-04-20 14:41:58 +0100479 case 'u':
480 Predicate = false;
481 Signed = false;
482 Float = false;
483 break;
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100484 case 'i':
485 Predicate = false;
486 Float = false;
487 ElementBitwidth = Bitwidth = 64;
488 NumVectors = 0;
489 Signed = false;
490 Immediate = true;
491 break;
492 case 'I':
493 Predicate = false;
494 Float = false;
495 ElementBitwidth = Bitwidth = 32;
496 NumVectors = 0;
497 Signed = true;
498 Immediate = true;
499 PredicatePattern = true;
500 break;
Sander de Smalen17a68c62020-04-14 13:17:52 +0100501 case 'l':
502 Predicate = false;
503 Signed = true;
504 Float = false;
505 ElementBitwidth = Bitwidth = 64;
506 NumVectors = 0;
507 break;
508 case 'S':
509 Constant = true;
510 Pointer = true;
511 ElementBitwidth = Bitwidth = 8;
512 NumVectors = 0;
513 Signed = true;
514 break;
515 case 'W':
516 Constant = true;
517 Pointer = true;
518 ElementBitwidth = Bitwidth = 8;
519 NumVectors = 0;
520 Signed = false;
521 break;
522 case 'T':
523 Constant = true;
524 Pointer = true;
525 ElementBitwidth = Bitwidth = 16;
526 NumVectors = 0;
527 Signed = true;
528 break;
529 case 'X':
530 Constant = true;
531 Pointer = true;
532 ElementBitwidth = Bitwidth = 16;
533 NumVectors = 0;
534 Signed = false;
535 break;
536 case 'Y':
537 Constant = true;
538 Pointer = true;
539 ElementBitwidth = Bitwidth = 32;
540 NumVectors = 0;
541 Signed = false;
542 break;
543 case 'U':
544 Constant = true;
545 Pointer = true;
546 ElementBitwidth = Bitwidth = 32;
547 NumVectors = 0;
548 Signed = true;
549 break;
550 case 'A':
551 Pointer = true;
552 ElementBitwidth = Bitwidth = 8;
553 NumVectors = 0;
554 Signed = true;
555 break;
556 case 'B':
557 Pointer = true;
558 ElementBitwidth = Bitwidth = 16;
559 NumVectors = 0;
560 Signed = true;
561 break;
562 case 'C':
563 Pointer = true;
564 ElementBitwidth = Bitwidth = 32;
565 NumVectors = 0;
566 Signed = true;
567 break;
568 case 'D':
569 Pointer = true;
570 ElementBitwidth = Bitwidth = 64;
571 NumVectors = 0;
572 Signed = true;
573 break;
574 case 'E':
575 Pointer = true;
576 ElementBitwidth = Bitwidth = 8;
577 NumVectors = 0;
578 Signed = false;
579 break;
580 case 'F':
581 Pointer = true;
582 ElementBitwidth = Bitwidth = 16;
583 NumVectors = 0;
584 Signed = false;
585 break;
586 case 'G':
587 Pointer = true;
588 ElementBitwidth = Bitwidth = 32;
589 NumVectors = 0;
590 Signed = false;
591 break;
Sander de Smalenc5b81462020-03-18 11:07:20 +0000592 default:
593 llvm_unreachable("Unhandled character!");
594 }
595}
596
597
598//===----------------------------------------------------------------------===//
599// Intrinsic implementation
600//===----------------------------------------------------------------------===//
601
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100602Intrinsic::Intrinsic(StringRef Name, StringRef Proto, uint64_t MergeTy,
603 StringRef MergeSuffix, uint64_t MemoryElementTy,
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100604 StringRef LLVMName, uint64_t Flags,
605 ArrayRef<ImmCheck> Checks, TypeSpec BT, ClassKind Class,
606 SVEEmitter &Emitter, StringRef Guard)
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100607 : Name(Name.str()), LLVMName(LLVMName), Proto(Proto.str()),
608 BaseTypeSpec(BT), Class(Class), Guard(Guard.str()),
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100609 MergeSuffix(MergeSuffix.str()), BaseType(BT, 'd'), Flags(Flags),
610 ImmChecks(Checks.begin(), Checks.end()) {
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100611
612 // Types[0] is the return value.
613 for (unsigned I = 0; I < Proto.size(); ++I) {
614 SVEType T(BaseTypeSpec, Proto[I]);
615 Types.push_back(T);
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100616
617 // Add range checks for immediates
618 if (I > 0) {
619 if (T.isPredicatePattern())
620 ImmChecks.emplace_back(
621 I - 1, Emitter.getEnumValueForImmCheck("ImmCheck0_31"));
622 }
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100623 }
624
625 // Set flags based on properties
626 this->Flags |= Emitter.encodeTypeFlags(BaseType);
627 this->Flags |= Emitter.encodeMemoryElementType(MemoryElementTy);
628 this->Flags |= Emitter.encodeMergeType(MergeTy);
629}
630
Sander de Smalenc5b81462020-03-18 11:07:20 +0000631std::string Intrinsic::getBuiltinTypeStr() {
632 std::string S;
633
634 SVEType RetT = getReturnType();
635 // Since the return value must be one type, return a vector type of the
636 // appropriate width which we will bitcast. An exception is made for
637 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
638 // fashion, storing them to a pointer arg.
639 if (RetT.getNumVectors() > 1) {
640 S += "vv*"; // void result with void* first argument
641 } else
642 S += RetT.builtin_str();
643
644 for (unsigned I = 0; I < getNumParams(); ++I)
645 S += getParamType(I).builtin_str();
646
647 return S;
648}
649
650std::string Intrinsic::replaceTemplatedArgs(std::string Name, TypeSpec TS,
651 std::string Proto) const {
652 std::string Ret = Name;
653 while (Ret.find('{') != std::string::npos) {
654 size_t Pos = Ret.find('{');
655 size_t End = Ret.find('}');
656 unsigned NumChars = End - Pos + 1;
657 assert(NumChars == 3 && "Unexpected template argument");
658
659 SVEType T;
660 char C = Ret[Pos+1];
661 switch(C) {
662 default:
663 llvm_unreachable("Unknown predication specifier");
664 case 'd':
665 T = SVEType(TS, 'd');
666 break;
667 case '0':
668 case '1':
669 case '2':
670 case '3':
671 T = SVEType(TS, Proto[C - '0']);
672 break;
673 }
674
675 // Replace templated arg with the right suffix (e.g. u32)
676 std::string TypeCode;
677 if (T.isInteger())
678 TypeCode = T.isSigned() ? 's' : 'u';
679 else if (T.isPredicateVector())
680 TypeCode = 'b';
681 else
682 TypeCode = 'f';
683 Ret.replace(Pos, NumChars, TypeCode + utostr(T.getElementSizeInBits()));
684 }
685
686 return Ret;
687}
688
Sander de Smalenc5b81462020-03-18 11:07:20 +0000689std::string Intrinsic::mangleName(ClassKind LocalCK) const {
690 std::string S = getName();
691
692 if (LocalCK == ClassG) {
693 // Remove the square brackets and everything in between.
694 while (S.find("[") != std::string::npos) {
695 auto Start = S.find("[");
696 auto End = S.find(']');
697 S.erase(Start, (End-Start)+1);
698 }
699 } else {
700 // Remove the square brackets.
701 while (S.find("[") != std::string::npos) {
702 auto BrPos = S.find('[');
703 if (BrPos != std::string::npos)
704 S.erase(BrPos, 1);
705 BrPos = S.find(']');
706 if (BrPos != std::string::npos)
707 S.erase(BrPos, 1);
708 }
709 }
710
711 // Replace all {d} like expressions with e.g. 'u32'
712 return replaceTemplatedArgs(S, getBaseTypeSpec(), getProto()) +
713 getMergeSuffix();
714}
715
716void Intrinsic::emitIntrinsic(raw_ostream &OS) const {
717 // Use the preprocessor to
718 if (getClassKind() != ClassG || getProto().size() <= 1) {
719 OS << "#define " << mangleName(getClassKind())
720 << "(...) __builtin_sve_" << mangleName(ClassS)
721 << "(__VA_ARGS__)\n";
722 } else {
Sander de Smalen981f0802020-03-18 15:05:08 +0000723 std::string FullName = mangleName(ClassS);
724 std::string ProtoName = mangleName(ClassG);
725
726 OS << "__aio __attribute__((__clang_arm_builtin_alias("
727 << "__builtin_sve_" << FullName << ")))\n";
728
729 OS << getTypes()[0].str() << " " << ProtoName << "(";
730 for (unsigned I = 0; I < getTypes().size() - 1; ++I) {
731 if (I != 0)
732 OS << ", ";
733 OS << getTypes()[I + 1].str();
734 }
735 OS << ");\n";
Sander de Smalenc5b81462020-03-18 11:07:20 +0000736 }
737}
738
739//===----------------------------------------------------------------------===//
740// SVEEmitter implementation
741//===----------------------------------------------------------------------===//
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100742uint64_t SVEEmitter::encodeTypeFlags(const SVEType &T) {
743 if (T.isFloat()) {
744 switch (T.getElementSizeInBits()) {
745 case 16:
746 return encodeEltType("EltTyFloat16");
747 case 32:
748 return encodeEltType("EltTyFloat32");
749 case 64:
750 return encodeEltType("EltTyFloat64");
751 default:
752 llvm_unreachable("Unhandled float element bitwidth!");
753 }
754 }
755
756 if (T.isPredicateVector()) {
757 switch (T.getElementSizeInBits()) {
758 case 8:
759 return encodeEltType("EltTyBool8");
760 case 16:
761 return encodeEltType("EltTyBool16");
762 case 32:
763 return encodeEltType("EltTyBool32");
764 case 64:
765 return encodeEltType("EltTyBool64");
766 default:
767 llvm_unreachable("Unhandled predicate element bitwidth!");
768 }
769 }
770
771 switch (T.getElementSizeInBits()) {
772 case 8:
773 return encodeEltType("EltTyInt8");
774 case 16:
775 return encodeEltType("EltTyInt16");
776 case 32:
777 return encodeEltType("EltTyInt32");
778 case 64:
779 return encodeEltType("EltTyInt64");
780 default:
781 llvm_unreachable("Unhandled integer element bitwidth!");
782 }
783}
784
Sander de Smalenc5b81462020-03-18 11:07:20 +0000785void SVEEmitter::createIntrinsic(
786 Record *R, SmallVectorImpl<std::unique_ptr<Intrinsic>> &Out) {
787 StringRef Name = R->getValueAsString("Name");
788 StringRef Proto = R->getValueAsString("Prototype");
789 StringRef Types = R->getValueAsString("Types");
790 StringRef Guard = R->getValueAsString("ArchGuard");
791 StringRef LLVMName = R->getValueAsString("LLVMIntrinsic");
Sander de Smalenf6ea0262020-04-14 15:31:20 +0100792 uint64_t Merge = R->getValueAsInt("Merge");
793 StringRef MergeSuffix = R->getValueAsString("MergeSuffix");
794 uint64_t MemEltType = R->getValueAsInt("MemEltType");
Sander de Smalenc5b81462020-03-18 11:07:20 +0000795 std::vector<Record*> FlagsList = R->getValueAsListOfDefs("Flags");
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100796 std::vector<Record*> ImmCheckList = R->getValueAsListOfDefs("ImmChecks");
Sander de Smalenc5b81462020-03-18 11:07:20 +0000797
798 int64_t Flags = 0;
799 for (auto FlagRec : FlagsList)
800 Flags |= FlagRec->getValueAsInt("Value");
Sander de Smalenc5b81462020-03-18 11:07:20 +0000801
802 // Extract type specs from string
803 SmallVector<TypeSpec, 8> TypeSpecs;
804 TypeSpec Acc;
805 for (char I : Types) {
806 Acc.push_back(I);
807 if (islower(I)) {
808 TypeSpecs.push_back(TypeSpec(Acc));
809 Acc.clear();
810 }
811 }
812
813 // Remove duplicate type specs.
Benjamin Kramer4065e922020-03-28 19:19:55 +0100814 llvm::sort(TypeSpecs);
Sander de Smalenc5b81462020-03-18 11:07:20 +0000815 TypeSpecs.erase(std::unique(TypeSpecs.begin(), TypeSpecs.end()),
816 TypeSpecs.end());
817
818 // Create an Intrinsic for each type spec.
819 for (auto TS : TypeSpecs) {
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100820 // Collate a list of range/option checks for the immediates.
821 SmallVector<ImmCheck, 2> ImmChecks;
822 for (auto *R : ImmCheckList) {
Christopher Tetreault464a0692020-04-15 15:16:17 -0700823 int64_t Arg = R->getValueAsInt("Arg");
824 int64_t EltSizeArg = R->getValueAsInt("EltSizeArg");
825 int64_t Kind = R->getValueAsDef("Kind")->getValueAsInt("Value");
826 assert(Arg >= 0 && Kind >= 0 && "Arg and Kind must be nonnegative");
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100827
828 unsigned ElementSizeInBits = 0;
829 if (EltSizeArg >= 0)
830 ElementSizeInBits =
831 SVEType(TS, Proto[EltSizeArg + /* offset by return arg */ 1])
832 .getElementSizeInBits();
833 ImmChecks.push_back(ImmCheck(Arg, Kind, ElementSizeInBits));
834 }
835
836 Out.push_back(std::make_unique<Intrinsic>(
837 Name, Proto, Merge, MergeSuffix, MemEltType, LLVMName, Flags, ImmChecks,
838 TS, ClassS, *this, Guard));
Sander de Smalen981f0802020-03-18 15:05:08 +0000839
840 // Also generate the short-form (e.g. svadd_m) for the given type-spec.
841 if (Intrinsic::isOverloadedIntrinsic(Name))
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100842 Out.push_back(std::make_unique<Intrinsic>(
843 Name, Proto, Merge, MergeSuffix, MemEltType, LLVMName, Flags,
844 ImmChecks, TS, ClassG, *this, Guard));
Sander de Smalenc5b81462020-03-18 11:07:20 +0000845 }
846}
847
848void SVEEmitter::createHeader(raw_ostream &OS) {
Sander de Smalen5087ace2020-03-15 14:29:45 +0000849 OS << "/*===---- arm_sve.h - ARM SVE intrinsics "
850 "-----------------------------------===\n"
851 " *\n"
852 " *\n"
853 " * Part of the LLVM Project, under the Apache License v2.0 with LLVM "
854 "Exceptions.\n"
855 " * See https://llvm.org/LICENSE.txt for license information.\n"
856 " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
857 " *\n"
858 " *===-----------------------------------------------------------------"
859 "------===\n"
860 " */\n\n";
861
862 OS << "#ifndef __ARM_SVE_H\n";
863 OS << "#define __ARM_SVE_H\n\n";
864
865 OS << "#if !defined(__ARM_FEATURE_SVE)\n";
866 OS << "#error \"SVE support not enabled\"\n";
867 OS << "#else\n\n";
868
869 OS << "#include <stdint.h>\n\n";
Sander de Smalenc5b81462020-03-18 11:07:20 +0000870 OS << "#ifdef __cplusplus\n";
871 OS << "extern \"C\" {\n";
872 OS << "#else\n";
Sander de Smalen5087ace2020-03-15 14:29:45 +0000873 OS << "#include <stdbool.h>\n";
874 OS << "#endif\n\n";
875
876 OS << "typedef __fp16 float16_t;\n";
877 OS << "typedef float float32_t;\n";
878 OS << "typedef double float64_t;\n";
879 OS << "typedef bool bool_t;\n\n";
880
881 OS << "typedef __SVInt8_t svint8_t;\n";
882 OS << "typedef __SVInt16_t svint16_t;\n";
883 OS << "typedef __SVInt32_t svint32_t;\n";
884 OS << "typedef __SVInt64_t svint64_t;\n";
885 OS << "typedef __SVUint8_t svuint8_t;\n";
886 OS << "typedef __SVUint16_t svuint16_t;\n";
887 OS << "typedef __SVUint32_t svuint32_t;\n";
888 OS << "typedef __SVUint64_t svuint64_t;\n";
889 OS << "typedef __SVFloat16_t svfloat16_t;\n";
890 OS << "typedef __SVFloat32_t svfloat32_t;\n";
891 OS << "typedef __SVFloat64_t svfloat64_t;\n";
892 OS << "typedef __SVBool_t svbool_t;\n\n";
893
Sander de Smalenc8a5b302020-04-14 15:56:36 +0100894 OS << "typedef enum\n";
895 OS << "{\n";
896 OS << " SV_POW2 = 0,\n";
897 OS << " SV_VL1 = 1,\n";
898 OS << " SV_VL2 = 2,\n";
899 OS << " SV_VL3 = 3,\n";
900 OS << " SV_VL4 = 4,\n";
901 OS << " SV_VL5 = 5,\n";
902 OS << " SV_VL6 = 6,\n";
903 OS << " SV_VL7 = 7,\n";
904 OS << " SV_VL8 = 8,\n";
905 OS << " SV_VL16 = 9,\n";
906 OS << " SV_VL32 = 10,\n";
907 OS << " SV_VL64 = 11,\n";
908 OS << " SV_VL128 = 12,\n";
909 OS << " SV_VL256 = 13,\n";
910 OS << " SV_MUL4 = 29,\n";
911 OS << " SV_MUL3 = 30,\n";
912 OS << " SV_ALL = 31\n";
913 OS << "} sv_pattern;\n\n";
914
Sander de Smalen981f0802020-03-18 15:05:08 +0000915 OS << "/* Function attributes */\n";
916 OS << "#define __aio static inline __attribute__((__always_inline__, "
917 "__nodebug__, __overloadable__))\n\n";
918
Sander de Smalenc5b81462020-03-18 11:07:20 +0000919 SmallVector<std::unique_ptr<Intrinsic>, 128> Defs;
920 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
921 for (auto *R : RV)
922 createIntrinsic(R, Defs);
Sander de Smalen5087ace2020-03-15 14:29:45 +0000923
Sander de Smalenc5b81462020-03-18 11:07:20 +0000924 // Sort intrinsics in header file by following order/priority:
925 // - Architectural guard (i.e. does it require SVE2 or SVE2_AES)
926 // - Class (is intrinsic overloaded or not)
927 // - Intrinsic name
928 std::stable_sort(
929 Defs.begin(), Defs.end(), [](const std::unique_ptr<Intrinsic> &A,
930 const std::unique_ptr<Intrinsic> &B) {
Eric Fiselieraf2968e2020-04-16 18:35:31 -0400931 auto ToTuple = [](const std::unique_ptr<Intrinsic> &I) {
932 return std::make_tuple(I->getGuard(), (unsigned)I->getClassKind(), I->getName());
933 };
934 return ToTuple(A) < ToTuple(B);
Sander de Smalenc5b81462020-03-18 11:07:20 +0000935 });
936
937 StringRef InGuard = "";
938 for (auto &I : Defs) {
939 // Emit #endif/#if pair if needed.
940 if (I->getGuard() != InGuard) {
941 if (!InGuard.empty())
942 OS << "#endif //" << InGuard << "\n";
943 InGuard = I->getGuard();
944 if (!InGuard.empty())
945 OS << "\n#if " << InGuard << "\n";
946 }
947
948 // Actually emit the intrinsic declaration.
949 I->emitIntrinsic(OS);
950 }
951
952 if (!InGuard.empty())
953 OS << "#endif //" << InGuard << "\n";
954
955 OS << "#ifdef __cplusplus\n";
956 OS << "} // extern \"C\"\n";
957 OS << "#endif\n\n";
958 OS << "#endif /*__ARM_FEATURE_SVE */\n\n";
Sander de Smalen5087ace2020-03-15 14:29:45 +0000959 OS << "#endif /* __ARM_SVE_H */\n";
960}
961
Sander de Smalenc5b81462020-03-18 11:07:20 +0000962void SVEEmitter::createBuiltins(raw_ostream &OS) {
963 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
964 SmallVector<std::unique_ptr<Intrinsic>, 128> Defs;
965 for (auto *R : RV)
966 createIntrinsic(R, Defs);
967
968 // The mappings must be sorted based on BuiltinID.
969 llvm::sort(Defs, [](const std::unique_ptr<Intrinsic> &A,
970 const std::unique_ptr<Intrinsic> &B) {
971 return A->getMangledName() < B->getMangledName();
972 });
973
974 OS << "#ifdef GET_SVE_BUILTINS\n";
975 for (auto &Def : Defs) {
976 // Only create BUILTINs for non-overloaded intrinsics, as overloaded
977 // declarations only live in the header file.
978 if (Def->getClassKind() != ClassG)
979 OS << "BUILTIN(__builtin_sve_" << Def->getMangledName() << ", \""
980 << Def->getBuiltinTypeStr() << "\", \"n\")\n";
981 }
982 OS << "#endif\n\n";
983}
984
985void SVEEmitter::createCodeGenMap(raw_ostream &OS) {
986 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
987 SmallVector<std::unique_ptr<Intrinsic>, 128> Defs;
988 for (auto *R : RV)
989 createIntrinsic(R, Defs);
990
991 // The mappings must be sorted based on BuiltinID.
992 llvm::sort(Defs, [](const std::unique_ptr<Intrinsic> &A,
993 const std::unique_ptr<Intrinsic> &B) {
994 return A->getMangledName() < B->getMangledName();
995 });
996
997 OS << "#ifdef GET_SVE_LLVM_INTRINSIC_MAP\n";
998 for (auto &Def : Defs) {
999 // Builtins only exist for non-overloaded intrinsics, overloaded
1000 // declarations only live in the header file.
1001 if (Def->getClassKind() == ClassG)
1002 continue;
1003
Sander de Smalenf6ea0262020-04-14 15:31:20 +01001004 uint64_t Flags = Def->getFlags();
Sander de Smalenc5b81462020-03-18 11:07:20 +00001005 auto FlagString = std::to_string(Flags);
1006
1007 std::string LLVMName = Def->getLLVMName();
1008 std::string Builtin = Def->getMangledName();
1009 if (!LLVMName.empty())
1010 OS << "SVEMAP1(" << Builtin << ", " << LLVMName << ", " << FlagString
1011 << "),\n";
1012 else
1013 OS << "SVEMAP2(" << Builtin << ", " << FlagString << "),\n";
1014 }
1015 OS << "#endif\n\n";
1016}
1017
Sander de Smalenc8a5b302020-04-14 15:56:36 +01001018void SVEEmitter::createRangeChecks(raw_ostream &OS) {
1019 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
1020 SmallVector<std::unique_ptr<Intrinsic>, 128> Defs;
1021 for (auto *R : RV)
1022 createIntrinsic(R, Defs);
1023
1024 // The mappings must be sorted based on BuiltinID.
1025 llvm::sort(Defs, [](const std::unique_ptr<Intrinsic> &A,
1026 const std::unique_ptr<Intrinsic> &B) {
1027 return A->getMangledName() < B->getMangledName();
1028 });
1029
1030
1031 OS << "#ifdef GET_SVE_IMMEDIATE_CHECK\n";
1032
1033 // Ensure these are only emitted once.
1034 std::set<std::string> Emitted;
1035
1036 for (auto &Def : Defs) {
1037 if (Emitted.find(Def->getMangledName()) != Emitted.end() ||
1038 Def->getImmChecks().empty())
1039 continue;
1040
1041 OS << "case SVE::BI__builtin_sve_" << Def->getMangledName() << ":\n";
1042 for (auto &Check : Def->getImmChecks())
1043 OS << "ImmChecks.push_back(std::make_tuple(" << Check.getArg() << ", "
1044 << Check.getKind() << ", " << Check.getElementSizeInBits() << "));\n";
1045 OS << " break;\n";
1046
1047 Emitted.insert(Def->getMangledName());
1048 }
1049
1050 OS << "#endif\n\n";
1051}
1052
Sander de Smalenc5b81462020-03-18 11:07:20 +00001053/// Create the SVETypeFlags used in CGBuiltins
1054void SVEEmitter::createTypeFlags(raw_ostream &OS) {
1055 OS << "#ifdef LLVM_GET_SVE_TYPEFLAGS\n";
1056 for (auto &KV : FlagTypes)
1057 OS << "const uint64_t " << KV.getKey() << " = " << KV.getValue() << ";\n";
1058 OS << "#endif\n\n";
1059
1060 OS << "#ifdef LLVM_GET_SVE_ELTTYPES\n";
1061 for (auto &KV : EltTypes)
1062 OS << " " << KV.getKey() << " = " << KV.getValue() << ",\n";
1063 OS << "#endif\n\n";
1064
1065 OS << "#ifdef LLVM_GET_SVE_MEMELTTYPES\n";
1066 for (auto &KV : MemEltTypes)
1067 OS << " " << KV.getKey() << " = " << KV.getValue() << ",\n";
1068 OS << "#endif\n\n";
Sander de Smalenf6ea0262020-04-14 15:31:20 +01001069
1070 OS << "#ifdef LLVM_GET_SVE_MERGETYPES\n";
1071 for (auto &KV : MergeTypes)
1072 OS << " " << KV.getKey() << " = " << KV.getValue() << ",\n";
1073 OS << "#endif\n\n";
Sander de Smalenc8a5b302020-04-14 15:56:36 +01001074
1075 OS << "#ifdef LLVM_GET_SVE_IMMCHECKTYPES\n";
1076 for (auto &KV : ImmCheckTypes)
1077 OS << " " << KV.getKey() << " = " << KV.getValue() << ",\n";
1078 OS << "#endif\n\n";
Sander de Smalenc5b81462020-03-18 11:07:20 +00001079}
1080
Sander de Smalen5087ace2020-03-15 14:29:45 +00001081namespace clang {
1082void EmitSveHeader(RecordKeeper &Records, raw_ostream &OS) {
Sander de Smalenc5b81462020-03-18 11:07:20 +00001083 SVEEmitter(Records).createHeader(OS);
1084}
1085
1086void EmitSveBuiltins(RecordKeeper &Records, raw_ostream &OS) {
1087 SVEEmitter(Records).createBuiltins(OS);
1088}
1089
1090void EmitSveBuiltinCG(RecordKeeper &Records, raw_ostream &OS) {
1091 SVEEmitter(Records).createCodeGenMap(OS);
1092}
Sander de Smalenc8a5b302020-04-14 15:56:36 +01001093
1094void EmitSveRangeChecks(RecordKeeper &Records, raw_ostream &OS) {
1095 SVEEmitter(Records).createRangeChecks(OS);
1096}
1097
Sander de Smalenc5b81462020-03-18 11:07:20 +00001098void EmitSveTypeFlags(RecordKeeper &Records, raw_ostream &OS) {
1099 SVEEmitter(Records).createTypeFlags(OS);
Sander de Smalen5087ace2020-03-15 14:29:45 +00001100}
1101
1102} // End namespace clang