Coverage Report

Created: 2020-02-18 08:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/utils/TableGen/NeonEmitter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- NeonEmitter.cpp - Generate arm_neon.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_neon.h, which includes
10
// a declaration and definition of each function specified by the ARM NEON
11
// compiler interface.  See ARM document DUI0348B.
12
//
13
// Each NEON instruction is implemented in terms of 1 or more functions which
14
// are suffixed with the element type of the input vectors.  Functions may be
15
// implemented in terms of generic vector operations such as +, *, -, etc. or
16
// by calling a __builtin_-prefixed function which will be handled by clang's
17
// CodeGen library.
18
//
19
// Additional validation code can be generated by this file when runHeader() is
20
// called, rather than the normal run() entry point.
21
//
22
// See also the documentation in include/clang/Basic/arm_neon.td.
23
//
24
//===----------------------------------------------------------------------===//
25
26
#include "TableGenBackends.h"
27
#include "llvm/ADT/ArrayRef.h"
28
#include "llvm/ADT/DenseMap.h"
29
#include "llvm/ADT/None.h"
30
#include "llvm/ADT/SmallVector.h"
31
#include "llvm/ADT/STLExtras.h"
32
#include "llvm/ADT/StringExtras.h"
33
#include "llvm/ADT/StringRef.h"
34
#include "llvm/Support/Casting.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/Support/raw_ostream.h"
37
#include "llvm/TableGen/Error.h"
38
#include "llvm/TableGen/Record.h"
39
#include "llvm/TableGen/SetTheory.h"
40
#include <algorithm>
41
#include <cassert>
42
#include <cctype>
43
#include <cstddef>
44
#include <cstdint>
45
#include <deque>
46
#include <map>
47
#include <set>
48
#include <sstream>
49
#include <string>
50
#include <utility>
51
#include <vector>
52
53
using namespace llvm;
54
55
namespace {
56
57
// While globals are generally bad, this one allows us to perform assertions
58
// liberally and somehow still trace them back to the def they indirectly
59
// came from.
60
static Record *CurrentRecord = nullptr;
61
0
static void assert_with_loc(bool Assertion, const std::string &Str) {
62
0
  if (!Assertion) {
63
0
    if (CurrentRecord)
64
0
      PrintFatalError(CurrentRecord->getLoc(), Str);
65
0
    else
66
0
      PrintFatalError(Str);
67
0
  }
68
0
}
69
70
enum ClassKind {
71
  ClassNone,
72
  ClassI,     // generic integer instruction, e.g., "i8" suffix
73
  ClassS,     // signed/unsigned/poly, e.g., "s8", "u8" or "p8" suffix
74
  ClassW,     // width-specific instruction, e.g., "8" suffix
75
  ClassB,     // bitcast arguments with enum argument to specify type
76
  ClassL,     // Logical instructions which are op instructions
77
              // but we need to not emit any suffix for in our
78
              // tests.
79
  ClassNoTest // Instructions which we do not test since they are
80
              // not TRUE instructions.
81
};
82
83
/// NeonTypeFlags - Flags to identify the types for overloaded Neon
84
/// builtins.  These must be kept in sync with the flags in
85
/// include/clang/Basic/TargetBuiltins.h.
86
namespace NeonTypeFlags {
87
88
enum { EltTypeMask = 0xf, UnsignedFlag = 0x10, QuadFlag = 0x20 };
89
90
enum EltType {
91
  Int8,
92
  Int16,
93
  Int32,
94
  Int64,
95
  Poly8,
96
  Poly16,
97
  Poly64,
98
  Poly128,
99
  Float16,
100
  Float32,
101
  Float64
102
};
103
104
} // end namespace NeonTypeFlags
105
106
class NeonEmitter;
107
108
//===----------------------------------------------------------------------===//
109
// TypeSpec
110
//===----------------------------------------------------------------------===//
111
112
/// A TypeSpec is just a simple wrapper around a string, but gets its own type
113
/// for strong typing purposes.
114
///
115
/// A TypeSpec can be used to create a type.
116
class TypeSpec : public std::string {
117
public:
118
0
  static std::vector<TypeSpec> fromTypeSpecs(StringRef Str) {
119
0
    std::vector<TypeSpec> Ret;
120
0
    TypeSpec Acc;
121
0
    for (char I : Str.str()) {
122
0
      if (islower(I)) {
123
0
        Acc.push_back(I);
124
0
        Ret.push_back(TypeSpec(Acc));
125
0
        Acc.clear();
126
0
      } else {
127
0
        Acc.push_back(I);
128
0
      }
129
0
    }
130
0
    return Ret;
131
0
  }
132
};
133
134
//===----------------------------------------------------------------------===//
135
// Type
136
//===----------------------------------------------------------------------===//
137
138
/// A Type. Not much more to say here.
139
class Type {
140
private:
141
  TypeSpec TS;
142
143
  enum TypeKind {
144
    Void,
145
    Float,
146
    SInt,
147
    UInt,
148
    Poly,
149
  };
150
  TypeKind Kind;
151
  bool Immediate, Constant, Pointer;
152
  // ScalarForMangling and NoManglingQ are really not suited to live here as
153
  // they are not related to the type. But they live in the TypeSpec (not the
154
  // prototype), so this is really the only place to store them.
155
  bool ScalarForMangling, NoManglingQ;
156
  unsigned Bitwidth, ElementBitwidth, NumVectors;
157
158
public:
159
  Type()
160
      : Kind(Void), Immediate(false), Constant(false),
161
        Pointer(false), ScalarForMangling(false), NoManglingQ(false),
162
0
        Bitwidth(0), ElementBitwidth(0), NumVectors(0) {}
163
164
  Type(TypeSpec TS, StringRef CharMods)
165
      : TS(std::move(TS)), Kind(Void), Immediate(false),
166
        Constant(false), Pointer(false), ScalarForMangling(false),
167
0
        NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {
168
0
    applyModifiers(CharMods);
169
0
  }
170
171
  /// Returns a type representing "void".
172
0
  static Type getVoid() { return Type(); }
173
174
0
  bool operator==(const Type &Other) const { return str() == Other.str(); }
175
0
  bool operator!=(const Type &Other) const { return !operator==(Other); }
176
177
  //
178
  // Query functions
179
  //
180
0
  bool isScalarForMangling() const { return ScalarForMangling; }
181
0
  bool noManglingQ() const { return NoManglingQ; }
182
183
0
  bool isPointer() const { return Pointer; }
184
0
  bool isValue() const { return !isVoid() && !isPointer(); }
185
0
  bool isScalar() const { return isValue() && NumVectors == 0; }
186
0
  bool isVector() const { return isValue() && NumVectors > 0; }
187
0
  bool isConstPointer() const { return Constant; }
188
0
  bool isFloating() const { return Kind == Float; }
189
0
  bool isInteger() const { return Kind == SInt || Kind == UInt; }
190
0
  bool isPoly() const { return Kind == Poly; }
191
0
  bool isSigned() const { return Kind == SInt; }
192
0
  bool isImmediate() const { return Immediate; }
193
0
  bool isFloat() const { return isFloating() && ElementBitwidth == 32; }
194
0
  bool isDouble() const { return isFloating() && ElementBitwidth == 64; }
195
0
  bool isHalf() const { return isFloating() && ElementBitwidth == 16; }
196
0
  bool isChar() const { return ElementBitwidth == 8; }
197
0
  bool isShort() const { return isInteger() && ElementBitwidth == 16; }
198
0
  bool isInt() const { return isInteger() && ElementBitwidth == 32; }
199
0
  bool isLong() const { return isInteger() && ElementBitwidth == 64; }
200
0
  bool isVoid() const { return Kind == Void; }
201
0
  unsigned getNumElements() const { return Bitwidth / ElementBitwidth; }
202
0
  unsigned getSizeInBits() const { return Bitwidth; }
203
0
  unsigned getElementSizeInBits() const { return ElementBitwidth; }
204
0
  unsigned getNumVectors() const { return NumVectors; }
205
206
  //
207
  // Mutator functions
208
  //
209
0
  void makeUnsigned() {
210
0
    assert(!isVoid() && "not a potentially signed type");
211
0
    Kind = UInt;
212
0
  }
213
0
  void makeSigned() {
214
0
    assert(!isVoid() && "not a potentially signed type");
215
0
    Kind = SInt;
216
0
  }
217
218
0
  void makeInteger(unsigned ElemWidth, bool Sign) {
219
0
    assert(!isVoid() && "converting void to int probably not useful");
220
0
    Kind = Sign ? SInt : UInt;
221
0
    Immediate = false;
222
0
    ElementBitwidth = ElemWidth;
223
0
  }
224
225
0
  void makeImmediate(unsigned ElemWidth) {
226
0
    Kind = SInt;
227
0
    Immediate = true;
228
0
    ElementBitwidth = ElemWidth;
229
0
  }
230
231
0
  void makeScalar() {
232
0
    Bitwidth = ElementBitwidth;
233
0
    NumVectors = 0;
234
0
  }
235
236
0
  void makeOneVector() {
237
0
    assert(isVector());
238
0
    NumVectors = 1;
239
0
  }
240
241
0
  void doubleLanes() {
242
0
    assert_with_loc(Bitwidth != 128, "Can't get bigger than 128!");
243
0
    Bitwidth = 128;
244
0
  }
245
246
0
  void halveLanes() {
247
0
    assert_with_loc(Bitwidth != 64, "Can't get smaller than 64!");
248
0
    Bitwidth = 64;
249
0
  }
250
251
  /// Return the C string representation of a type, which is the typename
252
  /// defined in stdint.h or arm_neon.h.
253
  std::string str() const;
254
255
  /// Return the string representation of a type, which is an encoded
256
  /// string for passing to the BUILTIN() macro in Builtins.def.
257
  std::string builtin_str() const;
258
259
  /// Return the value in NeonTypeFlags for this type.
260
  unsigned getNeonEnum() const;
261
262
  /// Parse a type from a stdint.h or arm_neon.h typedef name,
263
  /// for example uint32x2_t or int64_t.
264
  static Type fromTypedefName(StringRef Name);
265
266
private:
267
  /// Creates the type based on the typespec string in TS.
268
  /// Sets "Quad" to true if the "Q" or "H" modifiers were
269
  /// seen. This is needed by applyModifier as some modifiers
270
  /// only take effect if the type size was changed by "Q" or "H".
271
  void applyTypespec(bool &Quad);
272
  /// Applies prototype modifiers to the type.
273
  void applyModifiers(StringRef Mods);
274
};
275
276
//===----------------------------------------------------------------------===//
277
// Variable
278
//===----------------------------------------------------------------------===//
279
280
/// A variable is a simple class that just has a type and a name.
281
class Variable {
282
  Type T;
283
  std::string N;
284
285
public:
286
0
  Variable() : T(Type::getVoid()), N("") {}
287
0
  Variable(Type T, std::string N) : T(std::move(T)), N(std::move(N)) {}
288
289
0
  Type getType() const { return T; }
290
0
  std::string getName() const { return "__" + N; }
291
};
292
293
//===----------------------------------------------------------------------===//
294
// Intrinsic
295
//===----------------------------------------------------------------------===//
296
297
/// The main grunt class. This represents an instantiation of an intrinsic with
298
/// a particular typespec and prototype.
299
class Intrinsic {
300
  friend class DagEmitter;
301
302
  /// The Record this intrinsic was created from.
303
  Record *R;
304
  /// The unmangled name.
305
  std::string Name;
306
  /// The input and output typespecs. InTS == OutTS except when
307
  /// CartesianProductOfTypes is 1 - this is the case for vreinterpret.
308
  TypeSpec OutTS, InTS;
309
  /// The base class kind. Most intrinsics use ClassS, which has full type
310
  /// info for integers (s32/u32). Some use ClassI, which doesn't care about
311
  /// signedness (i32), while some (ClassB) have no type at all, only a width
312
  /// (32).
313
  ClassKind CK;
314
  /// The list of DAGs for the body. May be empty, in which case we should
315
  /// emit a builtin call.
316
  ListInit *Body;
317
  /// The architectural #ifdef guard.
318
  std::string Guard;
319
  /// Set if the Unavailable bit is 1. This means we don't generate a body,
320
  /// just an "unavailable" attribute on a declaration.
321
  bool IsUnavailable;
322
  /// Is this intrinsic safe for big-endian? or does it need its arguments
323
  /// reversing?
324
  bool BigEndianSafe;
325
326
  /// The types of return value [0] and parameters [1..].
327
  std::vector<Type> Types;
328
  /// The index of the key type passed to CGBuiltin.cpp for polymorphic calls.
329
  int PolymorphicKeyType;
330
  /// The local variables defined.
331
  std::map<std::string, Variable> Variables;
332
  /// NeededEarly - set if any other intrinsic depends on this intrinsic.
333
  bool NeededEarly;
334
  /// UseMacro - set if we should implement using a macro or unset for a
335
  ///            function.
336
  bool UseMacro;
337
  /// The set of intrinsics that this intrinsic uses/requires.
338
  std::set<Intrinsic *> Dependencies;
339
  /// The "base type", which is Type('d', OutTS). InBaseType is only
340
  /// different if CartesianProductOfTypes = 1 (for vreinterpret).
341
  Type BaseType, InBaseType;
342
  /// The return variable.
343
  Variable RetVar;
344
  /// A postfix to apply to every variable. Defaults to "".
345
  std::string VariablePostfix;
346
347
  NeonEmitter &Emitter;
348
  std::stringstream OS;
349
350
0
  bool isBigEndianSafe() const {
351
0
    if (BigEndianSafe)
352
0
      return true;
353
0
354
0
    for (const auto &T : Types){
355
0
      if (T.isVector() && T.getNumElements() > 1)
356
0
        return false;
357
0
    }
358
0
    return true;
359
0
  }
360
361
public:
362
  Intrinsic(Record *R, StringRef Name, StringRef Proto, TypeSpec OutTS,
363
            TypeSpec InTS, ClassKind CK, ListInit *Body, NeonEmitter &Emitter,
364
            StringRef Guard, bool IsUnavailable, bool BigEndianSafe)
365
      : R(R), Name(Name.str()), OutTS(OutTS), InTS(InTS), CK(CK), Body(Body),
366
        Guard(Guard.str()), IsUnavailable(IsUnavailable),
367
        BigEndianSafe(BigEndianSafe), PolymorphicKeyType(0), NeededEarly(false),
368
        UseMacro(false), BaseType(OutTS, "."), InBaseType(InTS, "."),
369
0
        Emitter(Emitter) {
370
0
    // Modify the TypeSpec per-argument to get a concrete Type, and create
371
0
    // known variables for each.
372
0
    // Types[0] is the return value.
373
0
    unsigned Pos = 0;
374
0
    Types.emplace_back(OutTS, getNextModifiers(Proto, Pos));
375
0
    StringRef Mods = getNextModifiers(Proto, Pos);
376
0
    while (!Mods.empty()) {
377
0
      Types.emplace_back(InTS, Mods);
378
0
      if (Mods.find("!") != StringRef::npos)
379
0
        PolymorphicKeyType = Types.size() - 1;
380
0
381
0
      Mods = getNextModifiers(Proto, Pos);
382
0
    }
383
0
384
0
    for (auto Type : Types) {
385
0
      // If this builtin takes an immediate argument, we need to #define it rather
386
0
      // than use a standard declaration, so that SemaChecking can range check
387
0
      // the immediate passed by the user.
388
0
389
0
      // Pointer arguments need to use macros to avoid hiding aligned attributes
390
0
      // from the pointer type.
391
0
392
0
      // It is not permitted to pass or return an __fp16 by value, so intrinsics
393
0
      // taking a scalar float16_t must be implemented as macros.
394
0
      if (Type.isImmediate() || Type.isPointer() ||
395
0
          (Type.isScalar() && Type.isHalf()))
396
0
        UseMacro = true;
397
0
    }
398
0
  }
399
400
  /// Get the Record that this intrinsic is based off.
401
0
  Record *getRecord() const { return R; }
402
  /// Get the set of Intrinsics that this intrinsic calls.
403
  /// this is the set of immediate dependencies, NOT the
404
  /// transitive closure.
405
0
  const std::set<Intrinsic *> &getDependencies() const { return Dependencies; }
406
  /// Get the architectural guard string (#ifdef).
407
0
  std::string getGuard() const { return Guard; }
408
  /// Get the non-mangled name.
409
0
  std::string getName() const { return Name; }
410
411
  /// Return true if the intrinsic takes an immediate operand.
412
0
  bool hasImmediate() const {
413
0
    return std::any_of(Types.begin(), Types.end(),
414
0
                       [](const Type &T) { return T.isImmediate(); });
415
0
  }
416
417
  /// Return the parameter index of the immediate operand.
418
0
  unsigned getImmediateIdx() const {
419
0
    for (unsigned Idx = 0; Idx < Types.size(); ++Idx)
420
0
      if (Types[Idx].isImmediate())
421
0
        return Idx - 1;
422
0
    llvm_unreachable("Intrinsic has no immediate");
423
0
  }
424
425
426
0
  unsigned getNumParams() const { return Types.size() - 1; }
427
0
  Type getReturnType() const { return Types[0]; }
428
0
  Type getParamType(unsigned I) const { return Types[I + 1]; }
429
0
  Type getBaseType() const { return BaseType; }
430
0
  Type getPolymorphicKeyType() const { return Types[PolymorphicKeyType]; }
431
432
  /// Return true if the prototype has a scalar argument.
433
  bool protoHasScalar() const;
434
435
  /// Return the index that parameter PIndex will sit at
436
  /// in a generated function call. This is often just PIndex,
437
  /// but may not be as things such as multiple-vector operands
438
  /// and sret parameters need to be taken into accont.
439
0
  unsigned getGeneratedParamIdx(unsigned PIndex) {
440
0
    unsigned Idx = 0;
441
0
    if (getReturnType().getNumVectors() > 1)
442
0
      // Multiple vectors are passed as sret.
443
0
      ++Idx;
444
0
445
0
    for (unsigned I = 0; I < PIndex; ++I)
446
0
      Idx += std::max(1U, getParamType(I).getNumVectors());
447
0
448
0
    return Idx;
449
0
  }
450
451
0
  bool hasBody() const { return Body && !Body->getValues().empty(); }
452
453
0
  void setNeededEarly() { NeededEarly = true; }
454
455
0
  bool operator<(const Intrinsic &Other) const {
456
0
    // Sort lexicographically on a two-tuple (Guard, Name)
457
0
    if (Guard != Other.Guard)
458
0
      return Guard < Other.Guard;
459
0
    return Name < Other.Name;
460
0
  }
461
462
0
  ClassKind getClassKind(bool UseClassBIfScalar = false) {
463
0
    if (UseClassBIfScalar && !protoHasScalar())
464
0
      return ClassB;
465
0
    return CK;
466
0
  }
467
468
  /// Return the name, mangled with type information.
469
  /// If ForceClassS is true, use ClassS (u32/s32) instead
470
  /// of the intrinsic's own type class.
471
  std::string getMangledName(bool ForceClassS = false) const;
472
  /// Return the type code for a builtin function call.
473
  std::string getInstTypeCode(Type T, ClassKind CK) const;
474
  /// Return the type string for a BUILTIN() macro in Builtins.def.
475
  std::string getBuiltinTypeStr();
476
477
  /// Generate the intrinsic, returning code.
478
  std::string generate();
479
  /// Perform type checking and populate the dependency graph, but
480
  /// don't generate code yet.
481
  void indexBody();
482
483
private:
484
  StringRef getNextModifiers(StringRef Proto, unsigned &Pos) const;
485
486
  std::string mangleName(std::string Name, ClassKind CK) const;
487
488
  void initVariables();
489
  std::string replaceParamsIn(std::string S);
490
491
  void emitBodyAsBuiltinCall();
492
493
  void generateImpl(bool ReverseArguments,
494
                    StringRef NamePrefix, StringRef CallPrefix);
495
  void emitReturn();
496
  void emitBody(StringRef CallPrefix);
497
  void emitShadowedArgs();
498
  void emitArgumentReversal();
499
  void emitReturnReversal();
500
  void emitReverseVariable(Variable &Dest, Variable &Src);
501
  void emitNewLine();
502
  void emitClosingBrace();
503
  void emitOpeningBrace();
504
  void emitPrototype(StringRef NamePrefix);
505
506
  class DagEmitter {
507
    Intrinsic &Intr;
508
    StringRef CallPrefix;
509
510
  public:
511
    DagEmitter(Intrinsic &Intr, StringRef CallPrefix) :
512
0
      Intr(Intr), CallPrefix(CallPrefix) {
513
0
    }
514
    std::pair<Type, std::string> emitDagArg(Init *Arg, std::string ArgName);
515
    std::pair<Type, std::string> emitDagSaveTemp(DagInit *DI);
516
    std::pair<Type, std::string> emitDagSplat(DagInit *DI);
517
    std::pair<Type, std::string> emitDagDup(DagInit *DI);
518
    std::pair<Type, std::string> emitDagDupTyped(DagInit *DI);
519
    std::pair<Type, std::string> emitDagShuffle(DagInit *DI);
520
    std::pair<Type, std::string> emitDagCast(DagInit *DI, bool IsBitCast);
521
    std::pair<Type, std::string> emitDagCall(DagInit *DI);
522
    std::pair<Type, std::string> emitDagNameReplace(DagInit *DI);
523
    std::pair<Type, std::string> emitDagLiteral(DagInit *DI);
524
    std::pair<Type, std::string> emitDagOp(DagInit *DI);
525
    std::pair<Type, std::string> emitDag(DagInit *DI);
526
  };
527
};
528
529
//===----------------------------------------------------------------------===//
530
// NeonEmitter
531
//===----------------------------------------------------------------------===//
532
533
class NeonEmitter {
534
  RecordKeeper &Records;
535
  DenseMap<Record *, ClassKind> ClassMap;
536
  std::map<std::string, std::deque<Intrinsic>> IntrinsicMap;
537
  unsigned UniqueNumber;
538
539
  void createIntrinsic(Record *R, SmallVectorImpl<Intrinsic *> &Out);
540
  void genBuiltinsDef(raw_ostream &OS, SmallVectorImpl<Intrinsic *> &Defs);
541
  void genOverloadTypeCheckCode(raw_ostream &OS,
542
                                SmallVectorImpl<Intrinsic *> &Defs);
543
  void genIntrinsicRangeCheckCode(raw_ostream &OS,
544
                                  SmallVectorImpl<Intrinsic *> &Defs);
545
546
public:
547
  /// Called by Intrinsic - this attempts to get an intrinsic that takes
548
  /// the given types as arguments.
549
  Intrinsic &getIntrinsic(StringRef Name, ArrayRef<Type> Types);
550
551
  /// Called by Intrinsic - returns a globally-unique number.
552
0
  unsigned getUniqueNumber() { return UniqueNumber++; }
553
554
0
  NeonEmitter(RecordKeeper &R) : Records(R), UniqueNumber(0) {
555
0
    Record *SI = R.getClass("SInst");
556
0
    Record *II = R.getClass("IInst");
557
0
    Record *WI = R.getClass("WInst");
558
0
    Record *SOpI = R.getClass("SOpInst");
559
0
    Record *IOpI = R.getClass("IOpInst");
560
0
    Record *WOpI = R.getClass("WOpInst");
561
0
    Record *LOpI = R.getClass("LOpInst");
562
0
    Record *NoTestOpI = R.getClass("NoTestOpInst");
563
0
564
0
    ClassMap[SI] = ClassS;
565
0
    ClassMap[II] = ClassI;
566
0
    ClassMap[WI] = ClassW;
567
0
    ClassMap[SOpI] = ClassS;
568
0
    ClassMap[IOpI] = ClassI;
569
0
    ClassMap[WOpI] = ClassW;
570
0
    ClassMap[LOpI] = ClassL;
571
0
    ClassMap[NoTestOpI] = ClassNoTest;
572
0
  }
573
574
  // run - Emit arm_neon.h.inc
575
  void run(raw_ostream &o);
576
577
  // runFP16 - Emit arm_fp16.h.inc
578
  void runFP16(raw_ostream &o);
579
580
  // runHeader - Emit all the __builtin prototypes used in arm_neon.h
581
  // and arm_fp16.h
582
  void runHeader(raw_ostream &o);
583
584
  // runTests - Emit tests for all the Neon intrinsics.
585
  void runTests(raw_ostream &o);
586
};
587
588
} // end anonymous namespace
589
590
//===----------------------------------------------------------------------===//
591
// Type implementation
592
//===----------------------------------------------------------------------===//
593
594
0
std::string Type::str() const {
595
0
  if (isVoid())
596
0
    return "void";
597
0
  std::string S;
598
0
599
0
  if (isInteger() && !isSigned())
600
0
    S += "u";
601
0
602
0
  if (isPoly())
603
0
    S += "poly";
604
0
  else if (isFloating())
605
0
    S += "float";
606
0
  else
607
0
    S += "int";
608
0
609
0
  S += utostr(ElementBitwidth);
610
0
  if (isVector())
611
0
    S += "x" + utostr(getNumElements());
612
0
  if (NumVectors > 1)
613
0
    S += "x" + utostr(NumVectors);
614
0
  S += "_t";
615
0
616
0
  if (Constant)
617
0
    S += " const";
618
0
  if (Pointer)
619
0
    S += " *";
620
0
621
0
  return S;
622
0
}
623
624
0
std::string Type::builtin_str() const {
625
0
  std::string S;
626
0
  if (isVoid())
627
0
    return "v";
628
0
629
0
  if (isPointer()) {
630
0
    // All pointers are void pointers.
631
0
    S = "v";
632
0
    if (isConstPointer())
633
0
      S += "C";
634
0
    S += "*";
635
0
    return S;
636
0
  } else if (isInteger())
637
0
    switch (ElementBitwidth) {
638
0
    case 8: S += "c"; break;
639
0
    case 16: S += "s"; break;
640
0
    case 32: S += "i"; break;
641
0
    case 64: S += "Wi"; break;
642
0
    case 128: S += "LLLi"; break;
643
0
    default: llvm_unreachable("Unhandled case!");
644
0
    }
645
0
  else
646
0
    switch (ElementBitwidth) {
647
0
    case 16: S += "h"; break;
648
0
    case 32: S += "f"; break;
649
0
    case 64: S += "d"; break;
650
0
    default: llvm_unreachable("Unhandled case!");
651
0
    }
652
0
653
0
  // FIXME: NECESSARY???????????????????????????????????????????????????????????????????????
654
0
  if (isChar() && !isPointer() && isSigned())
655
0
    // Make chars explicitly signed.
656
0
    S = "S" + S;
657
0
  else if (isInteger() && !isSigned())
658
0
    S = "U" + S;
659
0
660
0
  // Constant indices are "int", but have the "constant expression" modifier.
661
0
  if (isImmediate()) {
662
0
    assert(isInteger() && isSigned());
663
0
    S = "I" + S;
664
0
  }
665
0
666
0
  if (isScalar())
667
0
    return S;
668
0
669
0
  std::string Ret;
670
0
  for (unsigned I = 0; I < NumVectors; ++I)
671
0
    Ret += "V" + utostr(getNumElements()) + S;
672
0
673
0
  return Ret;
674
0
}
675
676
0
unsigned Type::getNeonEnum() const {
677
0
  unsigned Addend;
678
0
  switch (ElementBitwidth) {
679
0
  case 8: Addend = 0; break;
680
0
  case 16: Addend = 1; break;
681
0
  case 32: Addend = 2; break;
682
0
  case 64: Addend = 3; break;
683
0
  case 128: Addend = 4; break;
684
0
  default: llvm_unreachable("Unhandled element bitwidth!");
685
0
  }
686
0
687
0
  unsigned Base = (unsigned)NeonTypeFlags::Int8 + Addend;
688
0
  if (isPoly()) {
689
0
    // Adjustment needed because Poly32 doesn't exist.
690
0
    if (Addend >= 2)
691
0
      --Addend;
692
0
    Base = (unsigned)NeonTypeFlags::Poly8 + Addend;
693
0
  }
694
0
  if (isFloating()) {
695
0
    assert(Addend != 0 && "Float8 doesn't exist!");
696
0
    Base = (unsigned)NeonTypeFlags::Float16 + (Addend - 1);
697
0
  }
698
0
699
0
  if (Bitwidth == 128)
700
0
    Base |= (unsigned)NeonTypeFlags::QuadFlag;
701
0
  if (isInteger() && !isSigned())
702
0
    Base |= (unsigned)NeonTypeFlags::UnsignedFlag;
703
0
704
0
  return Base;
705
0
}
706
707
0
Type Type::fromTypedefName(StringRef Name) {
708
0
  Type T;
709
0
  T.Kind = SInt;
710
0
711
0
  if (Name.front() == 'u') {
712
0
    T.Kind = UInt;
713
0
    Name = Name.drop_front();
714
0
  }
715
0
716
0
  if (Name.startswith("float")) {
717
0
    T.Kind = Float;
718
0
    Name = Name.drop_front(5);
719
0
  } else if (Name.startswith("poly")) {
720
0
    T.Kind = Poly;
721
0
    Name = Name.drop_front(4);
722
0
  } else {
723
0
    assert(Name.startswith("int"));
724
0
    Name = Name.drop_front(3);
725
0
  }
726
0
727
0
  unsigned I = 0;
728
0
  for (I = 0; I < Name.size(); ++I) {
729
0
    if (!isdigit(Name[I]))
730
0
      break;
731
0
  }
732
0
  Name.substr(0, I).getAsInteger(10, T.ElementBitwidth);
733
0
  Name = Name.drop_front(I);
734
0
735
0
  T.Bitwidth = T.ElementBitwidth;
736
0
  T.NumVectors = 1;
737
0
738
0
  if (Name.front() == 'x') {
739
0
    Name = Name.drop_front();
740
0
    unsigned I = 0;
741
0
    for (I = 0; I < Name.size(); ++I) {
742
0
      if (!isdigit(Name[I]))
743
0
        break;
744
0
    }
745
0
    unsigned NumLanes;
746
0
    Name.substr(0, I).getAsInteger(10, NumLanes);
747
0
    Name = Name.drop_front(I);
748
0
    T.Bitwidth = T.ElementBitwidth * NumLanes;
749
0
  } else {
750
0
    // Was scalar.
751
0
    T.NumVectors = 0;
752
0
  }
753
0
  if (Name.front() == 'x') {
754
0
    Name = Name.drop_front();
755
0
    unsigned I = 0;
756
0
    for (I = 0; I < Name.size(); ++I) {
757
0
      if (!isdigit(Name[I]))
758
0
        break;
759
0
    }
760
0
    Name.substr(0, I).getAsInteger(10, T.NumVectors);
761
0
    Name = Name.drop_front(I);
762
0
  }
763
0
764
0
  assert(Name.startswith("_t") && "Malformed typedef!");
765
0
  return T;
766
0
}
767
768
0
void Type::applyTypespec(bool &Quad) {
769
0
  std::string S = TS;
770
0
  ScalarForMangling = false;
771
0
  Kind = SInt;
772
0
  ElementBitwidth = ~0U;
773
0
  NumVectors = 1;
774
0
775
0
  for (char I : S) {
776
0
    switch (I) {
777
0
    case 'S':
778
0
      ScalarForMangling = true;
779
0
      break;
780
0
    case 'H':
781
0
      NoManglingQ = true;
782
0
      Quad = true;
783
0
      break;
784
0
    case 'Q':
785
0
      Quad = true;
786
0
      break;
787
0
    case 'P':
788
0
      Kind = Poly;
789
0
      break;
790
0
    case 'U':
791
0
      Kind = UInt;
792
0
      break;
793
0
    case 'c':
794
0
      ElementBitwidth = 8;
795
0
      break;
796
0
    case 'h':
797
0
      Kind = Float;
798
0
      LLVM_FALLTHROUGH;
799
0
    case 's':
800
0
      ElementBitwidth = 16;
801
0
      break;
802
0
    case 'f':
803
0
      Kind = Float;
804
0
      LLVM_FALLTHROUGH;
805
0
    case 'i':
806
0
      ElementBitwidth = 32;
807
0
      break;
808
0
    case 'd':
809
0
      Kind = Float;
810
0
      LLVM_FALLTHROUGH;
811
0
    case 'l':
812
0
      ElementBitwidth = 64;
813
0
      break;
814
0
    case 'k':
815
0
      ElementBitwidth = 128;
816
0
      // Poly doesn't have a 128x1 type.
817
0
      if (isPoly())
818
0
        NumVectors = 0;
819
0
      break;
820
0
    default:
821
0
      llvm_unreachable("Unhandled type code!");
822
0
    }
823
0
  }
824
0
  assert(ElementBitwidth != ~0U && "Bad element bitwidth!");
825
0
826
0
  Bitwidth = Quad ? 128 : 64;
827
0
}
828
829
0
void Type::applyModifiers(StringRef Mods) {
830
0
  bool AppliedQuad = false;
831
0
  applyTypespec(AppliedQuad);
832
0
833
0
  for (char Mod : Mods) {
834
0
    switch (Mod) {
835
0
    case '.':
836
0
      break;
837
0
    case 'v':
838
0
      Kind = Void;
839
0
      break;
840
0
    case 'S':
841
0
      Kind = SInt;
842
0
      break;
843
0
    case 'U':
844
0
      Kind = UInt;
845
0
      break;
846
0
    case 'F':
847
0
      Kind = Float;
848
0
      break;
849
0
    case 'P':
850
0
      Kind = Poly;
851
0
      break;
852
0
    case '>':
853
0
      assert(ElementBitwidth < 128);
854
0
      ElementBitwidth *= 2;
855
0
      break;
856
0
    case '<':
857
0
      assert(ElementBitwidth > 8);
858
0
      ElementBitwidth /= 2;
859
0
      break;
860
0
    case '1':
861
0
      NumVectors = 0;
862
0
      break;
863
0
    case '2':
864
0
      NumVectors = 2;
865
0
      break;
866
0
    case '3':
867
0
      NumVectors = 3;
868
0
      break;
869
0
    case '4':
870
0
      NumVectors = 4;
871
0
      break;
872
0
    case '*':
873
0
      Pointer = true;
874
0
      break;
875
0
    case 'c':
876
0
      Constant = true;
877
0
      break;
878
0
    case 'Q':
879
0
      Bitwidth = 128;
880
0
      break;
881
0
    case 'q':
882
0
      Bitwidth = 64;
883
0
      break;
884
0
    case 'I':
885
0
      Kind = SInt;
886
0
      ElementBitwidth = Bitwidth = 32;
887
0
      NumVectors = 0;
888
0
      Immediate = true;
889
0
      break;
890
0
    case 'p':
891
0
      if (isPoly())
892
0
        Kind = UInt;
893
0
      break;
894
0
    case '!':
895
0
      // Key type, handled elsewhere.
896
0
      break;
897
0
    default:
898
0
      llvm_unreachable("Unhandled character!");
899
0
    }
900
0
  }
901
0
}
902
903
//===----------------------------------------------------------------------===//
904
// Intrinsic implementation
905
//===----------------------------------------------------------------------===//
906
907
0
StringRef Intrinsic::getNextModifiers(StringRef Proto, unsigned &Pos) const {
908
0
  if (Proto.size() == Pos)
909
0
    return StringRef();
910
0
  else if (Proto[Pos] != '(')
911
0
    return Proto.substr(Pos++, 1);
912
0
913
0
  size_t Start = Pos + 1;
914
0
  size_t End = Proto.find(')', Start);
915
0
  assert_with_loc(End != StringRef::npos, "unmatched modifier group paren");
916
0
  Pos = End + 1;
917
0
  return Proto.slice(Start, End);
918
0
}
919
920
0
std::string Intrinsic::getInstTypeCode(Type T, ClassKind CK) const {
921
0
  char typeCode = '\0';
922
0
  bool printNumber = true;
923
0
924
0
  if (CK == ClassB)
925
0
    return "";
926
0
927
0
  if (T.isPoly())
928
0
    typeCode = 'p';
929
0
  else if (T.isInteger())
930
0
    typeCode = T.isSigned() ? 's' : 'u';
931
0
  else
932
0
    typeCode = 'f';
933
0
934
0
  if (CK == ClassI) {
935
0
    switch (typeCode) {
936
0
    default:
937
0
      break;
938
0
    case 's':
939
0
    case 'u':
940
0
    case 'p':
941
0
      typeCode = 'i';
942
0
      break;
943
0
    }
944
0
  }
945
0
  if (CK == ClassB) {
946
0
    typeCode = '\0';
947
0
  }
948
0
949
0
  std::string S;
950
0
  if (typeCode != '\0')
951
0
    S.push_back(typeCode);
952
0
  if (printNumber)
953
0
    S += utostr(T.getElementSizeInBits());
954
0
955
0
  return S;
956
0
}
957
958
0
std::string Intrinsic::getBuiltinTypeStr() {
959
0
  ClassKind LocalCK = getClassKind(true);
960
0
  std::string S;
961
0
962
0
  Type RetT = getReturnType();
963
0
  if ((LocalCK == ClassI || LocalCK == ClassW) && RetT.isScalar() &&
964
0
      !RetT.isFloating())
965
0
    RetT.makeInteger(RetT.getElementSizeInBits(), false);
966
0
967
0
  // Since the return value must be one type, return a vector type of the
968
0
  // appropriate width which we will bitcast.  An exception is made for
969
0
  // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
970
0
  // fashion, storing them to a pointer arg.
971
0
  if (RetT.getNumVectors() > 1) {
972
0
    S += "vv*"; // void result with void* first argument
973
0
  } else {
974
0
    if (RetT.isPoly())
975
0
      RetT.makeInteger(RetT.getElementSizeInBits(), false);
976
0
    if (!RetT.isScalar() && RetT.isInteger() && !RetT.isSigned())
977
0
      RetT.makeSigned();
978
0
979
0
    if (LocalCK == ClassB && RetT.isValue() && !RetT.isScalar())
980
0
      // Cast to vector of 8-bit elements.
981
0
      RetT.makeInteger(8, true);
982
0
983
0
    S += RetT.builtin_str();
984
0
  }
985
0
986
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
987
0
    Type T = getParamType(I);
988
0
    if (T.isPoly())
989
0
      T.makeInteger(T.getElementSizeInBits(), false);
990
0
991
0
    if (LocalCK == ClassB && !T.isScalar())
992
0
      T.makeInteger(8, true);
993
0
    // Halves always get converted to 8-bit elements.
994
0
    if (T.isHalf() && T.isVector() && !T.isScalarForMangling())
995
0
      T.makeInteger(8, true);
996
0
997
0
    if (LocalCK == ClassI && T.isInteger())
998
0
      T.makeSigned();
999
0
1000
0
    if (hasImmediate() && getImmediateIdx() == I)
1001
0
      T.makeImmediate(32);
1002
0
1003
0
    S += T.builtin_str();
1004
0
  }
