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