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 };
250 
251 static void EncodeFixedValueType(MVT::SimpleValueType VT,
252                                  std::vector<unsigned char> &Sig) {
253   if (MVT(VT).isInteger()) {
254     unsigned BitWidth = MVT(VT).getSizeInBits();
255     switch (BitWidth) {
256     default: PrintFatalError("unhandled integer type width in intrinsic!");
257     case 1: return Sig.push_back(IIT_I1);
258     case 8: return Sig.push_back(IIT_I8);
259     case 16: return Sig.push_back(IIT_I16);
260     case 32: return Sig.push_back(IIT_I32);
261     case 64: return Sig.push_back(IIT_I64);
262     case 128: return Sig.push_back(IIT_I128);
263     }
264   }
265 
266   switch (VT) {
267   default: PrintFatalError("unhandled MVT in intrinsic!");
268   case MVT::f16: return Sig.push_back(IIT_F16);
269   case MVT::f32: return Sig.push_back(IIT_F32);
270   case MVT::f64: return Sig.push_back(IIT_F64);
271   case MVT::f128: return Sig.push_back(IIT_F128);
272   case MVT::token: return Sig.push_back(IIT_TOKEN);
273   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
274   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
275   // MVT::OtherVT is used to mean the empty struct type here.
276   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
277   // MVT::isVoid is used to represent varargs here.
278   case MVT::isVoid: return Sig.push_back(IIT_VARARG);
279   }
280 }
281 
282 #if defined(_MSC_VER) && !defined(__clang__)
283 #pragma optimize("",off) // MSVC 2015 optimizer can't deal with this function.
284 #endif
285 
286 static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
287                             unsigned &NextArgCode,
288                             std::vector<unsigned char> &Sig,
289                             ArrayRef<unsigned char> Mapping) {
290 
291   if (R->isSubClassOf("LLVMMatchType")) {
292     unsigned Number = Mapping[R->getValueAsInt("Number")];
293     assert(Number < ArgCodes.size() && "Invalid matching number!");
294     if (R->isSubClassOf("LLVMExtendedType"))
295       Sig.push_back(IIT_EXTEND_ARG);
296     else if (R->isSubClassOf("LLVMTruncatedType"))
297       Sig.push_back(IIT_TRUNC_ARG);
298     else if (R->isSubClassOf("LLVMHalfElementsVectorType"))
299       Sig.push_back(IIT_HALF_VEC_ARG);
300     else if (R->isSubClassOf("LLVMScalarOrSameVectorWidth")) {
301       Sig.push_back(IIT_SAME_VEC_WIDTH_ARG);
302       Sig.push_back((Number << 3) | ArgCodes[Number]);
303       MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy"));
304       EncodeFixedValueType(VT, Sig);
305       return;
306     }
307     else if (R->isSubClassOf("LLVMPointerTo"))
308       Sig.push_back(IIT_PTR_TO_ARG);
309     else if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
310       Sig.push_back(IIT_VEC_OF_ANYPTRS_TO_ELT);
311       // Encode overloaded ArgNo
312       Sig.push_back(NextArgCode++);
313       // Encode LLVMMatchType<Number> ArgNo
314       Sig.push_back(Number);
315       return;
316     } else if (R->isSubClassOf("LLVMPointerToElt"))
317       Sig.push_back(IIT_PTR_TO_ELT);
318     else if (R->isSubClassOf("LLVMVectorElementType"))
319       Sig.push_back(IIT_VEC_ELEMENT);
320     else if (R->isSubClassOf("LLVMSubdivide2VectorType"))
321       Sig.push_back(IIT_SUBDIVIDE2_ARG);
322     else if (R->isSubClassOf("LLVMSubdivide4VectorType"))
323       Sig.push_back(IIT_SUBDIVIDE4_ARG);
324     else if (R->isSubClassOf("LLVMVectorOfBitcastsToInt"))
325       Sig.push_back(IIT_VEC_OF_BITCASTS_TO_INT);
326     else
327       Sig.push_back(IIT_ARG);
328     return Sig.push_back((Number << 3) | 7 /*IITDescriptor::AK_MatchType*/);
329   }
330 
331   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
332 
333   unsigned Tmp = 0;
334   switch (VT) {
335   default: break;
336   case MVT::iPTRAny: ++Tmp; LLVM_FALLTHROUGH;
337   case MVT::vAny: ++Tmp;    LLVM_FALLTHROUGH;
338   case MVT::fAny: ++Tmp;    LLVM_FALLTHROUGH;
339   case MVT::iAny: ++Tmp;    LLVM_FALLTHROUGH;
340   case MVT::Any: {
341     // If this is an "any" valuetype, then the type is the type of the next
342     // type in the list specified to getIntrinsic().
343     Sig.push_back(IIT_ARG);
344 
345     // Figure out what arg # this is consuming, and remember what kind it was.
346     assert(NextArgCode < ArgCodes.size() && ArgCodes[NextArgCode] == Tmp &&
347            "Invalid or no ArgCode associated with overloaded VT!");
348     unsigned ArgNo = NextArgCode++;
349 
350     // Encode what sort of argument it must be in the low 3 bits of the ArgNo.
351     return Sig.push_back((ArgNo << 3) | Tmp);
352   }
353 
354   case MVT::iPTR: {
355     unsigned AddrSpace = 0;
356     if (R->isSubClassOf("LLVMQualPointerType")) {
357       AddrSpace = R->getValueAsInt("AddrSpace");
358       assert(AddrSpace < 256 && "Address space exceeds 255");
359     }
360     if (AddrSpace) {
361       Sig.push_back(IIT_ANYPTR);
362       Sig.push_back(AddrSpace);
363     } else {
364       Sig.push_back(IIT_PTR);
365     }
366     return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, NextArgCode, Sig,
367                            Mapping);
368   }
369   }
370 
371   if (MVT(VT).isVector()) {
372     MVT VVT = VT;
373     if (VVT.isScalableVector())
374       Sig.push_back(IIT_SCALABLE_VEC);
375     switch (VVT.getVectorNumElements()) {
376     default: PrintFatalError("unhandled vector type width in intrinsic!");
377     case 1: Sig.push_back(IIT_V1); break;
378     case 2: Sig.push_back(IIT_V2); break;
379     case 4: Sig.push_back(IIT_V4); break;
380     case 8: Sig.push_back(IIT_V8); break;
381     case 16: Sig.push_back(IIT_V16); break;
382     case 32: Sig.push_back(IIT_V32); break;
383     case 64: Sig.push_back(IIT_V64); break;
384     case 128: Sig.push_back(IIT_V128); break;
385     case 512: Sig.push_back(IIT_V512); break;
386     case 1024: Sig.push_back(IIT_V1024); break;
387     }
388 
389     return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
390   }
391 
392   EncodeFixedValueType(VT, Sig);
393 }
394 
395 static void UpdateArgCodes(Record *R, std::vector<unsigned char> &ArgCodes,
396                            unsigned int &NumInserted,
397                            SmallVectorImpl<unsigned char> &Mapping) {
398   if (R->isSubClassOf("LLVMMatchType")) {
399     if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
400       ArgCodes.push_back(3 /*vAny*/);
401       ++NumInserted;
402     }
403     return;
404   }
405 
406   unsigned Tmp = 0;
407   switch (getValueType(R->getValueAsDef("VT"))) {
408   default: break;
409   case MVT::iPTR:
410     UpdateArgCodes(R->getValueAsDef("ElTy"), ArgCodes, NumInserted, Mapping);
411     break;
412   case MVT::iPTRAny:
413     ++Tmp;
414     LLVM_FALLTHROUGH;
415   case MVT::vAny:
416     ++Tmp;
417     LLVM_FALLTHROUGH;
418   case MVT::fAny:
419     ++Tmp;
420     LLVM_FALLTHROUGH;
421   case MVT::iAny:
422     ++Tmp;
423     LLVM_FALLTHROUGH;
424   case MVT::Any:
425     unsigned OriginalIdx = ArgCodes.size() - NumInserted;
426     assert(OriginalIdx >= Mapping.size());
427     Mapping.resize(OriginalIdx+1);
428     Mapping[OriginalIdx] = ArgCodes.size();
429     ArgCodes.push_back(Tmp);
430     break;
431   }
432 }
433 
434 #if defined(_MSC_VER) && !defined(__clang__)
435 #pragma optimize("",on)
436 #endif
437 
438 /// ComputeFixedEncoding - If we can encode the type signature for this
439 /// intrinsic into 32 bits, return it.  If not, return ~0U.
440 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
441                                  std::vector<unsigned char> &TypeSig) {
442   std::vector<unsigned char> ArgCodes;
443 
444   // Add codes for any overloaded result VTs.
445   unsigned int NumInserted = 0;
446   SmallVector<unsigned char, 8> ArgMapping;
447   for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
448     UpdateArgCodes(Int.IS.RetTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
449 
450   // Add codes for any overloaded operand VTs.
451   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
452     UpdateArgCodes(Int.IS.ParamTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
453 
454   unsigned NextArgCode = 0;
455   if (Int.IS.RetVTs.empty())
456     TypeSig.push_back(IIT_Done);
457   else if (Int.IS.RetVTs.size() == 1 &&
458            Int.IS.RetVTs[0] == MVT::isVoid)
459     TypeSig.push_back(IIT_Done);
460   else {
461     switch (Int.IS.RetVTs.size()) {
462       case 1: break;
463       case 2: TypeSig.push_back(IIT_STRUCT2); break;
464       case 3: TypeSig.push_back(IIT_STRUCT3); break;
465       case 4: TypeSig.push_back(IIT_STRUCT4); break;
466       case 5: TypeSig.push_back(IIT_STRUCT5); break;
467       case 6: TypeSig.push_back(IIT_STRUCT6); break;
468       case 7: TypeSig.push_back(IIT_STRUCT7); break;
469       case 8: TypeSig.push_back(IIT_STRUCT8); break;
470       default: llvm_unreachable("Unhandled case in struct");
471     }
472 
473     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
474       EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
475                       ArgMapping);
476   }
477 
478   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
479     EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
480                     ArgMapping);
481 }
482 
483 static void printIITEntry(raw_ostream &OS, unsigned char X) {
484   OS << (unsigned)X;
485 }
486 
487 void IntrinsicEmitter::EmitGenerator(const CodeGenIntrinsicTable &Ints,
488                                      raw_ostream &OS) {
489   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
490   // capture it in this vector, otherwise store a ~0U.
491   std::vector<unsigned> FixedEncodings;
492 
493   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
494 
495   std::vector<unsigned char> TypeSig;
496 
497   // Compute the unique argument type info.
498   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
499     // Get the signature for the intrinsic.
500     TypeSig.clear();
501     ComputeFixedEncoding(Ints[i], TypeSig);
502 
503     // Check to see if we can encode it into a 32-bit word.  We can only encode
504     // 8 nibbles into a 32-bit word.
505     if (TypeSig.size() <= 8) {
506       bool Failed = false;
507       unsigned Result = 0;
508       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
509         // If we had an unencodable argument, bail out.
510         if (TypeSig[i] > 15) {
511           Failed = true;
512           break;
513         }
514         Result = (Result << 4) | TypeSig[e-i-1];
515       }
516 
517       // If this could be encoded into a 31-bit word, return it.
518       if (!Failed && (Result >> 31) == 0) {
519         FixedEncodings.push_back(Result);
520         continue;
521       }
522     }
523 
524     // Otherwise, we're going to unique the sequence into the
525     // LongEncodingTable, and use its offset in the 32-bit table instead.
526     LongEncodingTable.add(TypeSig);
527 
528     // This is a placehold that we'll replace after the table is laid out.
529     FixedEncodings.push_back(~0U);
530   }
531 
532   LongEncodingTable.layout();
533 
534   OS << "// Global intrinsic function declaration type table.\n";
535   OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
536 
537   OS << "static const unsigned IIT_Table[] = {\n  ";
538 
539   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
540     if ((i & 7) == 7)
541       OS << "\n  ";
542 
543     // If the entry fit in the table, just emit it.
544     if (FixedEncodings[i] != ~0U) {
545       OS << "0x" << Twine::utohexstr(FixedEncodings[i]) << ", ";
546       continue;
547     }
548 
549     TypeSig.clear();
550     ComputeFixedEncoding(Ints[i], TypeSig);
551 
552 
553     // Otherwise, emit the offset into the long encoding table.  We emit it this
554     // way so that it is easier to read the offset in the .def file.
555     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
556   }
557 
558   OS << "0\n};\n\n";
559 
560   // Emit the shared table of register lists.
561   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
562   if (!LongEncodingTable.empty())
563     LongEncodingTable.emit(OS, printIITEntry);
564   OS << "  255\n};\n\n";
565 
566   OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
567 }
568 
569 namespace {
570 struct AttributeComparator {
571   bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
572     // Sort throwing intrinsics after non-throwing intrinsics.
573     if (L->canThrow != R->canThrow)
574       return R->canThrow;
575 
576     if (L->isNoDuplicate != R->isNoDuplicate)
577       return R->isNoDuplicate;
578 
579     if (L->isNoReturn != R->isNoReturn)
580       return R->isNoReturn;
581 
582     if (L->isNoSync != R->isNoSync)
583       return R->isNoSync;
584 
585     if (L->isWillReturn != R->isWillReturn)
586       return R->isWillReturn;
587 
588     if (L->isCold != R->isCold)
589       return R->isCold;
590 
591     if (L->isConvergent != R->isConvergent)
592       return R->isConvergent;
593 
594     if (L->isSpeculatable != R->isSpeculatable)
595       return R->isSpeculatable;
596 
597     if (L->hasSideEffects != R->hasSideEffects)
598       return R->hasSideEffects;
599 
600     // Try to order by readonly/readnone attribute.
601     CodeGenIntrinsic::ModRefBehavior LK = L->ModRef;
602     CodeGenIntrinsic::ModRefBehavior RK = R->ModRef;
603     if (LK != RK) return (LK > RK);
604     // Order by argument attributes.
605     // This is reliable because each side is already sorted internally.
606     return (L->ArgumentAttributes < R->ArgumentAttributes);
607   }
608 };
609 } // End anonymous namespace
610 
611 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
612 void IntrinsicEmitter::EmitAttributes(const CodeGenIntrinsicTable &Ints,
613                                       raw_ostream &OS) {
614   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
615   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
616   OS << "AttributeList Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
617 
618   // Compute the maximum number of attribute arguments and the map
619   typedef std::map<const CodeGenIntrinsic*, unsigned,
620                    AttributeComparator> UniqAttrMapTy;
621   UniqAttrMapTy UniqAttributes;
622   unsigned maxArgAttrs = 0;
623   unsigned AttrNum = 0;
624   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
625     const CodeGenIntrinsic &intrinsic = Ints[i];
626     maxArgAttrs =
627       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
628     unsigned &N = UniqAttributes[&intrinsic];
629     if (N) continue;
630     assert(AttrNum < 256 && "Too many unique attributes for table!");
631     N = ++AttrNum;
632   }
633 
634   // Emit an array of AttributeList.  Most intrinsics will have at least one
635   // entry, for the function itself (index ~1), which is usually nounwind.
636   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
637 
638   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
639     const CodeGenIntrinsic &intrinsic = Ints[i];
640 
641     OS << "    " << UniqAttributes[&intrinsic] << ", // "
642        << intrinsic.Name << "\n";
643   }
644   OS << "  };\n\n";
645 
646   OS << "  AttributeList AS[" << maxArgAttrs + 1 << "];\n";
647   OS << "  unsigned NumAttrs = 0;\n";
648   OS << "  if (id != 0) {\n";
649   OS << "    switch(IntrinsicsToAttributesMap[id - 1]) {\n";
650   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
651   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
652        E = UniqAttributes.end(); I != E; ++I) {
653     OS << "    case " << I->second << ": {\n";
654 
655     const CodeGenIntrinsic &intrinsic = *(I->first);
656 
657     // Keep track of the number of attributes we're writing out.
658     unsigned numAttrs = 0;
659 
660     // The argument attributes are alreadys sorted by argument index.
661     unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size();
662     if (ae) {
663       while (ai != ae) {
664         unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
665         unsigned attrIdx = argNo + 1; // Must match AttributeList::FirstArgIndex
666 
667         OS << "      const Attribute::AttrKind AttrParam" << attrIdx << "[]= {";
668         bool addComma = false;
669 
670         do {
671           switch (intrinsic.ArgumentAttributes[ai].second) {
672           case CodeGenIntrinsic::NoCapture:
673             if (addComma)
674               OS << ",";
675             OS << "Attribute::NoCapture";
676             addComma = true;
677             break;
678           case CodeGenIntrinsic::NoAlias:
679             if (addComma)
680               OS << ",";
681             OS << "Attribute::NoAlias";
682             addComma = true;
683             break;
684           case CodeGenIntrinsic::Returned:
685             if (addComma)
686               OS << ",";
687             OS << "Attribute::Returned";
688             addComma = true;
689             break;
690           case CodeGenIntrinsic::ReadOnly:
691             if (addComma)
692               OS << ",";
693             OS << "Attribute::ReadOnly";
694             addComma = true;
695             break;
696           case CodeGenIntrinsic::WriteOnly:
697             if (addComma)
698               OS << ",";
699             OS << "Attribute::WriteOnly";
700             addComma = true;
701             break;
702           case CodeGenIntrinsic::ReadNone:
703             if (addComma)
704               OS << ",";
705             OS << "Attribute::ReadNone";
706             addComma = true;
707             break;
708           case CodeGenIntrinsic::ImmArg:
709             if (addComma)
710               OS << ',';
711             OS << "Attribute::ImmArg";
712             addComma = true;
713             break;
714           }
715 
716           ++ai;
717         } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
718         OS << "};\n";
719         OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
720            << attrIdx << ", AttrParam" << attrIdx << ");\n";
721       }
722     }
723 
724     if (!intrinsic.canThrow ||
725         (intrinsic.ModRef != CodeGenIntrinsic::ReadWriteMem && !intrinsic.hasSideEffects) ||
726         intrinsic.isNoReturn || intrinsic.isNoSync || intrinsic.isWillReturn ||
727         intrinsic.isCold || intrinsic.isNoDuplicate || intrinsic.isConvergent ||
728         intrinsic.isSpeculatable) {
729       OS << "      const Attribute::AttrKind Atts[] = {";
730       bool addComma = false;
731       if (!intrinsic.canThrow) {
732         OS << "Attribute::NoUnwind";
733         addComma = true;
734       }
735       if (intrinsic.isNoReturn) {
736         if (addComma)
737           OS << ",";
738         OS << "Attribute::NoReturn";
739         addComma = true;
740       }
741       if (intrinsic.isNoSync) {
742         if (addComma)
743           OS << ",";
744         OS << "Attribute::NoSync";
745         addComma = true;
746       }
747       if (intrinsic.isWillReturn) {
748         if (addComma)
749           OS << ",";
750         OS << "Attribute::WillReturn";
751         addComma = true;
752       }
753       if (intrinsic.isCold) {
754         if (addComma)
755           OS << ",";
756         OS << "Attribute::Cold";
757         addComma = true;
758       }
759       if (intrinsic.isNoDuplicate) {
760         if (addComma)
761           OS << ",";
762         OS << "Attribute::NoDuplicate";
763         addComma = true;
764       }
765       if (intrinsic.isConvergent) {
766         if (addComma)
767           OS << ",";
768         OS << "Attribute::Convergent";
769         addComma = true;
770       }
771       if (intrinsic.isSpeculatable) {
772         if (addComma)
773           OS << ",";
774         OS << "Attribute::Speculatable";
775         addComma = true;
776       }
777 
778       switch (intrinsic.ModRef) {
779       case CodeGenIntrinsic::NoMem:
780         if (intrinsic.hasSideEffects)
781           break;
782         if (addComma)
783           OS << ",";
784         OS << "Attribute::ReadNone";
785         break;
786       case CodeGenIntrinsic::ReadArgMem:
787         if (addComma)
788           OS << ",";
789         OS << "Attribute::ReadOnly,";
790         OS << "Attribute::ArgMemOnly";
791         break;
792       case CodeGenIntrinsic::ReadMem:
793         if (addComma)
794           OS << ",";
795         OS << "Attribute::ReadOnly";
796         break;
797       case CodeGenIntrinsic::ReadInaccessibleMem:
798         if (addComma)
799           OS << ",";
800         OS << "Attribute::ReadOnly,";
801         OS << "Attribute::InaccessibleMemOnly";
802         break;
803       case CodeGenIntrinsic::ReadInaccessibleMemOrArgMem:
804         if (addComma)
805           OS << ",";
806         OS << "Attribute::ReadOnly,";
807         OS << "Attribute::InaccessibleMemOrArgMemOnly";
808         break;
809       case CodeGenIntrinsic::WriteArgMem:
810         if (addComma)
811           OS << ",";
812         OS << "Attribute::WriteOnly,";
813         OS << "Attribute::ArgMemOnly";
814         break;
815       case CodeGenIntrinsic::WriteMem:
816         if (addComma)
817           OS << ",";
818         OS << "Attribute::WriteOnly";
819         break;
820       case CodeGenIntrinsic::WriteInaccessibleMem:
821         if (addComma)
822           OS << ",";
823         OS << "Attribute::WriteOnly,";
824         OS << "Attribute::InaccessibleMemOnly";
825         break;
826       case CodeGenIntrinsic::WriteInaccessibleMemOrArgMem:
827         if (addComma)
828           OS << ",";
829         OS << "Attribute::WriteOnly,";
830         OS << "Attribute::InaccessibleMemOrArgMemOnly";
831         break;
832       case CodeGenIntrinsic::ReadWriteArgMem:
833         if (addComma)
834           OS << ",";
835         OS << "Attribute::ArgMemOnly";
836         break;
837       case CodeGenIntrinsic::ReadWriteInaccessibleMem:
838         if (addComma)
839           OS << ",";
840         OS << "Attribute::InaccessibleMemOnly";
841         break;
842       case CodeGenIntrinsic::ReadWriteInaccessibleMemOrArgMem:
843         if (addComma)
844           OS << ",";
845         OS << "Attribute::InaccessibleMemOrArgMemOnly";
846         break;
847       case CodeGenIntrinsic::ReadWriteMem:
848         break;
849       }
850       OS << "};\n";
851       OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
852          << "AttributeList::FunctionIndex, Atts);\n";
853     }
854 
855     if (numAttrs) {
856       OS << "      NumAttrs = " << numAttrs << ";\n";
857       OS << "      break;\n";
858       OS << "      }\n";
859     } else {
860       OS << "      return AttributeList();\n";
861       OS << "      }\n";
862     }
863   }
864 
865   OS << "    }\n";
866   OS << "  }\n";
867   OS << "  return AttributeList::get(C, makeArrayRef(AS, NumAttrs));\n";
868   OS << "}\n";
869   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
870 }
871 
872 void IntrinsicEmitter::EmitIntrinsicToBuiltinMap(
873     const CodeGenIntrinsicTable &Ints, bool IsGCC, raw_ostream &OS) {
874   StringRef CompilerName = (IsGCC ? "GCC" : "MS");
875   typedef std::map<std::string, std::map<std::string, std::string>> BIMTy;
876   BIMTy BuiltinMap;
877   StringToOffsetTable Table;
878   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
879     const std::string &BuiltinName =
880         IsGCC ? Ints[i].GCCBuiltinName : Ints[i].MSBuiltinName;
881     if (!BuiltinName.empty()) {
882       // Get the map for this target prefix.
883       std::map<std::string, std::string> &BIM =
884           BuiltinMap[Ints[i].TargetPrefix];
885 
886       if (!BIM.insert(std::make_pair(BuiltinName, Ints[i].EnumName)).second)
887         PrintFatalError(Ints[i].TheDef->getLoc(),
888                         "Intrinsic '" + Ints[i].TheDef->getName() +
889                             "': duplicate " + CompilerName + " builtin name!");
890       Table.GetOrAddStringOffset(BuiltinName);
891     }
892   }
893 
894   OS << "// Get the LLVM intrinsic that corresponds to a builtin.\n";
895   OS << "// This is used by the C front-end.  The builtin name is passed\n";
896   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
897   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
898   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_" << CompilerName << "_BUILTIN\n";
899 
900   OS << "Intrinsic::ID Intrinsic::getIntrinsicFor" << CompilerName
901      << "Builtin(const char "
902      << "*TargetPrefixStr, StringRef BuiltinNameStr) {\n";
903 
904   if (Table.Empty()) {
905     OS << "  return Intrinsic::not_intrinsic;\n";
906     OS << "}\n";
907     OS << "#endif\n\n";
908     return;
909   }
910 
911   OS << "  static const char BuiltinNames[] = {\n";
912   Table.EmitCharArray(OS);
913   OS << "  };\n\n";
914 
915   OS << "  struct BuiltinEntry {\n";
916   OS << "    Intrinsic::ID IntrinID;\n";
917   OS << "    unsigned StrTabOffset;\n";
918   OS << "    const char *getName() const {\n";
919   OS << "      return &BuiltinNames[StrTabOffset];\n";
920   OS << "    }\n";
921   OS << "    bool operator<(StringRef RHS) const {\n";
922   OS << "      return strncmp(getName(), RHS.data(), RHS.size()) < 0;\n";
923   OS << "    }\n";
924   OS << "  };\n";
925 
926   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
927 
928   // Note: this could emit significantly better code if we cared.
929   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
930     OS << "  ";
931     if (!I->first.empty())
932       OS << "if (TargetPrefix == \"" << I->first << "\") ";
933     else
934       OS << "/* Target Independent Builtins */ ";
935     OS << "{\n";
936 
937     // Emit the comparisons for this target prefix.
938     OS << "    static const BuiltinEntry " << I->first << "Names[] = {\n";
939     for (const auto &P : I->second) {
940       OS << "      {Intrinsic::" << P.second << ", "
941          << Table.GetOrAddStringOffset(P.first) << "}, // " << P.first << "\n";
942     }
943     OS << "    };\n";
944     OS << "    auto I = std::lower_bound(std::begin(" << I->first << "Names),\n";
945     OS << "                              std::end(" << I->first << "Names),\n";
946     OS << "                              BuiltinNameStr);\n";
947     OS << "    if (I != std::end(" << I->first << "Names) &&\n";
948     OS << "        I->getName() == BuiltinNameStr)\n";
949     OS << "      return I->IntrinID;\n";
950     OS << "  }\n";
951   }
952   OS << "  return ";
953   OS << "Intrinsic::not_intrinsic;\n";
954   OS << "}\n";
955   OS << "#endif\n\n";
956 }
957 
958 void llvm::EmitIntrinsicEnums(RecordKeeper &RK, raw_ostream &OS) {
959   IntrinsicEmitter(RK).run(OS, /*Enums=*/true);
960 }
961 
962 void llvm::EmitIntrinsicImpl(RecordKeeper &RK, raw_ostream &OS) {
963   IntrinsicEmitter(RK).run(OS, /*Enums=*/false);
964 }
965