1005
0
1006
0
  // Extra constant integer to hold type class enum for this function, e.g. s8
1007
0
  if (LocalCK == ClassB)
1008
0
    S += "i";
1009
0
1010
0
  return S;
1011
0
}
1012
1013
0
std::string Intrinsic::getMangledName(bool ForceClassS) const {
1014
0
  // Check if the prototype has a scalar operand with the type of the vector
1015
0
  // elements.  If not, bitcasting the args will take care of arg checking.
1016
0
  // The actual signedness etc. will be taken care of with special enums.
1017
0
  ClassKind LocalCK = CK;
1018
0
  if (!protoHasScalar())
1019
0
    LocalCK = ClassB;
1020
0
1021
0
  return mangleName(Name, ForceClassS ? ClassS : LocalCK);
1022
0
}
1023
1024
0
std::string Intrinsic::mangleName(std::string Name, ClassKind LocalCK) const {
1025
0
  std::string typeCode = getInstTypeCode(BaseType, LocalCK);
1026
0
  std::string S = Name;
1027
0
1028
0
  if (Name == "vcvt_f16_f32" || Name == "vcvt_f32_f16" ||
1029
0
      Name == "vcvt_f32_f64" || Name == "vcvt_f64_f32")
1030
0
    return Name;
1031
0
1032
0
  if (!typeCode.empty()) {
1033
0
    // If the name ends with _xN (N = 2,3,4), insert the typeCode before _xN.
1034
0
    if (Name.size() >= 3 && isdigit(Name.back()) &&
1035
0
        Name[Name.length() - 2] == 'x' && Name[Name.length() - 3] == '_')
1036
0
      S.insert(S.length() - 3, "_" + typeCode);
1037
0
    else
1038
0
      S += "_" + typeCode;
1039
0
  }
1040
0
1041
0
  if (BaseType != InBaseType) {
1042
0
    // A reinterpret - out the input base type at the end.
1043
0
    S += "_" + getInstTypeCode(InBaseType, LocalCK);
1044
0
  }
1045
0
1046
0
  if (LocalCK == ClassB)
1047
0
    S += "_v";
1048
0
1049
0
  // Insert a 'q' before the first '_' character so that it ends up before
1050
0
  // _lane or _n on vector-scalar operations.
1051
0
  if (BaseType.getSizeInBits() == 128 && !BaseType.noManglingQ()) {
1052
0
    size_t Pos = S.find('_');
1053
0
    S.insert(Pos, "q");
1054
0
  }
1055
0
1056
0
  char Suffix = '\0';
1057
0
  if (BaseType.isScalarForMangling()) {
1058
0
    switch (BaseType.getElementSizeInBits()) {
1059
0
    case 8: Suffix = 'b'; break;
1060
0
    case 16: Suffix = 'h'; break;
1061
0
    case 32: Suffix = 's'; break;
1062
0
    case 64: Suffix = 'd'; break;
1063
0
    default: llvm_unreachable("Bad suffix!");
1064
0
    }
1065
0
  }
1066
0
  if (Suffix != '\0') {
1067
0
    size_t Pos = S.find('_');
1068
0
    S.insert(Pos, &Suffix, 1);
1069
0
  }
1070
0
1071
0
  return S;
1072
0
}
1073
1074
0
std::string Intrinsic::replaceParamsIn(std::string S) {
1075
0
  while (S.find('$') != std::string::npos) {
1076
0
    size_t Pos = S.find('$');
1077
0
    size_t End = Pos + 1;
1078
0
    while (isalpha(S[End]))
1079
0
      ++End;
1080
0
1081
0
    std::string VarName = S.substr(Pos + 1, End - Pos - 1);
1082
0
    assert_with_loc(Variables.find(VarName) != Variables.end(),
1083
0
                    "Variable not defined!");
1084
0
    S.replace(Pos, End - Pos, Variables.find(VarName)->second.getName());
1085
0
  }
1086
0
1087
0
  return S;
1088
0
}
1089
1090
0
void Intrinsic::initVariables() {
1091
0
  Variables.clear();
1092
0
1093
0
  // Modify the TypeSpec per-argument to get a concrete Type, and create
1094
0
  // known variables for each.
1095
0
  for (unsigned I = 1; I < Types.size(); ++I) {
1096
0
    char NameC = '0' + (I - 1);
1097
0
    std::string Name = "p";
1098
0
    Name.push_back(NameC);
1099
0
1100
0
    Variables[Name] = Variable(Types[I], Name + VariablePostfix);
1101
0
  }
1102
0
  RetVar = Variable(Types[0], "ret" + VariablePostfix);
1103
0
}
1104
1105
0
void Intrinsic::emitPrototype(StringRef NamePrefix) {
1106
0
  if (UseMacro)
1107
0
    OS << "#define ";
1108
0
  else
1109
0
    OS << "__ai " << Types[0].str() << " ";
1110
0
1111
0
  OS << NamePrefix.str() << mangleName(Name, ClassS) << "(";
1112
0
1113
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1114
0
    if (I != 0)
1115
0
      OS << ", ";
1116
0
1117
0
    char NameC = '0' + I;
1118
0
    std::string Name = "p";
1119
0
    Name.push_back(NameC);
1120
0
    assert(Variables.find(Name) != Variables.end());
1121
0
    Variable &V = Variables[Name];
1122
0
1123
0
    if (!UseMacro)
1124
0
      OS << V.getType().str() << " ";
1125
0
    OS << V.getName();
1126
0
  }
