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