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