1127
0
1128
0
  OS << ")";
1129
0
}
1130
1131
0
void Intrinsic::emitOpeningBrace() {
1132
0
  if (UseMacro)
1133
0
    OS << " __extension__ ({";
1134
0
  else
1135
0
    OS << " {";
1136
0
  emitNewLine();
1137
0
}
1138
1139
0
void Intrinsic::emitClosingBrace() {
1140
0
  if (UseMacro)
1141
0
    OS << "})";
1142
0
  else
1143
0
    OS << "}";
1144
0
}
1145
1146
0
void Intrinsic::emitNewLine() {
1147
0
  if (UseMacro)
1148
0
    OS << " \\\n";
1149
0
  else
1150
0
    OS << "\n";
1151
0
}
1152
1153
0
void Intrinsic::emitReverseVariable(Variable &Dest, Variable &Src) {
1154
0
  if (Dest.getType().getNumVectors() > 1) {
1155
0
    emitNewLine();
1156
0
1157
0
    for (unsigned K = 0; K < Dest.getType().getNumVectors(); ++K) {
1158
0
      OS << "  " << Dest.getName() << ".val[" << K << "] = "
1159
0
         << "__builtin_shufflevector("
1160
0
         << Src.getName() << ".val[" << K << "], "
1161
0
         << Src.getName() << ".val[" << K << "]";
1162
0
      for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1163
0
        OS << ", " << J;
1164
0
      OS << ");";
1165
0
      emitNewLine();
1166
0
    }
1167
0
  } else {
1168
0
    OS << "  " << Dest.getName()
1169
0
       << " = __builtin_shufflevector(" << Src.getName() << ", " << Src.getName();
1170
0
    for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1171
0
      OS << ", " << J;
1172
0
    OS << ");";
1173
0
    emitNewLine();
1174
0
  }
1175
0
}
1176
1177
0
void Intrinsic::emitArgumentReversal() {
1178
0
  if (isBigEndianSafe())
1179
0
    return;
1180
0
1181
0
  // Reverse all vector arguments.
1182
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1183
0
    std::string Name = "p" + utostr(I);
1184
0
    std::string NewName = "rev" + utostr(I);
1185
0
1186
0
    Variable &V = Variables[Name];
1187
0
    Variable NewV(V.getType(), NewName + VariablePostfix);
1188
0
1189
0
    if (!NewV.getType().isVector() || NewV.getType().getNumElements() == 1)
1190
0
      continue;
1191
0
1192
0
    OS << "  " << NewV.getType().str() << " " << NewV.getName() << ";";
1193
0
    emitReverseVariable(NewV, V);
1194
0
    V = NewV;
1195
0
  }
