xref: /freebsd/contrib/llvm-project/llvm/utils/TableGen/IntrinsicEmitter.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
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 emits information about intrinsic functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenIntrinsics.h"
14 #include "CodeGenTarget.h"
15 #include "SequenceToOffsetTable.h"
16 #include "TableGenBackends.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/StringToOffsetTable.h"
22 #include "llvm/TableGen/TableGenBackend.h"
23 #include <algorithm>
24 using namespace llvm;
25 
26 cl::OptionCategory GenIntrinsicCat("Options for -gen-intrinsic-enums");
27 cl::opt<std::string>
28     IntrinsicPrefix("intrinsic-prefix",
29                     cl::desc("Generate intrinsics with this target prefix"),
30                     cl::value_desc("target prefix"), cl::cat(GenIntrinsicCat));
31 
32 namespace {
33 class IntrinsicEmitter {
34   RecordKeeper &Records;
35 
36 public:
37   IntrinsicEmitter(RecordKeeper &R) : Records(R) {}
38 
39   void run(raw_ostream &OS, bool Enums);
40 
41   void EmitEnumInfo(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
42   void EmitTargetInfo(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
43   void EmitIntrinsicToNameTable(const CodeGenIntrinsicTable &Ints,
44                                 raw_ostream &OS);
45   void EmitIntrinsicToOverloadTable(const CodeGenIntrinsicTable &Ints,
46                                     raw_ostream &OS);
47   void EmitGenerator(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
48   void EmitAttributes(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
49   void EmitIntrinsicToBuiltinMap(const CodeGenIntrinsicTable &Ints, bool IsGCC,
50                                  raw_ostream &OS);
51 };
52 } // End anonymous namespace
53 
54 //===----------------------------------------------------------------------===//
55 // IntrinsicEmitter Implementation
56 //===----------------------------------------------------------------------===//
57 
58 void IntrinsicEmitter::run(raw_ostream &OS, bool Enums) {
59   emitSourceFileHeader("Intrinsic Function Source Fragment", OS);
60 
61   CodeGenIntrinsicTable Ints(Records);
62 
63   if (Enums) {
64     // Emit the enum information.
65     EmitEnumInfo(Ints, OS);
66   } else {
67     // Emit the target metadata.
68     EmitTargetInfo(Ints, OS);
69 
70     // Emit the intrinsic ID -> name table.
71     EmitIntrinsicToNameTable(Ints, OS);
72 
73     // Emit the intrinsic ID -> overload table.
74     EmitIntrinsicToOverloadTable(Ints, OS);
75 
76     // Emit the intrinsic declaration generator.
77     EmitGenerator(Ints, OS);
78 
79     // Emit the intrinsic parameter attributes.
80     EmitAttributes(Ints, OS);
81 
82     // Emit code to translate GCC builtins into LLVM intrinsics.
83     EmitIntrinsicToBuiltinMap(Ints, true, OS);
84 
85     // Emit code to translate MS builtins into LLVM intrinsics.
86     EmitIntrinsicToBuiltinMap(Ints, false, OS);
87   }
88 }
89 
90 void IntrinsicEmitter::EmitEnumInfo(const CodeGenIntrinsicTable &Ints,
91                                     raw_ostream &OS) {
92   // Find the TargetSet for which to generate enums. There will be an initial
93   // set with an empty target prefix which will include target independent
94   // intrinsics like dbg.value.
95   const CodeGenIntrinsicTable::TargetSet *Set = nullptr;
96   for (const auto &Target : Ints.Targets) {
97     if (Target.Name == IntrinsicPrefix) {
98       Set = &Target;
99       break;
100     }
101   }
102   if (!Set) {
103     std::vector<std::string> KnownTargets;
104     for (const auto &Target : Ints.Targets)
105       if (!Target.Name.empty())
106         KnownTargets.push_back(Target.Name);
107     PrintFatalError("tried to generate intrinsics for unknown target " +
108                     IntrinsicPrefix +
109                     "\nKnown targets are: " + join(KnownTargets, ", ") + "\n");
110   }
111 
112   // Generate a complete header for target specific intrinsics.
113   if (!IntrinsicPrefix.empty()) {
114     std::string UpperPrefix = StringRef(IntrinsicPrefix).upper();
115     OS << "#ifndef LLVM_IR_INTRINSIC_" << UpperPrefix << "_ENUMS_H\n";
116     OS << "#define LLVM_IR_INTRINSIC_" << UpperPrefix << "_ENUMS_H\n\n";
117     OS << "namespace llvm {\n";
118     OS << "namespace Intrinsic {\n";
119     OS << "enum " << UpperPrefix << "Intrinsics : unsigned {\n";
120   }
121 
122   OS << "// Enum values for intrinsics\n";
123   for (unsigned i = Set->Offset, e = Set->Offset + Set->Count; i != e; ++i) {
124     OS << "    " << Ints[i].EnumName;
125 
126     // Assign a value to the first intrinsic in this target set so that all
127     // intrinsic ids are distinct.
128     if (i == Set->Offset)
129       OS << " = " << (Set->Offset + 1);
130 
131     OS << ", ";
132     if (Ints[i].EnumName.size() < 40)
133       OS.indent(40 - Ints[i].EnumName.size());
134     OS << " // " << Ints[i].Name << "\n";
135   }
136 
137   // Emit num_intrinsics into the target neutral enum.
138   if (IntrinsicPrefix.empty()) {
139     OS << "    num_intrinsics = " << (Ints.size() + 1) << "\n";
140   } else {
141     OS << "}; // enum\n";
142     OS << "} // namespace Intrinsic\n";
143     OS << "} // namespace llvm\n\n";
144     OS << "#endif\n";
145   }
146 }
147 
148 void IntrinsicEmitter::EmitTargetInfo(const CodeGenIntrinsicTable &Ints,
149                                     raw_ostream &OS) {
150   OS << "// Target mapping\n";
151   OS << "#ifdef GET_INTRINSIC_TARGET_DATA\n";
152   OS << "struct IntrinsicTargetInfo {\n"
153      << "  llvm::StringLiteral Name;\n"
154      << "  size_t Offset;\n"
155      << "  size_t Count;\n"
156      << "};\n";
157   OS << "static constexpr IntrinsicTargetInfo TargetInfos[] = {\n";
158   for (auto Target : Ints.Targets)
159     OS << "  {llvm::StringLiteral(\"" << Target.Name << "\"), " << Target.Offset
160        << ", " << Target.Count << "},\n";
161   OS << "};\n";
162   OS << "#endif\n\n";
163 }
164 
165 void IntrinsicEmitter::EmitIntrinsicToNameTable(
166     const CodeGenIntrinsicTable &Ints, raw_ostream &OS) {
167   OS << "// Intrinsic ID to name table\n";
168   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
169   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
170   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
171     OS << "  \"" << Ints[i].Name << "\",\n";
172   OS << "#endif\n\n";
173 }
174 
175 void IntrinsicEmitter::EmitIntrinsicToOverloadTable(
176     const CodeGenIntrinsicTable &Ints, raw_ostream &OS) {
177   OS << "// Intrinsic ID to overload bitset\n";
178   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
179   OS << "static const uint8_t OTable[] = {\n";
180   OS << "  0";
181   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
182     // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
183     if ((i+1)%8 == 0)
184       OS << ",\n  0";
185     if (Ints[i].isOverloaded)
186       OS << " | (1<<" << (i+1)%8 << ')';
187   }
188   OS << "\n};\n\n";
189   // OTable contains a true bit at the position if the intrinsic is overloaded.
190   OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
191   OS << "#endif\n\n";
192 }
193 
194 
195 // NOTE: This must be kept in synch with the copy in lib/IR/Function.cpp!
196 enum IIT_Info {
197   // Common values should be encoded with 0-15.
198   IIT_Done = 0,
199   IIT_I1   = 1,
200   IIT_I8   = 2,
201   IIT_I16  = 3,
202   IIT_I32  = 4,
203   IIT_I64  = 5,
204   IIT_F16  = 6,
205   IIT_F32  = 7,
206   IIT_F64  = 8,
207   IIT_V2   = 9,
208   IIT_V4   = 10,
209   IIT_V8   = 11,
210   IIT_V16  = 12,
211   IIT_V32  = 13,
212   IIT_PTR  = 14,
213   IIT_ARG  = 15,
214 
215   // Values from 16+ are only encodable with the inefficient encoding.
216   IIT_V64  = 16,
217   IIT_MMX  = 17,
218   IIT_TOKEN = 18,
219   IIT_METADATA = 19,
220   IIT_EMPTYSTRUCT = 20,
221   IIT_STRUCT2 = 21,
222   IIT_STRUCT3 = 22,
223   IIT_STRUCT4 = 23,
224   IIT_STRUCT5 = 24,
225   IIT_EXTEND_ARG = 25,
226   IIT_TRUNC_ARG = 26,
227   IIT_ANYPTR = 27,
228   IIT_V1   = 28,
229   IIT_VARARG = 29,
230   IIT_HALF_VEC_ARG = 30,
231   IIT_SAME_VEC_WIDTH_ARG = 31,
232   IIT_PTR_TO_ARG = 32,
233   IIT_PTR_TO_ELT = 33,
234   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
235   IIT_I128 = 35,
236   IIT_V512 = 36,
237   IIT_V1024 = 37,
238   IIT_STRUCT6 = 38,
239   IIT_STRUCT7 = 39,
240   IIT_STRUCT8 = 40,
241   IIT_F128 = 41,
242   IIT_VEC_ELEMENT = 42,
243   IIT_SCALABLE_VEC = 43,
244   IIT_SUBDIVIDE2_ARG = 44,
245   IIT_SUBDIVIDE4_ARG = 45,
246   IIT_VEC_OF_BITCASTS_TO_INT = 46,
247   IIT_V128 = 47,
248   IIT_BF16 = 48,
249   IIT_STRUCT9 = 49,
250   IIT_V256 = 50,
251   IIT_AMX  = 51,
252   IIT_PPCF128 = 52,
253   IIT_V3 = 53,
254   IIT_EXTERNREF = 54,
255   IIT_FUNCREF = 55
256 };
257 
258 static void EncodeFixedValueType(MVT::SimpleValueType VT,
259                                  std::vector<unsigned char> &Sig) {
260   if (MVT(VT).isInteger()) {
261     unsigned BitWidth = MVT(VT).getFixedSizeInBits();
262     switch (BitWidth) {
263     default: PrintFatalError("unhandled integer type width in intrinsic!");
264     case 1: return Sig.push_back(IIT_I1);
265     case 8: return Sig.push_back(IIT_I8);
266     case 16: return Sig.push_back(IIT_I16);
267     case 32: return Sig.push_back(IIT_I32);
268     case 64: return Sig.push_back(IIT_I64);
269     case 128: return Sig.push_back(IIT_I128);
270     }
271   }
272 
273   switch (VT) {
274   default: PrintFatalError("unhandled MVT in intrinsic!");
275   case MVT::f16: return Sig.push_back(IIT_F16);
276   case MVT::bf16: return Sig.push_back(IIT_BF16);
277   case MVT::f32: return Sig.push_back(IIT_F32);
278   case MVT::f64: return Sig.push_back(IIT_F64);
279   case MVT::f128: return Sig.push_back(IIT_F128);
280   case MVT::ppcf128: return Sig.push_back(IIT_PPCF128);
281   case MVT::token: return Sig.push_back(IIT_TOKEN);
282   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
283   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
284   case MVT::x86amx: return Sig.push_back(IIT_AMX);
285   // MVT::OtherVT is used to mean the empty struct type here.
286   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
287   // MVT::isVoid is used to represent varargs here.
288   case MVT::isVoid: return Sig.push_back(IIT_VARARG);
289   case MVT::externref:
290     return Sig.push_back(IIT_EXTERNREF);
291   case MVT::funcref:
292     return Sig.push_back(IIT_FUNCREF);
293   }
294 }
295 
296 #if defined(_MSC_VER) && !defined(__clang__)
297 #pragma optimize("",off) // MSVC 2015 optimizer can't deal with this function.
298 #endif
299 
300 static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
301                             unsigned &NextArgCode,
302                             std::vector<unsigned char> &Sig,
303                             ArrayRef<unsigned char> Mapping) {
304 
305   if (R->isSubClassOf("LLVMMatchType")) {
306     unsigned Number = Mapping[R->getValueAsInt("Number")];
307     assert(Number < ArgCodes.size() && "Invalid matching number!");
308     if (R->isSubClassOf("LLVMExtendedType"))
309       Sig.push_back(IIT_EXTEND_ARG);
310     else if (R->isSubClassOf("LLVMTruncatedType"))
311       Sig.push_back(IIT_TRUNC_ARG);
312     else if (R->isSubClassOf("LLVMHalfElementsVectorType"))
313       Sig.push_back(IIT_HALF_VEC_ARG);
314     else if (R->isSubClassOf("LLVMScalarOrSameVectorWidth")) {
315       Sig.push_back(IIT_SAME_VEC_WIDTH_ARG);
316       Sig.push_back((Number << 3) | ArgCodes[Number]);
317       MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy"));
318       EncodeFixedValueType(VT, Sig);
319       return;
320     }
321     else if (R->isSubClassOf("LLVMPointerTo"))
322       Sig.push_back(IIT_PTR_TO_ARG);
323     else if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
324       Sig.push_back(IIT_VEC_OF_ANYPTRS_TO_ELT);
325       // Encode overloaded ArgNo
326       Sig.push_back(NextArgCode++);
327       // Encode LLVMMatchType<Number> ArgNo
328       Sig.push_back(Number);
329       return;
330     } else if (R->isSubClassOf("LLVMPointerToElt"))
331       Sig.push_back(IIT_PTR_TO_ELT);
332     else if (R->isSubClassOf("LLVMVectorElementType"))
333       Sig.push_back(IIT_VEC_ELEMENT);
334     else if (R->isSubClassOf("LLVMSubdivide2VectorType"))
335       Sig.push_back(IIT_SUBDIVIDE2_ARG);
336     else if (R->isSubClassOf("LLVMSubdivide4VectorType"))
337       Sig.push_back(IIT_SUBDIVIDE4_ARG);
338     else if (R->isSubClassOf("LLVMVectorOfBitcastsToInt"))
339       Sig.push_back(IIT_VEC_OF_BITCASTS_TO_INT);
340     else
341       Sig.push_back(IIT_ARG);
342     return Sig.push_back((Number << 3) | 7 /*IITDescriptor::AK_MatchType*/);
343   }
344 
345   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
346 
347   unsigned Tmp = 0;
348   switch (VT) {
349   default: break;
350   case MVT::iPTRAny: ++Tmp; LLVM_FALLTHROUGH;
351   case MVT::vAny: ++Tmp;    LLVM_FALLTHROUGH;
352   case MVT::fAny: ++Tmp;    LLVM_FALLTHROUGH;
353   case MVT::iAny: ++Tmp;    LLVM_FALLTHROUGH;
354   case MVT::Any: {
355     // If this is an "any" valuetype, then the type is the type of the next
356     // type in the list specified to getIntrinsic().
357     Sig.push_back(IIT_ARG);
358 
359     // Figure out what arg # this is consuming, and remember what kind it was.
360     assert(NextArgCode < ArgCodes.size() && ArgCodes[NextArgCode] == Tmp &&
361            "Invalid or no ArgCode associated with overloaded VT!");
362     unsigned ArgNo = NextArgCode++;
363 
364     // Encode what sort of argument it must be in the low 3 bits of the ArgNo.
365     return Sig.push_back((ArgNo << 3) | Tmp);
366   }
367 
368   case MVT::iPTR: {
369     unsigned AddrSpace = 0;
370     if (R->isSubClassOf("LLVMQualPointerType")) {
371       AddrSpace = R->getValueAsInt("AddrSpace");
372       assert(AddrSpace < 256 && "Address space exceeds 255");
373     }
374     if (AddrSpace) {
375       Sig.push_back(IIT_ANYPTR);
376       Sig.push_back(AddrSpace);
377     } else {
378       Sig.push_back(IIT_PTR);
379     }
380     return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, NextArgCode, Sig,
381                            Mapping);
382   }
383   }
384 
385   if (MVT(VT).isVector()) {
386     MVT VVT = VT;
387     if (VVT.isScalableVector())
388       Sig.push_back(IIT_SCALABLE_VEC);
389     switch (VVT.getVectorMinNumElements()) {
390     default: PrintFatalError("unhandled vector type width in intrinsic!");
391     case 1: Sig.push_back(IIT_V1); break;
392     case 2: Sig.push_back(IIT_V2); break;
393     case 3: Sig.push_back(IIT_V3); break;
394     case 4: Sig.push_back(IIT_V4); break;
395     case 8: Sig.push_back(IIT_V8); break;
396     case 16: Sig.push_back(IIT_V16); break;
397     case 32: Sig.push_back(IIT_V32); break;
398     case 64: Sig.push_back(IIT_V64); break;
399     case 128: Sig.push_back(IIT_V128); break;
400     case 256: Sig.push_back(IIT_V256); break;
401     case 512: Sig.push_back(IIT_V512); break;
402     case 1024: Sig.push_back(IIT_V1024); break;
403     }
404 
405     return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
406   }
407 
408   EncodeFixedValueType(VT, Sig);
409 }
410 
411 static void UpdateArgCodes(Record *R, std::vector<unsigned char> &ArgCodes,
412                            unsigned int &NumInserted,
413                            SmallVectorImpl<unsigned char> &Mapping) {
414   if (R->isSubClassOf("LLVMMatchType")) {
415     if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
416       ArgCodes.push_back(3 /*vAny*/);
417       ++NumInserted;
418     }
419     return;
420   }
421 
422   unsigned Tmp = 0;
423   switch (getValueType(R->getValueAsDef("VT"))) {
424   default: break;
425   case MVT::iPTR:
426     UpdateArgCodes(R->getValueAsDef("ElTy"), ArgCodes, NumInserted, Mapping);
427     break;
428   case MVT::iPTRAny:
429     ++Tmp;
430     LLVM_FALLTHROUGH;
431   case MVT::vAny:
432     ++Tmp;
433     LLVM_FALLTHROUGH;
434   case MVT::fAny:
435     ++Tmp;
436     LLVM_FALLTHROUGH;
437   case MVT::iAny:
438     ++Tmp;
439     LLVM_FALLTHROUGH;
440   case MVT::Any:
441     unsigned OriginalIdx = ArgCodes.size() - NumInserted;
442     assert(OriginalIdx >= Mapping.size());
443     Mapping.resize(OriginalIdx+1);
444     Mapping[OriginalIdx] = ArgCodes.size();
445     ArgCodes.push_back(Tmp);
446     break;
447   }
448 }
449 
450 #if defined(_MSC_VER) && !defined(__clang__)
451 #pragma optimize("",on)
452 #endif
453 
454 /// ComputeFixedEncoding - If we can encode the type signature for this
455 /// intrinsic into 32 bits, return it.  If not, return ~0U.
456 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
457                                  std::vector<unsigned char> &TypeSig) {
458   std::vector<unsigned char> ArgCodes;
459 
460   // Add codes for any overloaded result VTs.
461   unsigned int NumInserted = 0;
462   SmallVector<unsigned char, 8> ArgMapping;
463   for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
464     UpdateArgCodes(Int.IS.RetTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
465 
466   // Add codes for any overloaded operand VTs.
467   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
468     UpdateArgCodes(Int.IS.ParamTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
469 
470   unsigned NextArgCode = 0;
471   if (Int.IS.RetVTs.empty())
472     TypeSig.push_back(IIT_Done);
473   else if (Int.IS.RetVTs.size() == 1 &&
474            Int.IS.RetVTs[0] == MVT::isVoid)
475     TypeSig.push_back(IIT_Done);
476   else {
477     switch (Int.IS.RetVTs.size()) {
478       case 1: break;
479       case 2: TypeSig.push_back(IIT_STRUCT2); break;
480       case 3: TypeSig.push_back(IIT_STRUCT3); break;
481       case 4: TypeSig.push_back(IIT_STRUCT4); break;
482       case 5: TypeSig.push_back(IIT_STRUCT5); break;
483       case 6: TypeSig.push_back(IIT_STRUCT6); break;
484       case 7: TypeSig.push_back(IIT_STRUCT7); break;
485       case 8: TypeSig.push_back(IIT_STRUCT8); break;
486       case 9: TypeSig.push_back(IIT_STRUCT9); break;
487       default: llvm_unreachable("Unhandled case in struct");
488     }
489 
490     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
491       EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
492                       ArgMapping);
493   }
494 
495   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
496     EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
497                     ArgMapping);
498 }
499 
500 static void printIITEntry(raw_ostream &OS, unsigned char X) {
501   OS << (unsigned)X;
502 }
503 
504 void IntrinsicEmitter::EmitGenerator(const CodeGenIntrinsicTable &Ints,
505                                      raw_ostream &OS) {
506   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
507   // capture it in this vector, otherwise store a ~0U.
508   std::vector<unsigned> FixedEncodings;
509 
510   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
511 
512   std::vector<unsigned char> TypeSig;
513 
514   // Compute the unique argument type info.
515   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
516     // Get the signature for the intrinsic.
517     TypeSig.clear();
518     ComputeFixedEncoding(Ints[i], TypeSig);
519 
520     // Check to see if we can encode it into a 32-bit word.  We can only encode
521     // 8 nibbles into a 32-bit word.
522     if (TypeSig.size() <= 8) {
523       bool Failed = false;
524       unsigned Result = 0;
525       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
526         // If we had an unencodable argument, bail out.
527         if (TypeSig[i] > 15) {
528           Failed = true;
529           break;
530         }
531         Result = (Result << 4) | TypeSig[e-i-1];
532       }
533 
534       // If this could be encoded into a 31-bit word, return it.
535       if (!Failed && (Result >> 31) == 0) {
536         FixedEncodings.push_back(Result);
537         continue;
538       }
539     }
540 
541     // Otherwise, we're going to unique the sequence into the
542     // LongEncodingTable, and use its offset in the 32-bit table instead.
543     LongEncodingTable.add(TypeSig);
544 
545     // This is a placehold that we'll replace after the table is laid out.
546     FixedEncodings.push_back(~0U);
547   }
548 
549   LongEncodingTable.layout();
550 
551   OS << "// Global intrinsic function declaration type table.\n";
552   OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
553 
554   OS << "static const unsigned IIT_Table[] = {\n  ";
555 
556   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
557     if ((i & 7) == 7)
558       OS << "\n  ";
559 
560     // If the entry fit in the table, just emit it.
561     if (FixedEncodings[i] != ~0U) {
562       OS << "0x" << Twine::utohexstr(FixedEncodings[i]) << ", ";
563       continue;
564     }
565 
566     TypeSig.clear();
567     ComputeFixedEncoding(Ints[i], TypeSig);
568 
569 
570     // Otherwise, emit the offset into the long encoding table.  We emit it this
571     // way so that it is easier to read the offset in the .def file.
572     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
573   }
574 
575   OS << "0\n};\n\n";
576 
577   // Emit the shared table of register lists.
578   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
579   if (!LongEncodingTable.empty())
580     LongEncodingTable.emit(OS, printIITEntry);
581   OS << "  255\n};\n\n";
582 
583   OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
584 }
585 
586 namespace {
587 struct AttributeComparator {
588   bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
589     // Sort throwing intrinsics after non-throwing intrinsics.
590     if (L->canThrow != R->canThrow)
591       return R->canThrow;
592 
593     if (L->isNoDuplicate != R->isNoDuplicate)
594       return R->isNoDuplicate;
595 
596     if (L->isNoMerge != R->isNoMerge)
597       return R->isNoMerge;
598 
599     if (L->isNoReturn != R->isNoReturn)
600       return R->isNoReturn;
601 
602     if (L->isNoSync != R->isNoSync)
603       return R->isNoSync;
604 
605     if (L->isNoFree != R->isNoFree)
606       return R->isNoFree;
607 
608     if (L->isWillReturn != R->isWillReturn)
609       return R->isWillReturn;
610 
611     if (L->isCold != R->isCold)
612       return R->isCold;
613 
614     if (L->isConvergent != R->isConvergent)
615       return R->isConvergent;
616 
617     if (L->isSpeculatable != R->isSpeculatable)
618       return R->isSpeculatable;
619 
620     if (L->hasSideEffects != R->hasSideEffects)
621       return R->hasSideEffects;
622 
623     // Try to order by readonly/readnone attribute.
624     CodeGenIntrinsic::ModRefBehavior LK = L->ModRef;
625     CodeGenIntrinsic::ModRefBehavior RK = R->ModRef;
626     if (LK != RK) return (LK > RK);
627     // Order by argument attributes.
628     // This is reliable because each side is already sorted internally.
629     return (L->ArgumentAttributes < R->ArgumentAttributes);
630   }
631 };
632 } // End anonymous namespace
633 
634 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
635 void IntrinsicEmitter::EmitAttributes(const CodeGenIntrinsicTable &Ints,
636                                       raw_ostream &OS) {
637   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
638   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
639   OS << "AttributeList Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
640 
641   // Compute the maximum number of attribute arguments and the map
642   typedef std::map<const CodeGenIntrinsic*, unsigned,
643                    AttributeComparator> UniqAttrMapTy;
644   UniqAttrMapTy UniqAttributes;
645   unsigned maxArgAttrs = 0;
646   unsigned AttrNum = 0;
647   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
648     const CodeGenIntrinsic &intrinsic = Ints[i];
649     maxArgAttrs =
650       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
651     unsigned &N = UniqAttributes[&intrinsic];
652     if (N) continue;
653     N = ++AttrNum;
654     assert(N < 65536 && "Too many unique attributes for table!");
655   }
656 
657   // Emit an array of AttributeList.  Most intrinsics will have at least one
658   // entry, for the function itself (index ~1), which is usually nounwind.
659   OS << "  static const uint16_t IntrinsicsToAttributesMap[] = {\n";
660 
661   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
662     const CodeGenIntrinsic &intrinsic = Ints[i];
663 
664     OS << "    " << UniqAttributes[&intrinsic] << ", // "
665        << intrinsic.Name << "\n";
666   }
667   OS << "  };\n\n";
668 
669   OS << "  AttributeList AS[" << maxArgAttrs + 1 << "];\n";
670   OS << "  unsigned NumAttrs = 0;\n";
671   OS << "  if (id != 0) {\n";
672   OS << "    switch(IntrinsicsToAttributesMap[id - 1]) {\n";
673   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
674   for (auto UniqAttribute : UniqAttributes) {
675     OS << "    case " << UniqAttribute.second << ": {\n";
676 
677     const CodeGenIntrinsic &Intrinsic = *(UniqAttribute.first);
678 
679     // Keep track of the number of attributes we're writing out.
680     unsigned numAttrs = 0;
681 
682     // The argument attributes are alreadys sorted by argument index.
683     unsigned Ai = 0, Ae = Intrinsic.ArgumentAttributes.size();
684     if (Ae) {
685       while (Ai != Ae) {
686         unsigned AttrIdx = Intrinsic.ArgumentAttributes[Ai].Index;
687 
688         OS << "      const Attribute::AttrKind AttrParam" << AttrIdx << "[]= {";
689         ListSeparator LS(",");
690 
691         bool AllValuesAreZero = true;
692         SmallVector<uint64_t, 8> Values;
693         do {
694           switch (Intrinsic.ArgumentAttributes[Ai].Kind) {
695           case CodeGenIntrinsic::NoCapture:
696             OS << LS << "Attribute::NoCapture";
697             break;
698           case CodeGenIntrinsic::NoAlias:
699             OS << LS << "Attribute::NoAlias";
700             break;
701           case CodeGenIntrinsic::NoUndef:
702             OS << LS << "Attribute::NoUndef";
703             break;
704           case CodeGenIntrinsic::Returned:
705             OS << LS << "Attribute::Returned";
706             break;
707           case CodeGenIntrinsic::ReadOnly:
708             OS << LS << "Attribute::ReadOnly";
709             break;
710           case CodeGenIntrinsic::WriteOnly:
711             OS << LS << "Attribute::WriteOnly";
712             break;
713           case CodeGenIntrinsic::ReadNone:
714             OS << LS << "Attribute::ReadNone";
715             break;
716           case CodeGenIntrinsic::ImmArg:
717             OS << LS << "Attribute::ImmArg";
718             break;
719           case CodeGenIntrinsic::Alignment:
720             OS << LS << "Attribute::Alignment";
721             break;
722           }
723           uint64_t V = Intrinsic.ArgumentAttributes[Ai].Value;
724           Values.push_back(V);
725           AllValuesAreZero &= (V == 0);
726 
727           ++Ai;
728         } while (Ai != Ae && Intrinsic.ArgumentAttributes[Ai].Index == AttrIdx);
729         OS << "};\n";
730 
731         // Generate attribute value array if not all attribute values are zero.
732         if (!AllValuesAreZero) {
733           OS << "      const uint64_t AttrValParam" << AttrIdx << "[]= {";
734           ListSeparator LSV(",");
735           for (const auto V : Values)
736             OS << LSV << V;
737           OS << "};\n";
738         }
739 
740         OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
741            << AttrIdx << ", AttrParam" << AttrIdx;
742         if (!AllValuesAreZero)
743           OS << ", AttrValParam" << AttrIdx;
744         OS << ");\n";
745       }
746     }
747 
748     if (!Intrinsic.canThrow ||
749         (Intrinsic.ModRef != CodeGenIntrinsic::ReadWriteMem &&
750          !Intrinsic.hasSideEffects) ||
751         Intrinsic.isNoReturn || Intrinsic.isNoSync || Intrinsic.isNoFree ||
752         Intrinsic.isWillReturn || Intrinsic.isCold || Intrinsic.isNoDuplicate ||
753         Intrinsic.isNoMerge || Intrinsic.isConvergent ||
754         Intrinsic.isSpeculatable) {
755       OS << "      const Attribute::AttrKind Atts[] = {";
756       ListSeparator LS(",");
757       if (!Intrinsic.canThrow)
758         OS << LS << "Attribute::NoUnwind";
759       if (Intrinsic.isNoReturn)
760         OS << LS << "Attribute::NoReturn";
761       if (Intrinsic.isNoSync)
762         OS << LS << "Attribute::NoSync";
763       if (Intrinsic.isNoFree)
764         OS << LS << "Attribute::NoFree";
765       if (Intrinsic.isWillReturn)
766         OS << LS << "Attribute::WillReturn";
767       if (Intrinsic.isCold)
768         OS << LS << "Attribute::Cold";
769       if (Intrinsic.isNoDuplicate)
770         OS << LS << "Attribute::NoDuplicate";
771       if (Intrinsic.isNoMerge)
772         OS << LS << "Attribute::NoMerge";
773       if (Intrinsic.isConvergent)
774         OS << LS << "Attribute::Convergent";
775       if (Intrinsic.isSpeculatable)
776         OS << LS << "Attribute::Speculatable";
777 
778       switch (Intrinsic.ModRef) {
779       case CodeGenIntrinsic::NoMem:
780         if (Intrinsic.hasSideEffects)
781           break;
782         OS << LS;
783         OS << "Attribute::ReadNone";
784         break;
785       case CodeGenIntrinsic::ReadArgMem:
786         OS << LS;
787         OS << "Attribute::ReadOnly,";
788         OS << "Attribute::ArgMemOnly";
789         break;
790       case CodeGenIntrinsic::ReadMem:
791         OS << LS;
792         OS << "Attribute::ReadOnly";
793         break;
794       case CodeGenIntrinsic::ReadInaccessibleMem:
795         OS << LS;
796         OS << "Attribute::ReadOnly,";
797         OS << "Attribute::InaccessibleMemOnly";
798         break;
799       case CodeGenIntrinsic::ReadInaccessibleMemOrArgMem:
800         OS << LS;
801         OS << "Attribute::ReadOnly,";
802         OS << "Attribute::InaccessibleMemOrArgMemOnly";
803         break;
804       case CodeGenIntrinsic::WriteArgMem:
805         OS << LS;
806         OS << "Attribute::WriteOnly,";
807         OS << "Attribute::ArgMemOnly";
808         break;
809       case CodeGenIntrinsic::WriteMem:
810         OS << LS;
811         OS << "Attribute::WriteOnly";
812         break;
813       case CodeGenIntrinsic::WriteInaccessibleMem:
814         OS << LS;
815         OS << "Attribute::WriteOnly,";
816         OS << "Attribute::InaccessibleMemOnly";
817         break;
818       case CodeGenIntrinsic::WriteInaccessibleMemOrArgMem:
819         OS << LS;
820         OS << "Attribute::WriteOnly,";
821         OS << "Attribute::InaccessibleMemOrArgMemOnly";
822         break;
823       case CodeGenIntrinsic::ReadWriteArgMem:
824         OS << LS;
825         OS << "Attribute::ArgMemOnly";
826         break;
827       case CodeGenIntrinsic::ReadWriteInaccessibleMem:
828         OS << LS;
829         OS << "Attribute::InaccessibleMemOnly";
830         break;
831       case CodeGenIntrinsic::ReadWriteInaccessibleMemOrArgMem:
832         OS << LS;
833         OS << "Attribute::InaccessibleMemOrArgMemOnly";
834         break;
835       case CodeGenIntrinsic::ReadWriteMem:
836         break;
837       }
838       OS << "};\n";
839       OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
840          << "AttributeList::FunctionIndex, Atts);\n";
841     }
842 
843     if (numAttrs) {
844       OS << "      NumAttrs = " << numAttrs << ";\n";
845       OS << "      break;\n";
846       OS << "      }\n";
847     } else {
848       OS << "      return AttributeList();\n";
849       OS << "      }\n";
850     }
851   }
852 
853   OS << "    }\n";
854   OS << "  }\n";
855   OS << "  return AttributeList::get(C, makeArrayRef(AS, NumAttrs));\n";
856   OS << "}\n";
857   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
858 }
859 
860 void IntrinsicEmitter::EmitIntrinsicToBuiltinMap(
861     const CodeGenIntrinsicTable &Ints, bool IsGCC, raw_ostream &OS) {
862   StringRef CompilerName = (IsGCC ? "GCC" : "MS");
863   typedef std::map<std::string, std::map<std::string, std::string>> BIMTy;
864   BIMTy BuiltinMap;
865   StringToOffsetTable Table;
866   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
867     const std::string &BuiltinName =
868         IsGCC ? Ints[i].GCCBuiltinName : Ints[i].MSBuiltinName;
869     if (!BuiltinName.empty()) {
870       // Get the map for this target prefix.
871       std::map<std::string, std::string> &BIM =
872           BuiltinMap[Ints[i].TargetPrefix];
873 
874       if (!BIM.insert(std::make_pair(BuiltinName, Ints[i].EnumName)).second)
875         PrintFatalError(Ints[i].TheDef->getLoc(),
876                         "Intrinsic '" + Ints[i].TheDef->getName() +
877                             "': duplicate " + CompilerName + " builtin name!");
878       Table.GetOrAddStringOffset(BuiltinName);
879     }
880   }
881 
882   OS << "// Get the LLVM intrinsic that corresponds to a builtin.\n";
883   OS << "// This is used by the C front-end.  The builtin name is passed\n";
884   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
885   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
886   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_" << CompilerName << "_BUILTIN\n";
887 
888   OS << "Intrinsic::ID Intrinsic::getIntrinsicFor" << CompilerName
889      << "Builtin(const char "
890      << "*TargetPrefixStr, StringRef BuiltinNameStr) {\n";
891 
892   if (Table.Empty()) {
893     OS << "  return Intrinsic::not_intrinsic;\n";
894     OS << "}\n";
895     OS << "#endif\n\n";
896     return;
897   }
898 
899   OS << "  static const char BuiltinNames[] = {\n";
900   Table.EmitCharArray(OS);
901   OS << "  };\n\n";
902 
903   OS << "  struct BuiltinEntry {\n";
904   OS << "    Intrinsic::ID IntrinID;\n";
905   OS << "    unsigned StrTabOffset;\n";
906   OS << "    const char *getName() const {\n";
907   OS << "      return &BuiltinNames[StrTabOffset];\n";
908   OS << "    }\n";
909   OS << "    bool operator<(StringRef RHS) const {\n";
910   OS << "      return strncmp(getName(), RHS.data(), RHS.size()) < 0;\n";
911   OS << "    }\n";
912   OS << "  };\n";
913 
914   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
915 
916   // Note: this could emit significantly better code if we cared.
917   for (auto &I : BuiltinMap) {
918     OS << "  ";
919     if (!I.first.empty())
920       OS << "if (TargetPrefix == \"" << I.first << "\") ";
921     else
922       OS << "/* Target Independent Builtins */ ";
923     OS << "{\n";
924 
925     // Emit the comparisons for this target prefix.
926     OS << "    static const BuiltinEntry " << I.first << "Names[] = {\n";
927     for (const auto &P : I.second) {
928       OS << "      {Intrinsic::" << P.second << ", "
929          << Table.GetOrAddStringOffset(P.first) << "}, // " << P.first << "\n";
930     }
931     OS << "    };\n";
932     OS << "    auto I = std::lower_bound(std::begin(" << I.first << "Names),\n";
933     OS << "                              std::end(" << I.first << "Names),\n";
934     OS << "                              BuiltinNameStr);\n";
935     OS << "    if (I != std::end(" << I.first << "Names) &&\n";
936     OS << "        I->getName() == BuiltinNameStr)\n";
937     OS << "      return I->IntrinID;\n";
938     OS << "  }\n";
939   }
940   OS << "  return ";
941   OS << "Intrinsic::not_intrinsic;\n";
942   OS << "}\n";
943   OS << "#endif\n\n";
944 }
945 
946 void llvm::EmitIntrinsicEnums(RecordKeeper &RK, raw_ostream &OS) {
947   IntrinsicEmitter(RK).run(OS, /*Enums=*/true);
948 }
949 
950 void llvm::EmitIntrinsicImpl(RecordKeeper &RK, raw_ostream &OS) {
951   IntrinsicEmitter(RK).run(OS, /*Enums=*/false);
952 }
953