[AVX512] Added intrinsics for VPCMPEQB and VPCMPEQW.
[oota-llvm.git] / utils / TableGen / IntrinsicEmitter.cpp
1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits information about intrinsic functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenIntrinsics.h"
15 #include "CodeGenTarget.h"
16 #include "SequenceToOffsetTable.h"
17 #include "TableGenBackends.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/StringMatcher.h"
22 #include "llvm/TableGen/TableGenBackend.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 namespace {
27 class IntrinsicEmitter {
28   RecordKeeper &Records;
29   bool TargetOnly;
30   std::string TargetPrefix;
31
32 public:
33   IntrinsicEmitter(RecordKeeper &R, bool T)
34     : Records(R), TargetOnly(T) {}
35
36   void run(raw_ostream &OS);
37
38   void EmitPrefix(raw_ostream &OS);
39
40   void EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
41                     raw_ostream &OS);
42
43   void EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
44                             raw_ostream &OS);
45   void EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
46                                 raw_ostream &OS);
47   void EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,
48                                     raw_ostream &OS);
49   void EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
50                      raw_ostream &OS);
51   void EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints,
52                       raw_ostream &OS);
53   void EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints,
54                           raw_ostream &OS);
55   void EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
56                                     raw_ostream &OS);
57   void EmitIntrinsicToMSBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
58                                    raw_ostream &OS);
59   void EmitSuffix(raw_ostream &OS);
60 };
61 } // End anonymous namespace
62
63 //===----------------------------------------------------------------------===//
64 // IntrinsicEmitter Implementation
65 //===----------------------------------------------------------------------===//
66
67 void IntrinsicEmitter::run(raw_ostream &OS) {
68   emitSourceFileHeader("Intrinsic Function Source Fragment", OS);
69
70   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records, TargetOnly);
71
72   if (TargetOnly && !Ints.empty())
73     TargetPrefix = Ints[0].TargetPrefix;
74
75   EmitPrefix(OS);
76
77   // Emit the enum information.
78   EmitEnumInfo(Ints, OS);
79
80   // Emit the intrinsic ID -> name table.
81   EmitIntrinsicToNameTable(Ints, OS);
82
83   // Emit the intrinsic ID -> overload table.
84   EmitIntrinsicToOverloadTable(Ints, OS);
85
86   // Emit the function name recognizer.
87   EmitFnNameRecognizer(Ints, OS);
88
89   // Emit the intrinsic declaration generator.
90   EmitGenerator(Ints, OS);
91
92   // Emit the intrinsic parameter attributes.
93   EmitAttributes(Ints, OS);
94
95   // Emit intrinsic alias analysis mod/ref behavior.
96   EmitModRefBehavior(Ints, OS);
97
98   // Emit code to translate GCC builtins into LLVM intrinsics.
99   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
100
101   // Emit code to translate MS builtins into LLVM intrinsics.
102   EmitIntrinsicToMSBuiltinMap(Ints, OS);
103
104   EmitSuffix(OS);
105 }
106
107 void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) {
108   OS << "// VisualStudio defines setjmp as _setjmp\n"
109         "#if defined(_MSC_VER) && defined(setjmp) && \\\n"
110         "                         !defined(setjmp_undefined_for_msvc)\n"
111         "#  pragma push_macro(\"setjmp\")\n"
112         "#  undef setjmp\n"
113         "#  define setjmp_undefined_for_msvc\n"
114         "#endif\n\n";
115 }
116
117 void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) {
118   OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)\n"
119         "// let's return it to _setjmp state\n"
120         "#  pragma pop_macro(\"setjmp\")\n"
121         "#  undef setjmp_undefined_for_msvc\n"
122         "#endif\n\n";
123 }
124
125 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
126                                     raw_ostream &OS) {
127   OS << "// Enum values for Intrinsics.h\n";
128   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
129   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
130     OS << "    " << Ints[i].EnumName;
131     OS << ((i != e-1) ? ", " : "  ");
132     if (Ints[i].EnumName.size() < 40)
133       OS << std::string(40-Ints[i].EnumName.size(), ' ');
134     OS << " // " << Ints[i].Name << "\n";
135   }
136   OS << "#endif\n\n";
137 }
138
139 void IntrinsicEmitter::
140 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
141                      raw_ostream &OS) {
142   // Build a 'first character of function name' -> intrinsic # mapping.
143   std::map<char, std::vector<unsigned> > IntMapping;
144   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
145     IntMapping[Ints[i].Name[5]].push_back(i);
146
147   OS << "// Function name -> enum value recognizer code.\n";
148   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
149   OS << "  StringRef NameR(Name+6, Len-6);   // Skip over 'llvm.'\n";
150   OS << "  switch (Name[5]) {                  // Dispatch on first letter.\n";
151   OS << "  default: break;\n";
152   // Emit the intrinsic matching stuff by first letter.
153   for (std::map<char, std::vector<unsigned> >::iterator I = IntMapping.begin(),
154        E = IntMapping.end(); I != E; ++I) {
155     OS << "  case '" << I->first << "':\n";
156     std::vector<unsigned> &IntList = I->second;
157
158     // Sort in reverse order of intrinsic name so "abc.def" appears after
159     // "abd.def.ghi" in the overridden name matcher
160     std::sort(IntList.begin(), IntList.end(), [&](unsigned i, unsigned j) {
161       return Ints[i].Name > Ints[j].Name;
162     });
163
164     // Emit all the overloaded intrinsics first, build a table of the
165     // non-overloaded ones.
166     std::vector<StringMatcher::StringPair> MatchTable;
167
168     for (unsigned i = 0, e = IntList.size(); i != e; ++i) {
169       unsigned IntNo = IntList[i];
170       std::string Result = "return " + TargetPrefix + "Intrinsic::" +
171         Ints[IntNo].EnumName + ";";
172
173       if (!Ints[IntNo].isOverloaded) {
174         MatchTable.push_back(std::make_pair(Ints[IntNo].Name.substr(6),Result));
175         continue;
176       }
177
178       // For overloaded intrinsics, only the prefix needs to match
179       std::string TheStr = Ints[IntNo].Name.substr(6);
180       TheStr += '.';  // Require "bswap." instead of bswap.
181       OS << "    if (NameR.startswith(\"" << TheStr << "\")) "
182          << Result << '\n';
183     }
184
185     // Emit the matcher logic for the fixed length strings.
186     StringMatcher("NameR", MatchTable, OS).Emit(1);
187     OS << "    break;  // end of '" << I->first << "' case.\n";
188   }
189
190   OS << "  }\n";
191   OS << "#endif\n\n";
192 }
193
194 void IntrinsicEmitter::
195 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
196                          raw_ostream &OS) {
197   OS << "// Intrinsic ID to name table\n";
198   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
199   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
200   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
201     OS << "  \"" << Ints[i].Name << "\",\n";
202   OS << "#endif\n\n";
203 }
204
205 void IntrinsicEmitter::
206 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,
207                          raw_ostream &OS) {
208   OS << "// Intrinsic ID to overload bitset\n";
209   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
210   OS << "static const uint8_t OTable[] = {\n";
211   OS << "  0";
212   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
213     // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
214     if ((i+1)%8 == 0)
215       OS << ",\n  0";
216     if (Ints[i].isOverloaded)
217       OS << " | (1<<" << (i+1)%8 << ')';
218   }
219   OS << "\n};\n\n";
220   // OTable contains a true bit at the position if the intrinsic is overloaded.
221   OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
222   OS << "#endif\n\n";
223 }
224
225
226 // NOTE: This must be kept in synch with the copy in lib/VMCore/Function.cpp!
227 enum IIT_Info {
228   // Common values should be encoded with 0-16.
229   IIT_Done = 0,
230   IIT_I1   = 1,
231   IIT_I8   = 2,
232   IIT_I16  = 3,
233   IIT_I32  = 4,
234   IIT_I64  = 5,
235   IIT_F16  = 6,
236   IIT_F32  = 7,
237   IIT_F64  = 8,
238   IIT_V2   = 9,
239   IIT_V4   = 10,
240   IIT_V8   = 11,
241   IIT_V16  = 12,
242   IIT_V32  = 13,
243   IIT_V64  = 14,
244   IIT_PTR  = 15,
245   IIT_ARG  = 16,
246
247   // Values from 17+ are only encodable with the inefficient encoding.
248   IIT_MMX  = 17,
249   IIT_METADATA = 18,
250   IIT_EMPTYSTRUCT = 19,
251   IIT_STRUCT2 = 20,
252   IIT_STRUCT3 = 21,
253   IIT_STRUCT4 = 22,
254   IIT_STRUCT5 = 23,
255   IIT_EXTEND_ARG = 24,
256   IIT_TRUNC_ARG = 25,
257   IIT_ANYPTR = 26,
258   IIT_V1   = 27,
259   IIT_VARARG = 28,
260   IIT_HALF_VEC_ARG = 29
261 };
262
263
264 static void EncodeFixedValueType(MVT::SimpleValueType VT,
265                                  std::vector<unsigned char> &Sig) {
266   if (MVT(VT).isInteger()) {
267     unsigned BitWidth = MVT(VT).getSizeInBits();
268     switch (BitWidth) {
269     default: PrintFatalError("unhandled integer type width in intrinsic!");
270     case 1: return Sig.push_back(IIT_I1);
271     case 8: return Sig.push_back(IIT_I8);
272     case 16: return Sig.push_back(IIT_I16);
273     case 32: return Sig.push_back(IIT_I32);
274     case 64: return Sig.push_back(IIT_I64);
275     }
276   }
277
278   switch (VT) {
279   default: PrintFatalError("unhandled MVT in intrinsic!");
280   case MVT::f16: return Sig.push_back(IIT_F16);
281   case MVT::f32: return Sig.push_back(IIT_F32);
282   case MVT::f64: return Sig.push_back(IIT_F64);
283   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
284   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
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   }
290 }
291
292 #ifdef _MSC_VER
293 #pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function.
294 #endif
295
296 static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
297                             std::vector<unsigned char> &Sig) {
298
299   if (R->isSubClassOf("LLVMMatchType")) {
300     unsigned Number = 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
309       Sig.push_back(IIT_ARG);
310     return Sig.push_back((Number << 2) | ArgCodes[Number]);
311   }
312
313   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
314
315   unsigned Tmp = 0;
316   switch (VT) {
317   default: break;
318   case MVT::iPTRAny: ++Tmp; // FALL THROUGH.
319   case MVT::vAny: ++Tmp; // FALL THROUGH.
320   case MVT::fAny: ++Tmp; // FALL THROUGH.
321   case MVT::iAny: {
322     // If this is an "any" valuetype, then the type is the type of the next
323     // type in the list specified to getIntrinsic().
324     Sig.push_back(IIT_ARG);
325
326     // Figure out what arg # this is consuming, and remember what kind it was.
327     unsigned ArgNo = ArgCodes.size();
328     ArgCodes.push_back(Tmp);
329
330     // Encode what sort of argument it must be in the low 2 bits of the ArgNo.
331     return Sig.push_back((ArgNo << 2) | Tmp);
332   }
333
334   case MVT::iPTR: {
335     unsigned AddrSpace = 0;
336     if (R->isSubClassOf("LLVMQualPointerType")) {
337       AddrSpace = R->getValueAsInt("AddrSpace");
338       assert(AddrSpace < 256 && "Address space exceeds 255");
339     }
340     if (AddrSpace) {
341       Sig.push_back(IIT_ANYPTR);
342       Sig.push_back(AddrSpace);
343     } else {
344       Sig.push_back(IIT_PTR);
345     }
346     return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, Sig);
347   }
348   }
349
350   if (MVT(VT).isVector()) {
351     MVT VVT = VT;
352     switch (VVT.getVectorNumElements()) {
353     default: PrintFatalError("unhandled vector type width in intrinsic!");
354     case 1: Sig.push_back(IIT_V1); break;
355     case 2: Sig.push_back(IIT_V2); break;
356     case 4: Sig.push_back(IIT_V4); break;
357     case 8: Sig.push_back(IIT_V8); break;
358     case 16: Sig.push_back(IIT_V16); break;
359     case 32: Sig.push_back(IIT_V32); break;
360     case 64: Sig.push_back(IIT_V64); break;
361     }
362
363     return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
364   }
365
366   EncodeFixedValueType(VT, Sig);
367 }
368
369 #ifdef _MSC_VER
370 #pragma optimize("",on)
371 #endif
372
373 /// ComputeFixedEncoding - If we can encode the type signature for this
374 /// intrinsic into 32 bits, return it.  If not, return ~0U.
375 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
376                                  std::vector<unsigned char> &TypeSig) {
377   std::vector<unsigned char> ArgCodes;
378
379   if (Int.IS.RetVTs.empty())
380     TypeSig.push_back(IIT_Done);
381   else if (Int.IS.RetVTs.size() == 1 &&
382            Int.IS.RetVTs[0] == MVT::isVoid)
383     TypeSig.push_back(IIT_Done);
384   else {
385     switch (Int.IS.RetVTs.size()) {
386       case 1: break;
387       case 2: TypeSig.push_back(IIT_STRUCT2); break;
388       case 3: TypeSig.push_back(IIT_STRUCT3); break;
389       case 4: TypeSig.push_back(IIT_STRUCT4); break;
390       case 5: TypeSig.push_back(IIT_STRUCT5); break;
391       default: llvm_unreachable("Unhandled case in struct");
392     }
393
394     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
395       EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, TypeSig);
396   }
397
398   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
399     EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, TypeSig);
400 }
401
402 static void printIITEntry(raw_ostream &OS, unsigned char X) {
403   OS << (unsigned)X;
404 }
405
406 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
407                                      raw_ostream &OS) {
408   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
409   // capture it in this vector, otherwise store a ~0U.
410   std::vector<unsigned> FixedEncodings;
411
412   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
413
414   std::vector<unsigned char> TypeSig;
415
416   // Compute the unique argument type info.
417   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
418     // Get the signature for the intrinsic.
419     TypeSig.clear();
420     ComputeFixedEncoding(Ints[i], TypeSig);
421
422     // Check to see if we can encode it into a 32-bit word.  We can only encode
423     // 8 nibbles into a 32-bit word.
424     if (TypeSig.size() <= 8) {
425       bool Failed = false;
426       unsigned Result = 0;
427       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
428         // If we had an unencodable argument, bail out.
429         if (TypeSig[i] > 15) {
430           Failed = true;
431           break;
432         }
433         Result = (Result << 4) | TypeSig[e-i-1];
434       }
435
436       // If this could be encoded into a 31-bit word, return it.
437       if (!Failed && (Result >> 31) == 0) {
438         FixedEncodings.push_back(Result);
439         continue;
440       }
441     }
442
443     // Otherwise, we're going to unique the sequence into the
444     // LongEncodingTable, and use its offset in the 32-bit table instead.
445     LongEncodingTable.add(TypeSig);
446
447     // This is a placehold that we'll replace after the table is laid out.
448     FixedEncodings.push_back(~0U);
449   }
450
451   LongEncodingTable.layout();
452
453   OS << "// Global intrinsic function declaration type table.\n";
454   OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
455
456   OS << "static const unsigned IIT_Table[] = {\n  ";
457
458   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
459     if ((i & 7) == 7)
460       OS << "\n  ";
461
462     // If the entry fit in the table, just emit it.
463     if (FixedEncodings[i] != ~0U) {
464       OS << "0x" << utohexstr(FixedEncodings[i]) << ", ";
465       continue;
466     }
467
468     TypeSig.clear();
469     ComputeFixedEncoding(Ints[i], TypeSig);
470
471
472     // Otherwise, emit the offset into the long encoding table.  We emit it this
473     // way so that it is easier to read the offset in the .def file.
474     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
475   }
476
477   OS << "0\n};\n\n";
478
479   // Emit the shared table of register lists.
480   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
481   if (!LongEncodingTable.empty())
482     LongEncodingTable.emit(OS, printIITEntry);
483   OS << "  255\n};\n\n";
484
485   OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
486 }
487
488 namespace {
489 enum ModRefKind {
490   MRK_none,
491   MRK_readonly,
492   MRK_readnone
493 };
494 }
495
496 static ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
497   switch (intrinsic.ModRef) {
498   case CodeGenIntrinsic::NoMem:
499     return MRK_readnone;
500   case CodeGenIntrinsic::ReadArgMem:
501   case CodeGenIntrinsic::ReadMem:
502     return MRK_readonly;
503   case CodeGenIntrinsic::ReadWriteArgMem:
504   case CodeGenIntrinsic::ReadWriteMem:
505     return MRK_none;
506   }
507   llvm_unreachable("bad mod-ref kind");
508 }
509
510 namespace {
511 struct AttributeComparator {
512   bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
513     // Sort throwing intrinsics after non-throwing intrinsics.
514     if (L->canThrow != R->canThrow)
515       return R->canThrow;
516
517     if (L->isNoDuplicate != R->isNoDuplicate)
518       return R->isNoDuplicate;
519
520     if (L->isNoReturn != R->isNoReturn)
521       return R->isNoReturn;
522
523     // Try to order by readonly/readnone attribute.
524     ModRefKind LK = getModRefKind(*L);
525     ModRefKind RK = getModRefKind(*R);
526     if (LK != RK) return (LK > RK);
527
528     // Order by argument attributes.
529     // This is reliable because each side is already sorted internally.
530     return (L->ArgumentAttributes < R->ArgumentAttributes);
531   }
532 };
533 } // End anonymous namespace
534
535 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
536 void IntrinsicEmitter::
537 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
538   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
539   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
540   if (TargetOnly)
541     OS << "static AttributeSet getAttributes(LLVMContext &C, " << TargetPrefix
542        << "Intrinsic::ID id) {\n";
543   else
544     OS << "AttributeSet Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
545
546   // Compute the maximum number of attribute arguments and the map
547   typedef std::map<const CodeGenIntrinsic*, unsigned,
548                    AttributeComparator> UniqAttrMapTy;
549   UniqAttrMapTy UniqAttributes;
550   unsigned maxArgAttrs = 0;
551   unsigned AttrNum = 0;
552   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
553     const CodeGenIntrinsic &intrinsic = Ints[i];
554     maxArgAttrs =
555       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
556     unsigned &N = UniqAttributes[&intrinsic];
557     if (N) continue;
558     assert(AttrNum < 256 && "Too many unique attributes for table!");
559     N = ++AttrNum;
560   }
561
562   // Emit an array of AttributeSet.  Most intrinsics will have at least one
563   // entry, for the function itself (index ~1), which is usually nounwind.
564   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
565
566   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
567     const CodeGenIntrinsic &intrinsic = Ints[i];
568
569     OS << "    " << UniqAttributes[&intrinsic] << ", // "
570        << intrinsic.Name << "\n";
571   }
572   OS << "  };\n\n";
573
574   OS << "  AttributeSet AS[" << maxArgAttrs+1 << "];\n";
575   OS << "  unsigned NumAttrs = 0;\n";
576   OS << "  if (id != 0) {\n";
577   OS << "    switch(IntrinsicsToAttributesMap[id - ";
578   if (TargetOnly)
579     OS << "Intrinsic::num_intrinsics";
580   else
581     OS << "1";
582   OS << "]) {\n";
583   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
584   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
585        E = UniqAttributes.end(); I != E; ++I) {
586     OS << "    case " << I->second << ": {\n";
587
588     const CodeGenIntrinsic &intrinsic = *(I->first);
589
590     // Keep track of the number of attributes we're writing out.
591     unsigned numAttrs = 0;
592
593     // The argument attributes are alreadys sorted by argument index.
594     unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size();
595     if (ae) {
596       while (ai != ae) {
597         unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
598
599         OS <<  "      const Attribute::AttrKind AttrParam" << argNo + 1 <<"[]= {";
600         bool addComma = false;
601
602         do {
603           switch (intrinsic.ArgumentAttributes[ai].second) {
604           case CodeGenIntrinsic::NoCapture:
605             if (addComma)
606               OS << ",";
607             OS << "Attribute::NoCapture";
608             addComma = true;
609             break;
610           case CodeGenIntrinsic::ReadOnly:
611             if (addComma)
612               OS << ",";
613             OS << "Attribute::ReadOnly";
614             addComma = true;
615             break;
616           case CodeGenIntrinsic::ReadNone:
617             if (addComma)
618               OS << ",";
619             OS << "Attributes::ReadNone";
620             addComma = true;
621             break;
622           }
623
624           ++ai;
625         } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
626         OS << "};\n";
627         OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
628            << argNo+1 << ", AttrParam" << argNo +1 << ");\n";
629       }
630     }
631
632     ModRefKind modRef = getModRefKind(intrinsic);
633
634     if (!intrinsic.canThrow || modRef || intrinsic.isNoReturn ||
635         intrinsic.isNoDuplicate) {
636       OS << "      const Attribute::AttrKind Atts[] = {";
637       bool addComma = false;
638       if (!intrinsic.canThrow) {
639         OS << "Attribute::NoUnwind";
640         addComma = true;
641       }
642       if (intrinsic.isNoReturn) {
643         if (addComma)
644           OS << ",";
645         OS << "Attribute::NoReturn";
646         addComma = true;
647       }
648       if (intrinsic.isNoDuplicate) {
649         if (addComma)
650           OS << ",";
651         OS << "Attribute::NoDuplicate";
652         addComma = true;
653       }
654
655       switch (modRef) {
656       case MRK_none: break;
657       case MRK_readonly:
658         if (addComma)
659           OS << ",";
660         OS << "Attribute::ReadOnly";
661         break;
662       case MRK_readnone:
663         if (addComma)
664           OS << ",";
665         OS << "Attribute::ReadNone";
666         break;
667       }
668       OS << "};\n";
669       OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
670          << "AttributeSet::FunctionIndex, Atts);\n";
671     }
672
673     if (numAttrs) {
674       OS << "      NumAttrs = " << numAttrs << ";\n";
675       OS << "      break;\n";
676       OS << "      }\n";
677     } else {
678       OS << "      return AttributeSet();\n";
679       OS << "      }\n";
680     }
681   }
682
683   OS << "    }\n";
684   OS << "  }\n";
685   OS << "  return AttributeSet::get(C, makeArrayRef(AS, NumAttrs));\n";
686   OS << "}\n";
687   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
688 }
689
690 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
691 void IntrinsicEmitter::
692 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
693   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
694      << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
695      << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && "
696      << "\"Unknown intrinsic.\");\n\n";
697
698   OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n"
699      << "  /* invalid */ UnknownModRefBehavior,\n";
700   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
701     OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
702     switch (Ints[i].ModRef) {
703     case CodeGenIntrinsic::NoMem:
704       OS << "DoesNotAccessMemory,\n";
705       break;
706     case CodeGenIntrinsic::ReadArgMem:
707       OS << "OnlyReadsArgumentPointees,\n";
708       break;
709     case CodeGenIntrinsic::ReadMem:
710       OS << "OnlyReadsMemory,\n";
711       break;
712     case CodeGenIntrinsic::ReadWriteArgMem:
713       OS << "OnlyAccessesArgumentPointees,\n";
714       break;
715     case CodeGenIntrinsic::ReadWriteMem:
716       OS << "UnknownModRefBehavior,\n";
717       break;
718     }
719   }
720   OS << "};\n\n"
721      << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n"
722      << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
723 }
724
725 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
726 /// same target, and we already checked it.
727 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
728                                const std::string &TargetPrefix,
729                                raw_ostream &OS) {
730
731   std::vector<StringMatcher::StringPair> Results;
732
733   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
734        E = BIM.end(); I != E; ++I) {
735     std::string ResultCode =
736     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
737     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
738   }
739
740   StringMatcher("BuiltinName", Results, OS).Emit();
741 }
742
743
744 void IntrinsicEmitter::
745 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
746                              raw_ostream &OS) {
747   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
748   BIMTy BuiltinMap;
749   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
750     if (!Ints[i].GCCBuiltinName.empty()) {
751       // Get the map for this target prefix.
752       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
753
754       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
755                                      Ints[i].EnumName)).second)
756         PrintFatalError("Intrinsic '" + Ints[i].TheDef->getName() +
757               "': duplicate GCC builtin name!");
758     }
759   }
760
761   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
762   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
763   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
764   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
765   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
766
767   if (TargetOnly) {
768     OS << "static " << TargetPrefix << "Intrinsic::ID "
769        << "getIntrinsicForGCCBuiltin(const char "
770        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
771   } else {
772     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
773        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
774   }
775
776   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
777   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
778
779   // Note: this could emit significantly better code if we cared.
780   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
781     OS << "  ";
782     if (!I->first.empty())
783       OS << "if (TargetPrefix == \"" << I->first << "\") ";
784     else
785       OS << "/* Target Independent Builtins */ ";
786     OS << "{\n";
787
788     // Emit the comparisons for this target prefix.
789     EmitTargetBuiltins(I->second, TargetPrefix, OS);
790     OS << "  }\n";
791   }
792   OS << "  return ";
793   if (!TargetPrefix.empty())
794     OS << "(" << TargetPrefix << "Intrinsic::ID)";
795   OS << "Intrinsic::not_intrinsic;\n";
796   OS << "}\n";
797   OS << "#endif\n\n";
798 }
799
800 void IntrinsicEmitter::
801 EmitIntrinsicToMSBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
802                             raw_ostream &OS) {
803   std::map<std::string, std::map<std::string, std::string>> TargetBuiltins;
804
805   for (const auto &Intrinsic : Ints) {
806     if (Intrinsic.MSBuiltinName.empty())
807       continue;
808
809     auto &Builtins = TargetBuiltins[Intrinsic.TargetPrefix];
810     if (!Builtins.insert(std::make_pair(Intrinsic.MSBuiltinName,
811                                         Intrinsic.EnumName)).second)
812       PrintFatalError("Intrinsic '" + Intrinsic.TheDef->getName() + "': "
813                       "duplicate MS builtin name!");
814   }
815
816   OS << "// Get the LLVM intrinsic that corresponds to a MS builtin.\n"
817         "// This is used by the C front-end.  The MS builtin name is passed\n"
818         "// in as a BuiltinName, and a target prefix (e.g. 'arm') is passed\n"
819         "// in as a TargetPrefix.  The result is assigned to 'IntrinsicID'.\n"
820         "#ifdef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN\n";
821
822   OS << (TargetOnly ? "static " + TargetPrefix : "") << "Intrinsic::ID "
823      << (TargetOnly ? "" : "Intrinsic::")
824      << "getIntrinsicForMSBuiltin(const char *TP, const char *BN) {\n";
825   OS << "  StringRef BuiltinName(BN);\n"
826         "  StringRef TargetPrefix(TP);\n"
827         "\n";
828
829   for (const auto &Builtins : TargetBuiltins) {
830     OS << "  ";
831     if (Builtins.first.empty())
832       OS << "/* Target Independent Builtins */ ";
833     else
834       OS << "if (TargetPrefix == \"" << Builtins.first << "\") ";
835     OS << "{\n";
836     EmitTargetBuiltins(Builtins.second, TargetPrefix, OS);
837     OS << "}";
838   }
839
840   OS << "  return ";
841   if (!TargetPrefix.empty())
842     OS << "(" << TargetPrefix << "Intrinsic::ID)";
843   OS << "Intrinsic::not_intrinsic;\n";
844   OS << "}\n";
845
846   OS << "#endif\n\n";
847 }
848
849 void llvm::EmitIntrinsics(RecordKeeper &RK, raw_ostream &OS, bool TargetOnly) {
850   IntrinsicEmitter(RK, TargetOnly).run(OS);
851 }