1196
0
}
1197
1198
0
void Intrinsic::emitReturnReversal() {
1199
0
  if (isBigEndianSafe())
1200
0
    return;
1201
0
  if (!getReturnType().isVector() || getReturnType().isVoid() ||
1202
0
      getReturnType().getNumElements() == 1)
1203
0
    return;
1204
0
  emitReverseVariable(RetVar, RetVar);
1205
0
}
1206
1207
0
void Intrinsic::emitShadowedArgs() {
1208
0
  // Macro arguments are not type-checked like inline function arguments,
1209
0
  // so assign them to local temporaries to get the right type checking.
1210
0
  if (!UseMacro)
1211
0
    return;
1212
0
1213
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1214
0
    // Do not create a temporary for an immediate argument.
1215
0
    // That would defeat the whole point of using a macro!
1216
0
    if (getParamType(I).isImmediate())
1217
0
      continue;
1218
0
    // Do not create a temporary for pointer arguments. The input
1219
0
    // pointer may have an alignment hint.
1220
0
    if (getParamType(I).isPointer())
1221
0
      continue;
1222
0
1223
0
    std::string Name = "p" + utostr(I);
1224
0
1225
0
    assert(Variables.find(Name) != Variables.end());
1226
0
    Variable &V = Variables[Name];
1227
0
1228
0
    std::string NewName = "s" + utostr(I);
1229
0
    Variable V2(V.getType(), NewName + VariablePostfix);
1230
0
1231
0
    OS << "  " << V2.getType().str() << " " << V2.getName() << " = "
1232
0
       << V.getName() << ";";
1233
0
    emitNewLine();
1234
0
1235
0
    V = V2;
1236
0
  }
1237
0
}
1238
1239
0
bool Intrinsic::protoHasScalar() const {
1240
0
  return std::any_of(Types.begin(), Types.end(), [](const Type &T) {
1241
0
    return T.isScalar() && !T.isImmediate();
1242
0
  });
1243
0
}
1244
1245
0
void Intrinsic::emitBodyAsBuiltinCall() {
1246
0
  std::string S;
1247
0
1248
0
  // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
1249
0
  // sret-like argument.
1250
0
  bool SRet = getReturnType().getNumVectors() >= 2;
1251
0
1252
0
  StringRef N = Name;
1253
0
  ClassKind LocalCK = CK;
1254
0
  if (!protoHasScalar())
1255
0
    LocalCK = ClassB;
1256
0
1257
0
  if (!getReturnType().isVoid() && !SRet)
1258
0
    S += "(" + RetVar.getType().str() + ") ";
1259
0
1260
0
  S += "__builtin_neon_" + mangleName(std::string(N), LocalCK) + "(";
1261
0
1262
0
  if (SRet)
1263
0
    S += "&" + RetVar.getName() + ", ";
1264
0
1265
0
  for (unsigned I = 0; I < getNumParams(); ++I) {
1266
0
    Variable &V = Variables["p" + utostr(I)];
1267
0
    Type T = V.getType();
1268
0
1269
0
    // Handle multiple-vector values specially, emitting each subvector as an
1270
0
    // argument to the builtin.
1271
0
    if (T.getNumVectors() > 1) {
1272
0
      // Check if an explicit cast is needed.
1273
0
      std::string Cast;
1274
0
      if (LocalCK == ClassB) {
1275
0
        Type T2 = T;
1276
0
        T2.makeOneVector();
1277
0
        T2.makeInteger(8, /*Signed=*/true);
1278
0
        Cast = "(" + T2.str() + ")";
1279
0
      }
1280
0
1281
0
      for (unsigned J = 0; J < T.getNumVectors(); ++J)
1282
0
        S += Cast + V.getName() + ".val[" + utostr(J) + "], ";
1283
0
      continue;
1284
0
    }
1285
0
1286
0
    std::string Arg = V.getName();
1287
0
    Type CastToType = T;
1288
0
1289
0
    // Check if an explicit cast is needed.
1290
0
    if (CastToType.isVector() &&
1291
0
        (LocalCK == ClassB || (T.isHalf() && !T.isScalarForMangling()))) {
1292
0
      CastToType.makeInteger(8, true);
1293
0
      Arg = "(" + CastToType.str() + ")" + Arg;
1294
0
    } else if (CastToType.isVector() && LocalCK == ClassI) {
1295
0
      if (CastToType.isInteger())
1296
0
        CastToType.makeSigned();
1297
0
      Arg = "(" + CastToType.str() + ")" + Arg;
1298
0
    }
1299
0
1300
0
    S += Arg + ", ";
1301
0
  }
1302
0
1303
0
  // Extra constant integer to hold type class enum for this function, e.g. s8
1304
0
  if (getClassKind(true) == ClassB) {
1305
0
    S += utostr(getPolymorphicKeyType().getNeonEnum());
1306
0
  } else {
1307
0
    // Remove extraneous ", ".
1308
0
    S.pop_back();
1309
0
    S.pop_back();
1310
0
  }
1311
0
  S += ");";
1312
0
1313
0
  std::string RetExpr;
1314
0
  if (!SRet && !RetVar.getType().isVoid())
1315
0
    RetExpr = RetVar.getName() + " = ";
1316
0
1317
0
  OS << "  " << RetExpr << S;
1318
0
  emitNewLine();
1319
0
}
1320
1321
0
void Intrinsic::emitBody(StringRef CallPrefix) {
1322
0
  std::vector<std::string> Lines;
1323
0
1324
0
  assert(RetVar.getType() == Types[0]);
1325
0
  // Create a return variable, if we're not void.
1326
0
  if (!RetVar.getType().isVoid()) {
1327
0
    OS << "  " << RetVar.getType().str() << " " << RetVar.getName() << ";";
1328
0
    emitNewLine();
1329
0
  }
1330
0
1331
0
  if (!Body || Body->getValues().empty()) {
1332
0
    // Nothing specific to output - must output a builtin.
1333
0
    emitBodyAsBuiltinCall();
1334
0
    return;
1335
0
  }
1336
0
1337
0
  // We have a list of "things to output". The last should be returned.
1338
0
  for (auto *I : Body->getValues()) {
1339
0
    if (StringInit *SI = dyn_cast<StringInit>(I)) {
1340
0
      Lines.push_back(replaceParamsIn(SI->getAsString()));
1341
0
    } else if (DagInit *DI = dyn_cast<DagInit>(I)) {
1342
0
      DagEmitter DE(*this, CallPrefix);
1343
0
      Lines.push_back(DE.emitDag(DI).second + ";");
1344
0
    }
1345
0
  }
1346
0
1347
0
  assert(!Lines.empty() && "Empty def?");
1348
0
  if (!RetVar.getType().isVoid())
1349
0
    Lines.back().insert(0, RetVar.getName() + " = ");
1350
0
1351
0
  for (auto &L : Lines) {
1352
0
    OS << "  " << L;
1353
0
    emitNewLine();
1354
0
  }
1355
0
}
1356
1357
0
void Intrinsic::emitReturn() {
1358
0
  if (RetVar.getType().isVoid())
1359
0
    return;
1360
0
  if (UseMacro)
1361
0
    OS << "  " << RetVar.getName() << ";";
1362
0
  else
1363
0
    OS << "  return " << RetVar.getName() << ";";
1364
0
  emitNewLine();
1365
0
}
1366
1367
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDag(DagInit *DI) {
1368
0
  // At this point we should only be seeing a def.
1369
0
  DefInit *DefI = cast<DefInit>(DI->getOperator());
1370
0
  std::string Op = DefI->getAsString();
1371
0
1372
0
  if (Op == "cast" || Op == "bitcast")
1373
0
    return emitDagCast(DI, Op == "bitcast");
1374
0
  if (Op == "shuffle")
1375
0
    return emitDagShuffle(DI);
1376
0
  if (Op == "dup")
1377
0
    return emitDagDup(DI);
1378
0
  if (Op == "dup_typed")
1379
0
    return emitDagDupTyped(DI);
1380
0
  if (Op == "splat")
1381
0
    return emitDagSplat(DI);
1382
0
  if (Op == "save_temp")
1383
0
    return emitDagSaveTemp(DI);
1384
0
  if (Op == "op")
1385
0
    return emitDagOp(DI);
1386
0
  if (Op == "call")
1387
0
    return emitDagCall(DI);
1388
0
  if (Op == "name_replace")
1389
0
    return emitDagNameReplace(DI);
1390
0
  if (Op == "literal")
1391
0
    return emitDagLiteral(DI);
1392
0
  assert_with_loc(false, "Unknown operation!");
1393
0
  return std::make_pair(Type::getVoid(), "");
1394
0
}
1395
1396
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagOp(DagInit *DI) {
1397
0
  std::string Op = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1398
0
  if (DI->getNumArgs() == 2) {
1399
0
    // Unary op.
1400
0
    std::pair<Type, std::string> R =
1401
0
        emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1402
0
    return std::make_pair(R.first, Op + R.second);
1403
0
  } else {
1404
0
    assert(DI->getNumArgs() == 3 && "Can only handle unary and binary ops!");
1405
0
    std::pair<Type, std::string> R1 =
1406
0
        emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1407
0
    std::pair<Type, std::string> R2 =
1408
0
        emitDagArg(DI->getArg(2), std::string(DI->getArgNameStr(2)));
1409
0
    assert_with_loc(R1.first == R2.first, "Argument type mismatch!");
1410
0
    return std::make_pair(R1.first, R1.second + " " + Op + " " + R2.second);
1411
0
  }
1412
0
}
1413
1414
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCall(DagInit *DI) {
1415
0
  std::vector<Type> Types;
1416
0
  std::vector<std::string> Values;
1417
0
  for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1418
0
    std::pair<Type, std::string> R =
1419
0
        emitDagArg(DI->getArg(I + 1), std::string(DI->getArgNameStr(I + 1)));
1420
0
    Types.push_back(R.first);
1421
0
    Values.push_back(R.second);
1422
0
  }
1423
0
1424
0
  // Look up the called intrinsic.
1425
0
  std::string N;
1426
0
  if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0)))
1427
0
    N = SI->getAsUnquotedString();
1428
0
  else
1429
0
    N = emitDagArg(DI->getArg(0), "").second;
1430
0
  Intrinsic &Callee = Intr.Emitter.getIntrinsic(N, Types);
1431
0
1432
0
  // Make sure the callee is known as an early def.
1433
0
  Callee.setNeededEarly();
1434
0
  Intr.Dependencies.insert(&Callee);
1435
0
1436
0
  // Now create the call itself.
1437
0
  std::string S = "";
1438
0
  if (!Callee.isBigEndianSafe())
1439
0
    S += CallPrefix.str();
1440
0
  S += Callee.getMangledName(true) + "(";
1441
0
  for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1442
0
    if (I != 0)
1443
0
      S += ", ";
1444
0
    S += Values[I];
1445
0
  }
1446
0
  S += ")";
1447
0
1448
0
  return std::make_pair(Callee.getReturnType(), S);
1449
0
}
1450
1451
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCast(DagInit *DI,
1452
0
                                                                bool IsBitCast){
1453
0
  // (cast MOD* VAL) -> cast VAL to type given by MOD.
1454
0
  std::pair<Type, std::string> R =
1455
0
      emitDagArg(DI->getArg(DI->getNumArgs() - 1),
1456
0
                 std::string(DI->getArgNameStr(DI->getNumArgs() - 1)));
1457
0
  Type castToType = R.first;
1458
0
  for (unsigned ArgIdx = 0; ArgIdx < DI->getNumArgs() - 1; ++ArgIdx) {
1459
0
1460
0
    // MOD can take several forms:
1461
0
    //   1. $X - take the type of parameter / variable X.
1462
0
    //   2. The value "R" - take the type of the return type.
1463
0
    //   3. a type string
1464
0
    //   4. The value "U" or "S" to switch the signedness.
1465
0
    //   5. The value "H" or "D" to half or double the bitwidth.
1466
0
    //   6. The value "8" to convert to 8-bit (signed) integer lanes.
1467
0
    if (!DI->getArgNameStr(ArgIdx).empty()) {
1468
0
      assert_with_loc(Intr.Variables.find(std::string(
1469
0
                          DI->getArgNameStr(ArgIdx))) != Intr.Variables.end(),
1470
0
                      "Variable not found");
1471
0
      castToType =
1472
0
          Intr.Variables[std::string(DI->getArgNameStr(ArgIdx))].getType();
1473
0
    } else {
1474
0
      StringInit *SI = dyn_cast<StringInit>(DI->getArg(ArgIdx));
1475
0
      assert_with_loc(SI, "Expected string type or $Name for cast type");
1476
0
1477
0
      if (SI->getAsUnquotedString() == "R") {
1478
0
        castToType = Intr.getReturnType();
1479
0
      } else if (SI->getAsUnquotedString() == "U") {
1480
0
        castToType.makeUnsigned();
1481
0
      } else if (SI->getAsUnquotedString() == "S") {
1482
0
        castToType.makeSigned();
1483
0
      } else if (SI->getAsUnquotedString() == "H") {
1484
0
        castToType.halveLanes();
1485
0
      } else if (SI->getAsUnquotedString() == "D") {
1486
0
        castToType.doubleLanes();
1487
0
      } else if (SI->getAsUnquotedString() == "8") {
1488
0
        castToType.makeInteger(8, true);
1489
0
      } else {
1490
0
        castToType = Type::fromTypedefName(SI->getAsUnquotedString());
1491
0
        assert_with_loc(!castToType.isVoid(), "Unknown typedef");
1492
0
      }
1493
0
    }
1494
0
  }
1495
0
1496
0
  std::string S;
1497
0
  if (IsBitCast) {
1498
0
    // Emit a reinterpret cast. The second operand must be an lvalue, so create
1499
0
    // a temporary.
1500
0
    std::string N = "reint";
1501
0
    unsigned I = 0;
1502
0
    while (Intr.Variables.find(N) != Intr.Variables.end())
1503
0
      N = "reint" + utostr(++I);
1504
0
    Intr.Variables[N] = Variable(R.first, N + Intr.VariablePostfix);
1505
0
1506
0
    Intr.OS << R.first.str() << " " << Intr.Variables[N].getName() << " = "
1507
0
            << R.second << ";";
1508
0
    Intr.emitNewLine();
1509
0
1510
0
    S = "*(" + castToType.str() + " *) &" + Intr.Variables[N].getName() + "";
1511
0
  } else {
1512
0
    // Emit a normal (static) cast.
1513
0
    S = "(" + castToType.str() + ")(" + R.second + ")";
1514
0
  }
1515
0
1516
0
  return std::make_pair(castToType, S);
1517
0
}
1518
1519
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
1520
  // See the documentation in arm_neon.td for a description of these operators.
1521
  class LowHalf : public SetTheory::Operator {
1522
  public:
1523
    void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1524
0
               ArrayRef<SMLoc> Loc) override {
1525
0
      SetTheory::RecSet Elts2;
1526
0
      ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1527
0
      Elts.insert(Elts2.begin(), Elts2.begin() + (Elts2.size() / 2));
1528
0
    }
1529
  };
1530
1531
  class HighHalf : public SetTheory::Operator {
1532
  public:
1533
    void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1534
0
               ArrayRef<SMLoc> Loc) override {
1535
0
      SetTheory::RecSet Elts2;
1536
0
      ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1537
0
      Elts.insert(Elts2.begin() + (Elts2.size() / 2), Elts2.end());
1538
0
    }
1539
  };
1540
1541
  class Rev : public SetTheory::Operator {
1542
    unsigned ElementSize;
1543
1544
  public:
1545
0
    Rev(unsigned ElementSize) : ElementSize(ElementSize) {}
1546
1547
    void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1548
0
               ArrayRef<SMLoc> Loc) override {
1549
0
      SetTheory::RecSet Elts2;
1550
0
      ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Elts2, Loc);
1551
0
1552
0
      int64_t VectorSize = cast<IntInit>(Expr->getArg(0))->getValue();
1553
0
      VectorSize /= ElementSize;
1554
0
1555
0
      std::vector<Record *> Revved;
1556
0
      for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
1557
0
        for (int LI = VectorSize - 1; LI >= 0; --LI) {
1558
0
          Revved.push_back(Elts2[VI + LI]);
1559
0
        }
1560
0
      }
1561
0
1562
0
      Elts.insert(Revved.begin(), Revved.end());
1563
0
    }
1564
  };
1565
1566
  class MaskExpander : public SetTheory::Expander {
1567
    unsigned N;
1568
1569
  public:
1570
0
    MaskExpander(unsigned N) : N(N) {}
1571
1572
0
    void expand(SetTheory &ST, Record *R, SetTheory::RecSet &Elts) override {
1573
0
      unsigned Addend = 0;
1574
0
      if (R->getName() == "mask0")
1575
0
        Addend = 0;
1576
0
      else if (R->getName() == "mask1")
1577
0
        Addend = N;
1578
0
      else
1579
0
        return;
1580
0
      for (unsigned I = 0; I < N; ++I)
1581
0
        Elts.insert(R->getRecords().getDef("sv" + utostr(I + Addend)));
1582
0
    }
1583
  };
1584
1585
  // (shuffle arg1, arg2, sequence)
1586
  std::pair<Type, std::string> Arg1 =
1587
      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1588
  std::pair<Type, std::string> Arg2 =
1589
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1590
  assert_with_loc(Arg1.first == Arg2.first,
1591
                  "Different types in arguments to shuffle!");
1592
1593
  SetTheory ST;
1594
  SetTheory::RecSet Elts;
1595
  ST.addOperator("lowhalf", std::make_unique<LowHalf>());
1596
  ST.addOperator("highhalf", std::make_unique<HighHalf>());
1597
  ST.addOperator("rev",
1598
                 std::make_unique<Rev>(Arg1.first.getElementSizeInBits()));
1599
  ST.addExpander("MaskExpand",
1600
                 std::make_unique<MaskExpander>(Arg1.first.getNumElements()));
1601
  ST.evaluate(DI->getArg(2), Elts, None);
1602
1603
  std::string S = "__builtin_shufflevector(" + Arg1.second + ", " + Arg2.second;
1604
  for (auto &E : Elts) {
1605
    StringRef Name = E->getName();
1606
    assert_with_loc(Name.startswith("sv"),
1607
                    "Incorrect element kind in shuffle mask!");
1608
    S += ", " + Name.drop_front(2).str();
1609
  }
1610
  S += ")";
1611
1612
  // Recalculate the return type - the shuffle may have halved or doubled it.
1613
  Type T(Arg1.first);
1614
  if (Elts.size() > T.getNumElements()) {
1615
    assert_with_loc(
1616
        Elts.size() == T.getNumElements() * 2,
1617
        "Can only double or half the number of elements in a shuffle!");
1618
    T.doubleLanes();
1619
  } else if (Elts.size() < T.getNumElements()) {
1620
    assert_with_loc(
1621
        Elts.size() == T.getNumElements() / 2,
1622
        "Can only double or half the number of elements in a shuffle!");
1623
    T.halveLanes();
1624
  }
1625
1626
  return std::make_pair(T, S);
1627
}
1628
1629
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDup(DagInit *DI) {
1630
0
  assert_with_loc(DI->getNumArgs() == 1, "dup() expects one argument");
1631
0
  std::pair<Type, std::string> A =
1632
0
      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1633
0
  assert_with_loc(A.first.isScalar(), "dup() expects a scalar argument");
1634
0
1635
0
  Type T = Intr.getBaseType();
1636
0
  assert_with_loc(T.isVector(), "dup() used but default type is scalar!");
1637
0
  std::string S = "(" + T.str() + ") {";
1638
0
  for (unsigned I = 0; I < T.getNumElements(); ++I) {
1639
0
    if (I != 0)
1640
0
      S += ", ";
1641
0
    S += A.second;
1642
0
  }
1643
0
  S += "}";
1644
0
1645
0
  return std::make_pair(T, S);
1646
0
}
1647
1648
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDupTyped(DagInit *DI) {
1649
0
  assert_with_loc(DI->getNumArgs() == 2, "dup_typed() expects two arguments");
1650
0
  std::pair<Type, std::string> A =
1651
0
      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1652
0
  std::pair<Type, std::string> B =
1653
0
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1654
0
  assert_with_loc(B.first.isScalar(),
1655
0
                  "dup_typed() requires a scalar as the second argument");
1656
0
1657
0
  Type T = A.first;
1658
0
  assert_with_loc(T.isVector(), "dup_typed() used but target type is scalar!");
1659
0
  std::string S = "(" + T.str() + ") {";
1660
0
  for (unsigned I = 0; I < T.getNumElements(); ++I) {
1661
0
    if (I != 0)
1662
0
      S += ", ";
1663
0
    S += B.second;
1664
0
  }
1665
0
  S += "}";
1666
0
1667
0
  return std::make_pair(T, S);
1668
0
}
1669
1670
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSplat(DagInit *DI) {
1671
0
  assert_with_loc(DI->getNumArgs() == 2, "splat() expects two arguments");
1672
0
  std::pair<Type, std::string> A =
1673
0
      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1674
0
  std::pair<Type, std::string> B =
1675
0
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1676
0
1677
0
  assert_with_loc(B.first.isScalar(),
1678
0
                  "splat() requires a scalar int as the second argument");
1679
0
1680
0
  std::string S = "__builtin_shufflevector(" + A.second + ", " + A.second;
1681
0
  for (unsigned I = 0; I < Intr.getBaseType().getNumElements(); ++I) {
1682
0
    S += ", " + B.second;
1683
0
  }
1684
0
  S += ")";
1685
0
1686
0
  return std::make_pair(Intr.getBaseType(), S);
1687
0
}
1688
1689
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSaveTemp(DagInit *DI) {
1690
0
  assert_with_loc(DI->getNumArgs() == 2, "save_temp() expects two arguments");
1691
0
  std::pair<Type, std::string> A =
1692
0
      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1693
0
1694
0
  assert_with_loc(!A.first.isVoid(),
1695
0
                  "Argument to save_temp() must have non-void type!");
1696
0
1697
0
  std::string N = std::string(DI->getArgNameStr(0));
1698
0
  assert_with_loc(!N.empty(),
1699
0
                  "save_temp() expects a name as the first argument");
1700
0
1701
0
  assert_with_loc(Intr.Variables.find(N) == Intr.Variables.end(),
1702
0
                  "Variable already defined!");
1703
0
  Intr.Variables[N] = Variable(A.first, N + Intr.VariablePostfix);
1704
0
1705
0
  std::string S =
1706
0
      A.first.str() + " " + Intr.Variables[N].getName() + " = " + A.second;
1707
0
1708
0
  return std::make_pair(Type::getVoid(), S);
1709
0
}
1710
1711
std::pair<Type, std::string>
1712
0
Intrinsic::DagEmitter::emitDagNameReplace(DagInit *DI) {
1713
0
  std::string S = Intr.Name;
1714
0
1715
0
  assert_with_loc(DI->getNumArgs() == 2, "name_replace requires 2 arguments!");
1716
0
  std::string ToReplace = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1717
0
  std::string ReplaceWith = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1718
0
1719
0
  size_t Idx = S.find(ToReplace);
1720
0
1721
0
  assert_with_loc(Idx != std::string::npos, "name should contain '" + ToReplace + "'!");
1722
0
  S.replace(Idx, ToReplace.size(), ReplaceWith);
1723
0
1724
0
  return std::make_pair(Type::getVoid(), S);
1725
0
}
1726
1727
0
std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagLiteral(DagInit *DI){
1728
0
  std::string Ty = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1729
0
  std::string Value = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1730
0
  return std::make_pair(Type::fromTypedefName(Ty), Value);
1731
0
}
1732
1733
std::pair<Type, std::string>
1734
0
Intrinsic::DagEmitter::emitDagArg(Init *Arg, std::string ArgName) {
1735
0
  if (!ArgName.empty()) {
1736
0
    assert_with_loc(!Arg->isComplete(),
1737
0
                    "Arguments must either be DAGs or names, not both!");
1738
0
    assert_with_loc(Intr.Variables.find(ArgName) != Intr.Variables.end(),
1739
0
                    "Variable not defined!");
1740
0
    Variable &V = Intr.Variables[ArgName];
1741
0
    return std::make_pair(V.getType(), V.getName());
1742
0
  }
1743
0
1744
0
  assert(Arg && "Neither ArgName nor Arg?!");
1745
0
  DagInit *DI = dyn_cast<DagInit>(Arg);
1746
0
  assert_with_loc(DI, "Arguments must either be DAGs or names!");
1747
0
1748
0
  return emitDag(DI);
1749
0
}
1750
1751
0
std::string Intrinsic::generate() {
1752
0
  // Avoid duplicated code for big and little endian
1753
0
  if (isBigEndianSafe()) {
1754
0
    generateImpl(false, "", "");
1755
0
    return OS.str();
1756
0
  }
1757
0
  // Little endian intrinsics are simple and don't require any argument
1758
0
  // swapping.
1759
0
  OS << "#ifdef __LITTLE_ENDIAN__\n";
1760
0
1761
0
  generateImpl(false, "", "");
1762
0
1763
0
  OS << "#else\n";
1764
0
1765
0
  // Big endian intrinsics are more complex. The user intended these
1766
0
  // intrinsics to operate on a vector "as-if" loaded by (V)LDR,
1767
0
  // but we load as-if (V)LD1. So we should swap all arguments and
1768
0
  // swap the return value too.
1769
0
  //
1770
0
  // If we call sub-intrinsics, we should call a version that does
1771
0
  // not re-swap the arguments!
1772
0
  generateImpl(true, "", "__noswap_");
1773
0
1774
0
  // If we're needed early, create a non-swapping variant for
1775
0
  // big-endian.
1776
0
  if (NeededEarly) {
1777
0
    generateImpl(false, "__noswap_", "__noswap_");
1778
0
  }
1779
0
  OS << "#endif\n\n";
1780
0
1781
0
  return OS.str();
1782
0
}
1783
1784
void Intrinsic::generateImpl(bool ReverseArguments,
1785
0
                             StringRef NamePrefix, StringRef CallPrefix) {
1786
0
  CurrentRecord = R;
1787
0
1788
0
  // If we call a macro, our local variables may be corrupted due to
1789
0
  // lack of proper lexical scoping. So, add a globally unique postfix
1790
0
  // to every variable.
1791
0
  //
1792
0
  // indexBody() should have set up the Dependencies set by now.
1793
0
  for (auto *I : Dependencies)
1794
0
    if (I->UseMacro) {
1795
0
      VariablePostfix = "_" + utostr(Emitter.getUniqueNumber());
1796
0
      break;
1797
0
    }
1798
0
1799
0
  initVariables();
1800
0
1801
0
  emitPrototype(NamePrefix);
1802
0
1803
0
  if (IsUnavailable) {
1804
0
    OS << " __attribute__((unavailable));";
1805
0
  } else {
1806
0
    emitOpeningBrace();
1807
0
    emitShadowedArgs();
1808
0
    if (ReverseArguments)
1809
0
      emitArgumentReversal();
1810
0
    emitBody(CallPrefix);
1811
0
    if (ReverseArguments)
1812
0
      emitReturnReversal();
1813
0
    emitReturn();
1814
0
    emitClosingBrace();
1815
0
  }
1816
0
  OS << "\n";
1817
0
1818
0
  CurrentRecord = nullptr;
1819
0
}
1820
1821
0
void Intrinsic::indexBody() {
1822
0
  CurrentRecord = R;
1823
0
1824
0
  initVariables();
1825
0
  emitBody("");
1826
0
  OS.str("");
1827
0
1828
0
  CurrentRecord = nullptr;
1829
0
}
1830
1831
//===----------------------------------------------------------------------===//
1832
// NeonEmitter implementation
1833
//===----------------------------------------------------------------------===//
1834
1835
0
Intrinsic &NeonEmitter::getIntrinsic(StringRef Name, ArrayRef<Type> Types) {
1836
0
  // First, look up the name in the intrinsic map.
1837
0
  assert_with_loc(IntrinsicMap.find(Name.str()) != IntrinsicMap.end(),
1838
0
                  ("Intrinsic '" + Name + "' not found!").str());
1839
0
  auto &V = IntrinsicMap.find(Name.str())->second;
1840
0
  std::vector<Intrinsic *> GoodVec;
1841
0
1842
0
  // Create a string to print if we end up failing.
1843
0
  std::string ErrMsg = "looking up intrinsic '" + Name.str() + "(";
1844
0
  for (unsigned I = 0; I < Types.size(); ++I) {
1845
0
    if (I != 0)
1846
0
      ErrMsg += ", ";
1847
0
    ErrMsg += Types[I].str();
1848
0
  }
1849
0
  ErrMsg += ")'\n";
1850
0
  ErrMsg += "Available overloads:\n";
1851
0
1852
0
  // Now, look through each intrinsic implementation and see if the types are
1853
0
  // compatible.
1854
0
  for (auto &I : V) {
1855
0
    ErrMsg += "  - " + I.getReturnType().str() + " " + I.getMangledName();
1856
0
    ErrMsg += "(";
1857
0
    for (unsigned A = 0; A < I.getNumParams(); ++A) {
1858
0
      if (A != 0)
1859
0
        ErrMsg += ", ";
1860
0
      ErrMsg += I.getParamType(A).str();
1861
0
    }
1862
0
    ErrMsg += ")\n";
1863
0
1864
0
    if (I.getNumParams() != Types.size())
1865
0
      continue;
1866
0
1867
0
    bool Good = true;
1868
0
    for (unsigned Arg = 0; Arg < Types.size(); ++Arg) {
1869
0
      if (I.getParamType(Arg) != Types[Arg]) {
1870
0
        Good = false;
1871
0
        break;
1872
0
      }
1873
0
    }
1874
0
    if (Good)
1875
0
      GoodVec.push_back(&I);
1876
0
  }
1877
0
1878
0
  assert_with_loc(!GoodVec.empty(),
1879
0
                  "No compatible intrinsic found - " + ErrMsg);
1880
0
  assert_with_loc(GoodVec.size() == 1, "Multiple overloads found - " + ErrMsg);
1881
0
1882
0
  return *GoodVec.front();
1883
0
}
1884
1885
void NeonEmitter::createIntrinsic(Record *R,
1886
0
                                  SmallVectorImpl<Intrinsic *> &Out) {
1887
0
  std::string Name = std::string(R->getValueAsString("Name"));
1888
0
  std::string Proto = std::string(R->getValueAsString("Prototype"));
1889
0
  std::string Types = std::string(R->getValueAsString("Types"));
1890
0
  Record *OperationRec = R->getValueAsDef("Operation");
1891
0
  bool CartesianProductOfTypes = R->getValueAsBit("CartesianProductOfTypes");
1892
0
  bool BigEndianSafe  = R->getValueAsBit("BigEndianSafe");
1893
0
  std::string Guard = std::string(R->getValueAsString("ArchGuard"));
1894
0
  bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
1895
0
1896
0
  // Set the global current record. This allows assert_with_loc to produce
1897
0
  // decent location information even when highly nested.
1898
0
  CurrentRecord = R;
1899
0
1900
0
  ListInit *Body = OperationRec->getValueAsListInit("Ops");
1901
0
1902
0
  std::vector<TypeSpec> TypeSpecs = TypeSpec::fromTypeSpecs(Types);
1903
0
1904
0
  ClassKind CK = ClassNone;
1905
0
  if (R->getSuperClasses().size() >= 2)
1906
0
    CK = ClassMap[R->getSuperClasses()[1].first];
1907
0
1908
0
  std::vector<std::pair<TypeSpec, TypeSpec>> NewTypeSpecs;
1909
0
  for (auto TS : TypeSpecs) {
1910
0
    if (CartesianProductOfTypes) {
1911
0
      Type DefaultT(TS, ".");
1912
0
      for (auto SrcTS : TypeSpecs) {
1913
0
        Type DefaultSrcT(SrcTS, ".");
1914
0
        if (TS == SrcTS ||
1915
0
            DefaultSrcT.getSizeInBits() != DefaultT.getSizeInBits())
1916
0
          continue;
1917
0
        NewTypeSpecs.push_back(std::make_pair(TS, SrcTS));
1918
0
      }
1919
0
    } else {
1920
0
      NewTypeSpecs.push_back(std::make_pair(TS, TS));
1921
0
    }
1922
0
  }
1923
0
1924
0
  llvm::sort(NewTypeSpecs);
1925
0
  NewTypeSpecs.erase(std::unique(NewTypeSpecs.begin(), NewTypeSpecs.end()),
1926
0
         NewTypeSpecs.end());
1927
0
  auto &Entry = IntrinsicMap[Name];
1928
0
1929
0
  for (auto &I : NewTypeSpecs) {
1930
0
    Entry.emplace_back(R, Name, Proto, I.first, I.second, CK, Body, *this,
1931
0
                       Guard, IsUnavailable, BigEndianSafe);
1932
0
    Out.push_back(&Entry.back());
1933
0
  }
1934
0
1935
0
  CurrentRecord = nullptr;
1936
0
}
1937
1938
/// genBuiltinsDef: Generate the BuiltinsARM.def and  BuiltinsAArch64.def
1939
/// declaration of builtins, checking for unique builtin declarations.
1940
void NeonEmitter::genBuiltinsDef(raw_ostream &OS,
1941
0
                                 SmallVectorImpl<Intrinsic *> &Defs) {
1942
0
  OS << "#ifdef GET_NEON_BUILTINS\n";
1943
0
1944
0
  // We only want to emit a builtin once, and we want to emit them in
1945
0
  // alphabetical order, so use a std::set.
1946
0
  std::set<std::string> Builtins;
1947
0
1948
0
  for (auto *Def : Defs) {
1949
0
    if (Def->hasBody())
1950
0
      continue;
1951
0
1952
0
    std::string S = "BUILTIN(__builtin_neon_" + Def->getMangledName() + ", \"";
1953
0
1954
0
    S += Def->getBuiltinTypeStr();
1955
0
    S += "\", \"n\")";
1956
0
1957
0
    Builtins.insert(S);
1958
0
  }
1959
0
1960
0
  for (auto &S : Builtins)
1961
0
    OS << S << "\n";
1962
0
  OS << "#endif\n\n";
1963
0
}
1964
1965
/// Generate the ARM and AArch64 overloaded type checking code for
1966
/// SemaChecking.cpp, checking for unique builtin declarations.
1967
void NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS,
1968
0
                                           SmallVectorImpl<Intrinsic *> &Defs) {
1969
0
  OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1970
0
1971
0
  // We record each overload check line before emitting because subsequent Inst
1972
0
  // definitions may extend the number of permitted types (i.e. augment the
1973
0
  // Mask). Use std::map to avoid sorting the table by hash number.
1974
0
  struct OverloadInfo {
1975
0
    uint64_t Mask;
1976
0
    int PtrArgNum;
1977
0
    bool HasConstPtr;
1978
0
    OverloadInfo() : Mask(0ULL), PtrArgNum(0), HasConstPtr(false) {}
1979
0
  };
1980
0
  std::map<std::string, OverloadInfo> OverloadMap;
1981
0
1982
0
  for (auto *Def : Defs) {
1983
0
    // If the def has a body (that is, it has Operation DAGs), it won't call
1984
0
    // __builtin_neon_* so we don't need to generate a definition for it.
1985
0
    if (Def->hasBody())
1986
0
      continue;
1987
0
    // Functions which have a scalar argument cannot be overloaded, no need to
1988
0
    // check them if we are emitting the type checking code.
1989
0
    if (Def->protoHasScalar())
1990
0
      continue;
1991
0
1992
0
    uint64_t Mask = 0ULL;
1993
0
    Mask |= 1ULL << Def->getPolymorphicKeyType().getNeonEnum();
1994
0
1995
0
    // Check if the function has a pointer or const pointer argument.
1996
0
    int PtrArgNum = -1;
1997
0
    bool HasConstPtr = false;
1998
0
    for (unsigned I = 0; I < Def->getNumParams(); ++I) {
1999
0
      const auto &Type = Def->getParamType(I);
2000
0
      if (Type.isPointer()) {
2001
0
        PtrArgNum = I;
2002
0
        HasConstPtr = Type.isConstPointer();
2003
0
      }
2004
0
    }
2005
0
2006
0
    // For sret builtins, adjust the pointer argument index.
2007
0
    if (PtrArgNum >= 0 && Def->getReturnType().getNumVectors() > 1)
2008
0
      PtrArgNum += 1;
2009
0
2010
0
    std::string Name = Def->getName();
2011
0
    // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
2012
0
    // and vst1_lane intrinsics.  Using a pointer to the vector element
2013
0
    // type with one of those operations causes codegen to select an aligned
2014
0
    // load/store instruction.  If you want an unaligned operation,
2015
0
    // the pointer argument needs to have less alignment than element type,
2016
0
    // so just accept any pointer type.
2017
0
    if (Name == "vld1_lane" || Name == "vld1_dup" || Name == "vst1_lane") {
2018
0
      PtrArgNum = -1;
2019
0
      HasConstPtr = false;
2020
0
    }
2021
0
2022
0
    if (Mask) {
2023
0
      std::string Name = Def->getMangledName();
2024
0
      OverloadMap.insert(std::make_pair(Name, OverloadInfo()));
2025
0
      OverloadInfo &OI = OverloadMap[Name];
2026
0
      OI.Mask |= Mask;
2027
0
      OI.PtrArgNum |= PtrArgNum;
2028
0
      OI.HasConstPtr = HasConstPtr;
2029
0
    }
2030
0
  }
2031
0
2032
0
  for (auto &I : OverloadMap) {
2033
0
    OverloadInfo &OI = I.second;
2034
0
2035
0
    OS << "case NEON::BI__builtin_neon_" << I.first << ": ";
2036
0
    OS << "mask = 0x" << Twine::utohexstr(OI.Mask) << "ULL";
2037
0
    if (OI.PtrArgNum >= 0)
2038
0
      OS << "; PtrArgNum = " << OI.PtrArgNum;
2039
0
    if (OI.HasConstPtr)
2040
0
      OS << "; HasConstPtr = true";
2041
0
    OS << "; break;\n";
2042
0
  }
2043
0
  OS << "#endif\n\n";
2044
0
}
2045
2046
void NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
2047
0
                                        SmallVectorImpl<Intrinsic *> &Defs) {
2048
0
  OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
2049
0
2050
0
  std::set<std::string> Emitted;
2051
0
2052
0
  for (auto *Def : Defs) {
2053
0
    if (Def->hasBody())
2054
0
      continue;
2055
0
    // Functions which do not have an immediate do not need to have range
2056
0
    // checking code emitted.
2057
0
    if (!Def->hasImmediate())
2058
0
      continue;
2059
0
    if (Emitted.find(Def->getMangledName()) != Emitted.end())
2060
0
      continue;
2061
0
2062
0
    std::string LowerBound, UpperBound;
2063
0
2064
0
    Record *R = Def->getRecord();
2065
0
    if (R->getValueAsBit("isVCVT_N")) {
2066
0
      // VCVT between floating- and fixed-point values takes an immediate
2067
0
      // in the range [1, 32) for f32 or [1, 64) for f64 or [1, 16) for f16.
2068
0
      LowerBound = "1";
2069
0
    if (Def->getBaseType().getElementSizeInBits() == 16 ||
2070
0
      Def->getName().find('h') != std::string::npos)
2071
0
    // VCVTh operating on FP16 intrinsics in range [1, 16)
2072
0
    UpperBound = "15";
2073
0
    else if (Def->getBaseType().getElementSizeInBits() == 32)
2074
0
        UpperBound = "31";
2075
0
    else
2076
0
        UpperBound = "63";
2077
0
    } else if (R->getValueAsBit("isScalarShift")) {
2078
0
      // Right shifts have an 'r' in the name, left shifts do not. Convert
2079
0
      // instructions have the same bounds and right shifts.
2080
0
      if (Def->getName().find('r') != std::string::npos ||
2081
0
          Def->getName().find("cvt") != std::string::npos)
2082
0
        LowerBound = "1";
2083
0
2084
0
      UpperBound = utostr(Def->getReturnType().getElementSizeInBits() - 1);
2085
0
    } else if (R->getValueAsBit("isShift")) {
2086
0
      // Builtins which are overloaded by type will need to have their upper
2087
0
      // bound computed at Sema time based on the type constant.
2088
0
2089
0
      // Right shifts have an 'r' in the name, left shifts do not.
2090
0
      if (Def->getName().find('r') != std::string::npos)
2091
0
        LowerBound = "1";
2092
0
      UpperBound = "RFT(TV, true)";
2093
0
    } else if (Def->getClassKind(true) == ClassB) {
2094
0
      // ClassB intrinsics have a type (and hence lane number) that is only
2095
0
      // known at runtime.
2096
0
      if (R->getValueAsBit("isLaneQ"))
2097
0
        UpperBound = "RFT(TV, false, true)";
2098
0
      else
2099
0
        UpperBound = "RFT(TV, false, false)";
2100
0
    } else {
2101
0
      // The immediate generally refers to a lane in the preceding argument.
2102
0
      assert(Def->getImmediateIdx() > 0);
2103
0
      Type T = Def->getParamType(Def->getImmediateIdx() - 1);
2104
0
      UpperBound = utostr(T.getNumElements() - 1);
2105
0
    }
2106
0
2107
0
    // Calculate the index of the immediate that should be range checked.
2108
0
    unsigned Idx = Def->getNumParams();
2109
0
    if (Def->hasImmediate())
2110
0
      Idx = Def->getGeneratedParamIdx(Def->getImmediateIdx());
2111
0
2112
0
    OS << "case NEON::BI__builtin_neon_" << Def->getMangledName() << ": "
2113
0
       << "i = " << Idx << ";";
2114
0
    if (!LowerBound.empty())
2115
0
      OS << " l = " << LowerBound << ";";
2116
0
    if (!UpperBound.empty())
2117
0
      OS << " u = " << UpperBound << ";";
2118
0
    OS << " break;\n";
2119
0
2120
0
    Emitted.insert(Def->getMangledName());
2121
0
  }
2122
0
2123
0
  OS << "#endif\n\n";
2124
0
}
2125
2126
/// runHeader - Emit a file with sections defining:
2127
/// 1. the NEON section of BuiltinsARM.def and BuiltinsAArch64.def.
2128
/// 2. the SemaChecking code for the type overload checking.
2129
/// 3. the SemaChecking code for validation of intrinsic immediate arguments.
2130
0
void NeonEmitter::runHeader(raw_ostream &OS) {
2131
0
  std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2132
0
2133
0
  SmallVector<Intrinsic *, 128> Defs;
2134
0
  for (auto *R : RV)
2135
0
    createIntrinsic(R, Defs);
2136
0
2137
0
  // Generate shared BuiltinsXXX.def
2138
0
  genBuiltinsDef(OS, Defs);
2139
0
2140
0
  // Generate ARM overloaded type checking code for SemaChecking.cpp
2141
0
  genOverloadTypeCheckCode(OS, Defs);
2142
0
2143
0
  // Generate ARM range checking code for shift/lane immediates.
2144
0
  genIntrinsicRangeCheckCode(OS, Defs);
2145
0
}
2146
2147
/// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
2148
/// is comprised of type definitions and function declarations.
2149
0
void NeonEmitter::run(raw_ostream &OS) {
2150
0
  OS << "/*===---- arm_neon.h - ARM Neon intrinsics "
2151
0
        "------------------------------"
2152
0
        "---===\n"
2153
0
        " *\n"
2154
0
        " * Permission is hereby granted, free of charge, to any person "
2155
0
        "obtaining "
2156
0
        "a copy\n"
2157
0
        " * of this software and associated documentation files (the "
2158
0
        "\"Software\"),"
2159
0
        " to deal\n"
2160
0
        " * in the Software without restriction, including without limitation "
2161
0
        "the "
2162
0
        "rights\n"
2163
0
        " * to use, copy, modify, merge, publish, distribute, sublicense, "
2164
0
        "and/or sell\n"
2165
0
        " * copies of the Software, and to permit persons to whom the Software "
2166
0
        "is\n"
2167
0
        " * furnished to do so, subject to the following conditions:\n"
2168
0
        " *\n"
2169
0
        " * The above copyright notice and this permission notice shall be "
2170
0
        "included in\n"
2171
0
        " * all copies or substantial portions of the Software.\n"
2172
0
        " *\n"
2173
0
        " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2174
0
        "EXPRESS OR\n"
2175
0
        " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2176
0
        "MERCHANTABILITY,\n"
2177
0
        " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2178
0
        "SHALL THE\n"
2179
0
        " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2180
0
        "OTHER\n"
2181
0
        " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2182
0
        "ARISING FROM,\n"
2183
0
        " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2184
0
        "DEALINGS IN\n"
2185
0
        " * THE SOFTWARE.\n"
2186
0
        " *\n"
2187
0
        " *===-----------------------------------------------------------------"
2188
0
        "---"
2189
0
        "---===\n"
2190
0
        " */\n\n";
2191
0
2192
0
  OS << "#ifndef __ARM_NEON_H\n";
2193
0
  OS << "#define __ARM_NEON_H\n\n";
2194
0
2195
0
  OS << "#if !defined(__ARM_NEON)\n";
2196
0
  OS << "#error \"NEON support not enabled\"\n";
2197
0
  OS << "#endif\n\n";
2198
0
2199
0
  OS << "#include <stdint.h>\n\n";
2200
0
2201
0
  // Emit NEON-specific scalar typedefs.
2202
0
  OS << "typedef float float32_t;\n";
2203
0
  OS << "typedef __fp16 float16_t;\n";
2204
0
2205
0
  OS << "#ifdef __aarch64__\n";
2206
0
  OS << "typedef double float64_t;\n";
2207
0
  OS << "#endif\n\n";
2208
0
2209
0
  // For now, signedness of polynomial types depends on target
2210
0
  OS << "#ifdef __aarch64__\n";
2211
0
  OS << "typedef uint8_t poly8_t;\n";
2212
0
  OS << "typedef uint16_t poly16_t;\n";
2213
0
  OS << "typedef uint64_t poly64_t;\n";
2214
0
  OS << "typedef __uint128_t poly128_t;\n";
2215
0
  OS << "#else\n";
2216
0
  OS << "typedef int8_t poly8_t;\n";
2217
0
  OS << "typedef int16_t poly16_t;\n";
2218
0
  OS << "#endif\n";
2219
0
2220
0
  // Emit Neon vector typedefs.
2221
0
  std::string TypedefTypes(
2222
0
      "cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfdQdPcQPcPsQPsPlQPl");
2223
0
  std::vector<TypeSpec> TDTypeVec = TypeSpec::fromTypeSpecs(TypedefTypes);
2224
0
2225
0
  // Emit vector typedefs.
2226
0
  bool InIfdef = false;
2227
0
  for (auto &TS : TDTypeVec) {
2228
0
    bool IsA64 = false;
2229
0
    Type T(TS, ".");
2230
0
    if (T.isDouble() || (T.isPoly() && T.getElementSizeInBits() == 64))
2231
0
      IsA64 = true;
2232
0
2233
0
    if (InIfdef && !IsA64) {
2234
0
      OS << "#endif\n";
2235
0
      InIfdef = false;
2236
0
    }
2237
0
    if (!InIfdef && IsA64) {
2238
0
      OS << "#ifdef __aarch64__\n";
2239
0
      InIfdef = true;
2240
0
    }
2241
0
2242
0
    if (T.isPoly())
2243
0
      OS << "typedef __attribute__((neon_polyvector_type(";
2244
0
    else
2245
0
      OS << "typedef __attribute__((neon_vector_type(";
2246
0
2247
0
    Type T2 = T;
2248
0
    T2.makeScalar();
2249
0
    OS << T.getNumElements() << "))) ";
2250
0
    OS << T2.str();
2251
0
    OS << " " << T.str() << ";\n";
2252
0
  }
2253
0
  if (InIfdef)
2254
0
    OS << "#endif\n";
2255
0
  OS << "\n";
2256
0
2257
0
  // Emit struct typedefs.
2258
0
  InIfdef = false;
2259
0
  for (unsigned NumMembers = 2; NumMembers <= 4; ++NumMembers) {
2260
0
    for (auto &TS : TDTypeVec) {
2261
0
      bool IsA64 = false;
2262
0
      Type T(TS, ".");
2263
0
      if (T.isDouble() || (T.isPoly() && T.getElementSizeInBits() == 64))
2264
0
        IsA64 = true;
2265
0
2266
0
      if (InIfdef && !IsA64) {
2267
0
        OS << "#endif\n";
2268
0
        InIfdef = false;
2269
0
      }
2270
0
      if (!InIfdef && IsA64) {
2271
0
        OS << "#ifdef __aarch64__\n";
2272
0
        InIfdef = true;
2273
0
      }
2274
0
2275
0
      const char Mods[] = { static_cast<char>('2' + (NumMembers - 2)), 0};
2276
0
      Type VT(TS, Mods);
2277
0
      OS << "typedef struct " << VT.str() << " {\n";
2278
0
      OS << "  " << T.str() << " val";
2279
0
      OS << "[" << NumMembers << "]";
2280
0
      OS << ";\n} ";
2281
0
      OS << VT.str() << ";\n";
2282
0
      OS << "\n";
2283
0
    }
2284
0
  }
2285
0
  if (InIfdef)
2286
0
    OS << "#endif\n";
2287
0
  OS << "\n";
2288
0
2289
0
  OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2290
0
        "__nodebug__))\n\n";
2291
0
2292
0
  SmallVector<Intrinsic *, 128> Defs;
2293
0
  std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2294
0
  for (auto *R : RV)
2295
0
    createIntrinsic(R, Defs);
2296
0
2297
0
  for (auto *I : Defs)
2298
0
    I->indexBody();
2299
0
2300
0
  llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2301
0
2302
0
  // Only emit a def when its requirements have been met.
2303
0
  // FIXME: This loop could be made faster, but it's fast enough for now.
2304
0
  bool MadeProgress = true;
2305
0
  std::string InGuard;
2306
0
  while (!Defs.empty() && MadeProgress) {
2307
0
    MadeProgress = false;
2308
0
2309
0
    for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2310
0
         I != Defs.end(); /*No step*/) {
2311
0
      bool DependenciesSatisfied = true;
2312
0
      for (auto *II : (*I)->getDependencies()) {
2313
0
        if (llvm::is_contained(Defs, II))
2314
0
          DependenciesSatisfied = false;
2315
0
      }
2316
0
      if (!DependenciesSatisfied) {
2317
0
        // Try the next one.
2318
0
        ++I;
2319
0
        continue;
2320
0
      }
2321
0
2322
0
      // Emit #endif/#if pair if needed.
2323
0
      if ((*I)->getGuard() != InGuard) {
2324
0
        if (!InGuard.empty())
2325
0
          OS << "#endif\n";
2326
0
        InGuard = (*I)->getGuard();
2327
0
        if (!InGuard.empty())
2328
0
          OS << "#if " << InGuard << "\n";
2329
0
      }
2330
0
2331
0
      // Actually generate the intrinsic code.
2332
0
      OS << (*I)->generate();
2333
0
2334
0
      MadeProgress = true;
2335
0
      I = Defs.erase(I);
2336
0
    }
2337
0
  }
2338
0
  assert(Defs.empty() && "Some requirements were not satisfied!");
2339
0
  if (!InGuard.empty())
2340
0
    OS << "#endif\n";
2341
0
2342
0
  OS << "\n";
2343
0
  OS << "#undef __ai\n\n";
2344
0
  OS << "#endif /* __ARM_NEON_H */\n";
2345
0
}
2346
2347
/// run - Read the records in arm_fp16.td and output arm_fp16.h.  arm_fp16.h
2348
/// is comprised of type definitions and function declarations.
2349
0
void NeonEmitter::runFP16(raw_ostream &OS) {
2350
0
  OS << "/*===---- arm_fp16.h - ARM FP16 intrinsics "
2351
0
        "------------------------------"
2352
0
        "---===\n"
2353
0
        " *\n"
2354
0
        " * Permission is hereby granted, free of charge, to any person "
2355
0
        "obtaining a copy\n"
2356
0
        " * of this software and associated documentation files (the "
2357
0
        "\"Software\"), to deal\n"
2358
0
        " * in the Software without restriction, including without limitation "
2359
0
        "the rights\n"
2360
0
        " * to use, copy, modify, merge, publish, distribute, sublicense, "
2361
0
        "and/or sell\n"
2362
0
        " * copies of the Software, and to permit persons to whom the Software "
2363
0
        "is\n"
2364
0
        " * furnished to do so, subject to the following conditions:\n"
2365
0
        " *\n"
2366
0
        " * The above copyright notice and this permission notice shall be "
2367
0
        "included in\n"
2368
0
        " * all copies or substantial portions of the Software.\n"
2369
0
        " *\n"
2370
0
        " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2371
0
        "EXPRESS OR\n"
2372
0
        " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2373
0
        "MERCHANTABILITY,\n"
2374
0
        " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2375
0
        "SHALL THE\n"
2376
0
        " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2377
0
        "OTHER\n"
2378
0
        " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2379
0
        "ARISING FROM,\n"
2380
0
        " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2381
0
        "DEALINGS IN\n"
2382
0
        " * THE SOFTWARE.\n"
2383
0
        " *\n"
2384
0
        " *===-----------------------------------------------------------------"
2385
0
        "---"
2386
0
        "---===\n"
2387
0
        " */\n\n";
2388
0
2389
0
  OS << "#ifndef __ARM_FP16_H\n";
2390
0
  OS << "#define __ARM_FP16_H\n\n";
2391
0
2392
0
  OS << "#include <stdint.h>\n\n";
2393
0
2394
0
  OS << "typedef __fp16 float16_t;\n";
2395
0
2396
0
  OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2397
0
        "__nodebug__))\n\n";
2398
0
2399
0
  SmallVector<Intrinsic *, 128> Defs;
2400
0
  std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2401
0
  for (auto *R : RV)
2402
0
    createIntrinsic(R, Defs);
2403
0
2404
0
  for (auto *I : Defs)
2405
0
    I->indexBody();
2406
0
2407
0
  llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2408
0
2409
0
  // Only emit a def when its requirements have been met.
2410
0
  // FIXME: This loop could be made faster, but it's fast enough for now.
2411
0
  bool MadeProgress = true;
2412
0
  std::string InGuard;
2413
0
  while (!Defs.empty() && MadeProgress) {
2414
0
    MadeProgress = false;
2415
0
2416
0
    for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2417
0
         I != Defs.end(); /*No step*/) {
2418
0
      bool DependenciesSatisfied = true;
2419
0
      for (auto *II : (*I)->getDependencies()) {
2420
0
        if (llvm::is_contained(Defs, II))
2421
0
          DependenciesSatisfied = false;
2422
0
      }
2423
0
      if (!DependenciesSatisfied) {
2424
0
        // Try the next one.
2425
0
        ++I;
2426
0
        continue;
2427
0
      }
2428
0
2429
0
      // Emit #endif/#if pair if needed.
2430
0
      if ((*I)->getGuard() != InGuard) {
2431
0
        if (!InGuard.empty())
2432
0
          OS << "#endif\n";
2433
0
        InGuard = (*I)->getGuard();
2434
0
        if (!InGuard.empty())
2435
0
          OS << "#if " << InGuard << "\n";
2436
0
      }
2437
0
2438
0
      // Actually generate the intrinsic code.
2439
0
      OS << (*I)->generate();
2440
0
2441
0
      MadeProgress = true;
2442
0
      I = Defs.erase(I);
2443
0
    }
2444
0
  }
2445
0
  assert(Defs.empty() && "Some requirements were not satisfied!");
2446
0
  if (!InGuard.empty())
2447
0
    OS << "#endif\n";
2448
0
2449
0
  OS << "\n";
2450
0
  OS << "#undef __ai\n\n";
2451
0
  OS << "#endif /* __ARM_FP16_H */\n";
2452
0
}
2453
2454
0
void clang::EmitNeon(RecordKeeper &Records, raw_ostream &OS) {
2455
0
  NeonEmitter(Records).run(OS);
2456
0
}
2457
2458
0
void clang::EmitFP16(RecordKeeper &Records, raw_ostream &OS) {
2459
0
  NeonEmitter(Records).runFP16(OS);
2460
0
}
2461
2462
0
void clang::EmitNeonSema(RecordKeeper &Records, raw_ostream &OS) {
2463
0
  NeonEmitter(Records).runHeader(OS);
2464
0
}
2465
2466
0
void clang::EmitNeonTest(RecordKeeper &Records, raw_ostream &OS) {
2467
0
  llvm_unreachable("Neon test generation no longer implemented!");
2468
0
}