Emit the "is an intrinsic overloaded" table as a bitfield.
[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 "CodeGenTarget.h"
15 #include "IntrinsicEmitter.h"
16 #include "StringMatcher.h"
17 #include "llvm/TableGen/Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include <algorithm>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // IntrinsicEmitter Implementation
24 //===----------------------------------------------------------------------===//
25
26 void IntrinsicEmitter::run(raw_ostream &OS) {
27   EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
28   
29   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records, TargetOnly);
30   
31   if (TargetOnly && !Ints.empty())
32     TargetPrefix = Ints[0].TargetPrefix;
33
34   EmitPrefix(OS);
35
36   // Emit the enum information.
37   EmitEnumInfo(Ints, OS);
38
39   // Emit the intrinsic ID -> name table.
40   EmitIntrinsicToNameTable(Ints, OS);
41
42   // Emit the intrinsic ID -> overload table.
43   EmitIntrinsicToOverloadTable(Ints, OS);
44
45   // Emit the function name recognizer.
46   EmitFnNameRecognizer(Ints, OS);
47   
48   // Emit the intrinsic verifier.
49   EmitVerifier(Ints, OS);
50   
51   // Emit the intrinsic declaration generator.
52   EmitGenerator(Ints, OS);
53   
54   // Emit the intrinsic parameter attributes.
55   EmitAttributes(Ints, OS);
56
57   // Emit intrinsic alias analysis mod/ref behavior.
58   EmitModRefBehavior(Ints, OS);
59
60   // Emit a list of intrinsics with corresponding GCC builtins.
61   EmitGCCBuiltinList(Ints, OS);
62
63   // Emit code to translate GCC builtins into LLVM intrinsics.
64   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
65
66   EmitSuffix(OS);
67 }
68
69 void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) {
70   OS << "// VisualStudio defines setjmp as _setjmp\n"
71         "#if defined(_MSC_VER) && defined(setjmp) && \\\n"
72         "                         !defined(setjmp_undefined_for_msvc)\n"
73         "#  pragma push_macro(\"setjmp\")\n"
74         "#  undef setjmp\n"
75         "#  define setjmp_undefined_for_msvc\n"
76         "#endif\n\n";
77 }
78
79 void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) {
80   OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)\n"
81         "// let's return it to _setjmp state\n"
82         "#  pragma pop_macro(\"setjmp\")\n"
83         "#  undef setjmp_undefined_for_msvc\n"
84         "#endif\n\n";
85 }
86
87 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
88                                     raw_ostream &OS) {
89   OS << "// Enum values for Intrinsics.h\n";
90   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
91   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
92     OS << "    " << Ints[i].EnumName;
93     OS << ((i != e-1) ? ", " : "  ");
94     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
95       << "// " << Ints[i].Name << "\n";
96   }
97   OS << "#endif\n\n";
98 }
99
100 void IntrinsicEmitter::
101 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
102                      raw_ostream &OS) {
103   // Build a 'first character of function name' -> intrinsic # mapping.
104   std::map<char, std::vector<unsigned> > IntMapping;
105   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
106     IntMapping[Ints[i].Name[5]].push_back(i);
107   
108   OS << "// Function name -> enum value recognizer code.\n";
109   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
110   OS << "  StringRef NameR(Name+6, Len-6);   // Skip over 'llvm.'\n";
111   OS << "  switch (Name[5]) {                  // Dispatch on first letter.\n";
112   OS << "  default: break;\n";
113   // Emit the intrinsic matching stuff by first letter.
114   for (std::map<char, std::vector<unsigned> >::iterator I = IntMapping.begin(),
115        E = IntMapping.end(); I != E; ++I) {
116     OS << "  case '" << I->first << "':\n";
117     std::vector<unsigned> &IntList = I->second;
118
119     // Emit all the overloaded intrinsics first, build a table of the
120     // non-overloaded ones.
121     std::vector<StringMatcher::StringPair> MatchTable;
122     
123     for (unsigned i = 0, e = IntList.size(); i != e; ++i) {
124       unsigned IntNo = IntList[i];
125       std::string Result = "return " + TargetPrefix + "Intrinsic::" +
126         Ints[IntNo].EnumName + ";";
127
128       if (!Ints[IntNo].isOverloaded) {
129         MatchTable.push_back(std::make_pair(Ints[IntNo].Name.substr(6),Result));
130         continue;
131       }
132
133       // For overloaded intrinsics, only the prefix needs to match
134       std::string TheStr = Ints[IntNo].Name.substr(6);
135       TheStr += '.';  // Require "bswap." instead of bswap.
136       OS << "    if (NameR.startswith(\"" << TheStr << "\")) "
137          << Result << '\n';
138     }
139     
140     // Emit the matcher logic for the fixed length strings.
141     StringMatcher("NameR", MatchTable, OS).Emit(1);
142     OS << "    break;  // end of '" << I->first << "' case.\n";
143   }
144   
145   OS << "  }\n";
146   OS << "#endif\n\n";
147 }
148
149 void IntrinsicEmitter::
150 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, 
151                          raw_ostream &OS) {
152   OS << "// Intrinsic ID to name table\n";
153   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
154   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
155   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
156     OS << "  \"" << Ints[i].Name << "\",\n";
157   OS << "#endif\n\n";
158 }
159
160 void IntrinsicEmitter::
161 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints, 
162                          raw_ostream &OS) {
163   OS << "// Intrinsic ID to overload bitset\n";
164   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
165   OS << "static const uint8_t OTable[] = {\n";
166   OS << "  0";
167   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
168     // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
169     if ((i+1)%8 == 0)
170       OS << ",\n  0";
171     if (Ints[i].isOverloaded)
172       OS << " | (1<<" << (i+1)%8 << ')';
173   }
174   OS << "\n};\n\n";
175   // OTable contains a true bit at the position if the intrinsic is overloaded.
176   OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
177   OS << "#endif\n\n";
178 }
179
180 static void EmitTypeForValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
181   if (EVT(VT).isInteger()) {
182     unsigned BitWidth = EVT(VT).getSizeInBits();
183     OS << "IntegerType::get(Context, " << BitWidth << ")";
184   } else if (VT == MVT::Other) {
185     // MVT::OtherVT is used to mean the empty struct type here.
186     OS << "StructType::get(Context)";
187   } else if (VT == MVT::f16) {
188     OS << "Type::getHalfTy(Context)";
189   } else if (VT == MVT::f32) {
190     OS << "Type::getFloatTy(Context)";
191   } else if (VT == MVT::f64) {
192     OS << "Type::getDoubleTy(Context)";
193   } else if (VT == MVT::f80) {
194     OS << "Type::getX86_FP80Ty(Context)";
195   } else if (VT == MVT::f128) {
196     OS << "Type::getFP128Ty(Context)";
197   } else if (VT == MVT::ppcf128) {
198     OS << "Type::getPPC_FP128Ty(Context)";
199   } else if (VT == MVT::isVoid) {
200     OS << "Type::getVoidTy(Context)";
201   } else if (VT == MVT::Metadata) {
202     OS << "Type::getMetadataTy(Context)";
203   } else if (VT == MVT::x86mmx) {
204     OS << "Type::getX86_MMXTy(Context)";
205   } else {
206     assert(false && "Unsupported ValueType!");
207   }
208 }
209
210 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
211                              unsigned &ArgNo);
212
213 static void EmitTypeGenerate(raw_ostream &OS,
214                              const std::vector<Record*> &ArgTypes,
215                              unsigned &ArgNo) {
216   if (ArgTypes.empty())
217     return EmitTypeForValueType(OS, MVT::isVoid);
218   
219   if (ArgTypes.size() == 1)
220     return EmitTypeGenerate(OS, ArgTypes.front(), ArgNo);
221
222   OS << "StructType::get(";
223
224   for (std::vector<Record*>::const_iterator
225          I = ArgTypes.begin(), E = ArgTypes.end(); I != E; ++I) {
226     EmitTypeGenerate(OS, *I, ArgNo);
227     OS << ", ";
228   }
229
230   OS << " NULL)";
231 }
232
233 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
234                              unsigned &ArgNo) {
235   MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
236
237   if (ArgType->isSubClassOf("LLVMMatchType")) {
238     unsigned Number = ArgType->getValueAsInt("Number");
239     assert(Number < ArgNo && "Invalid matching number!");
240     if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
241       OS << "VectorType::getExtendedElementVectorType"
242          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
243     else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
244       OS << "VectorType::getTruncatedElementVectorType"
245          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
246     else
247       OS << "Tys[" << Number << "]";
248   } else if (VT == MVT::iAny || VT == MVT::fAny || VT == MVT::vAny) {
249     // NOTE: The ArgNo variable here is not the absolute argument number, it is
250     // the index of the "arbitrary" type in the Tys array passed to the
251     // Intrinsic::getDeclaration function. Consequently, we only want to
252     // increment it when we actually hit an overloaded type. Getting this wrong
253     // leads to very subtle bugs!
254     OS << "Tys[" << ArgNo++ << "]";
255   } else if (EVT(VT).isVector()) {
256     EVT VVT = VT;
257     OS << "VectorType::get(";
258     EmitTypeForValueType(OS, VVT.getVectorElementType().getSimpleVT().SimpleTy);
259     OS << ", " << VVT.getVectorNumElements() << ")";
260   } else if (VT == MVT::iPTR) {
261     OS << "PointerType::getUnqual(";
262     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
263     OS << ")";
264   } else if (VT == MVT::iPTRAny) {
265     // Make sure the user has passed us an argument type to overload. If not,
266     // treat it as an ordinary (not overloaded) intrinsic.
267     OS << "(" << ArgNo << " < Tys.size()) ? Tys[" << ArgNo
268     << "] : PointerType::getUnqual(";
269     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
270     OS << ")";
271     ++ArgNo;
272   } else if (VT == MVT::isVoid) {
273     if (ArgNo == 0)
274       OS << "Type::getVoidTy(Context)";
275     else
276       // MVT::isVoid is used to mean varargs here.
277       OS << "...";
278   } else {
279     EmitTypeForValueType(OS, VT);
280   }
281 }
282
283 /// RecordListComparator - Provide a deterministic comparator for lists of
284 /// records.
285 namespace {
286   typedef std::pair<std::vector<Record*>, std::vector<Record*> > RecPair;
287   struct RecordListComparator {
288     bool operator()(const RecPair &LHS,
289                     const RecPair &RHS) const {
290       unsigned i = 0;
291       const std::vector<Record*> *LHSVec = &LHS.first;
292       const std::vector<Record*> *RHSVec = &RHS.first;
293       unsigned RHSSize = RHSVec->size();
294       unsigned LHSSize = LHSVec->size();
295
296       for (; i != LHSSize; ++i) {
297         if (i == RHSSize) return false;  // RHS is shorter than LHS.
298         if ((*LHSVec)[i] != (*RHSVec)[i])
299           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
300       }
301
302       if (i != RHSSize) return true;
303
304       i = 0;
305       LHSVec = &LHS.second;
306       RHSVec = &RHS.second;
307       RHSSize = RHSVec->size();
308       LHSSize = LHSVec->size();
309
310       for (i = 0; i != LHSSize; ++i) {
311         if (i == RHSSize) return false;  // RHS is shorter than LHS.
312         if ((*LHSVec)[i] != (*RHSVec)[i])
313           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
314       }
315
316       return i != RHSSize;
317     }
318   };
319 }
320
321 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
322                                     raw_ostream &OS) {
323   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
324   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
325   OS << "  switch (ID) {\n";
326   OS << "  default: llvm_unreachable(\"Invalid intrinsic!\");\n";
327   
328   // This checking can emit a lot of very common code.  To reduce the amount of
329   // code that we emit, batch up cases that have identical types.  This avoids
330   // problems where GCC can run out of memory compiling Verifier.cpp.
331   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
332   MapTy UniqueArgInfos;
333   
334   // Compute the unique argument type info.
335   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
336     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
337                              Ints[i].IS.ParamTypeDefs)].push_back(i);
338
339   // Loop through the array, emitting one comparison for each batch.
340   for (MapTy::iterator I = UniqueArgInfos.begin(),
341        E = UniqueArgInfos.end(); I != E; ++I) {
342     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
343       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
344          << Ints[I->second[i]].Name << "\n";
345     
346     const RecPair &ArgTypes = I->first;
347     const std::vector<Record*> &RetTys = ArgTypes.first;
348     const std::vector<Record*> &ParamTys = ArgTypes.second;
349     std::vector<unsigned> OverloadedTypeIndices;
350
351     OS << "    VerifyIntrinsicPrototype(ID, IF, " << RetTys.size() << ", "
352        << ParamTys.size();
353
354     // Emit return types.
355     for (unsigned j = 0, je = RetTys.size(); j != je; ++j) {
356       Record *ArgType = RetTys[j];
357       OS << ", ";
358
359       if (ArgType->isSubClassOf("LLVMMatchType")) {
360         unsigned Number = ArgType->getValueAsInt("Number");
361         assert(Number < OverloadedTypeIndices.size() &&
362                "Invalid matching number!");
363         Number = OverloadedTypeIndices[Number];
364         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
365           OS << "~(ExtendedElementVectorType | " << Number << ")";
366         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
367           OS << "~(TruncatedElementVectorType | " << Number << ")";
368         else
369           OS << "~" << Number;
370       } else {
371         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
372         OS << getEnumName(VT);
373
374         if (EVT(VT).isOverloaded())
375           OverloadedTypeIndices.push_back(j);
376
377         if (VT == MVT::isVoid && j != 0 && j != je - 1)
378           throw "Var arg type not last argument";
379       }
380     }
381
382     // Emit the parameter types.
383     for (unsigned j = 0, je = ParamTys.size(); j != je; ++j) {
384       Record *ArgType = ParamTys[j];
385       OS << ", ";
386
387       if (ArgType->isSubClassOf("LLVMMatchType")) {
388         unsigned Number = ArgType->getValueAsInt("Number");
389         assert(Number < OverloadedTypeIndices.size() &&
390                "Invalid matching number!");
391         Number = OverloadedTypeIndices[Number];
392         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
393           OS << "~(ExtendedElementVectorType | " << Number << ")";
394         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
395           OS << "~(TruncatedElementVectorType | " << Number << ")";
396         else
397           OS << "~" << Number;
398       } else {
399         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
400         OS << getEnumName(VT);
401
402         if (EVT(VT).isOverloaded())
403           OverloadedTypeIndices.push_back(j + RetTys.size());
404
405         if (VT == MVT::isVoid && j != 0 && j != je - 1)
406           throw "Var arg type not last argument";
407       }
408     }
409       
410     OS << ");\n";
411     OS << "    break;\n";
412   }
413   OS << "  }\n";
414   OS << "#endif\n\n";
415 }
416
417 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, 
418                                      raw_ostream &OS) {
419   OS << "// Code for generating Intrinsic function declarations.\n";
420   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
421   OS << "  switch (id) {\n";
422   OS << "  default: llvm_unreachable(\"Invalid intrinsic!\");\n";
423   
424   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
425   // types.
426   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
427   MapTy UniqueArgInfos;
428   
429   // Compute the unique argument type info.
430   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
431     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
432                              Ints[i].IS.ParamTypeDefs)].push_back(i);
433
434   // Loop through the array, emitting one generator for each batch.
435   std::string IntrinsicStr = TargetPrefix + "Intrinsic::";
436   
437   for (MapTy::iterator I = UniqueArgInfos.begin(),
438        E = UniqueArgInfos.end(); I != E; ++I) {
439     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
440       OS << "  case " << IntrinsicStr << Ints[I->second[i]].EnumName 
441          << ":\t\t// " << Ints[I->second[i]].Name << "\n";
442     
443     const RecPair &ArgTypes = I->first;
444     const std::vector<Record*> &RetTys = ArgTypes.first;
445     const std::vector<Record*> &ParamTys = ArgTypes.second;
446
447     unsigned N = ParamTys.size();
448
449     if (N > 1 &&
450         getValueType(ParamTys[N - 1]->getValueAsDef("VT")) == MVT::isVoid) {
451       OS << "    IsVarArg = true;\n";
452       --N;
453     }
454
455     unsigned ArgNo = 0;
456     OS << "    ResultTy = ";
457     EmitTypeGenerate(OS, RetTys, ArgNo);
458     OS << ";\n";
459     
460     for (unsigned j = 0; j != N; ++j) {
461       OS << "    ArgTys.push_back(";
462       EmitTypeGenerate(OS, ParamTys[j], ArgNo);
463       OS << ");\n";
464     }
465
466     OS << "    break;\n";
467   }
468
469   OS << "  }\n";
470   OS << "#endif\n\n";
471 }
472
473 namespace {
474   enum ModRefKind {
475     MRK_none,
476     MRK_readonly,
477     MRK_readnone
478   };
479
480   ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
481     switch (intrinsic.ModRef) {
482     case CodeGenIntrinsic::NoMem:
483       return MRK_readnone;
484     case CodeGenIntrinsic::ReadArgMem:
485     case CodeGenIntrinsic::ReadMem:
486       return MRK_readonly;
487     case CodeGenIntrinsic::ReadWriteArgMem:
488     case CodeGenIntrinsic::ReadWriteMem:
489       return MRK_none;
490     }
491     llvm_unreachable("bad mod-ref kind");
492   }
493
494   struct AttributeComparator {
495     bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
496       // Sort throwing intrinsics after non-throwing intrinsics.
497       if (L->canThrow != R->canThrow)
498         return R->canThrow;
499
500       // Try to order by readonly/readnone attribute.
501       ModRefKind LK = getModRefKind(*L);
502       ModRefKind RK = getModRefKind(*R);
503       if (LK != RK) return (LK > RK);
504
505       // Order by argument attributes.
506       // This is reliable because each side is already sorted internally.
507       return (L->ArgumentAttributes < R->ArgumentAttributes);
508     }
509   };
510 }
511
512 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
513 void IntrinsicEmitter::
514 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
515   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
516   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
517   if (TargetOnly)
518     OS << "static AttrListPtr getAttributes(" << TargetPrefix 
519        << "Intrinsic::ID id) {\n";
520   else
521     OS << "AttrListPtr Intrinsic::getAttributes(ID id) {\n";
522
523   // Compute the maximum number of attribute arguments and the map
524   typedef std::map<const CodeGenIntrinsic*, unsigned,
525                    AttributeComparator> UniqAttrMapTy;
526   UniqAttrMapTy UniqAttributes;
527   unsigned maxArgAttrs = 0;
528   unsigned AttrNum = 0;
529   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
530     const CodeGenIntrinsic &intrinsic = Ints[i];
531     maxArgAttrs =
532       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
533     unsigned &N = UniqAttributes[&intrinsic];
534     if (N) continue;
535     assert(AttrNum < 256 && "Too many unique attributes for table!");
536     N = ++AttrNum;
537   }
538
539   // Emit an array of AttributeWithIndex.  Most intrinsics will have
540   // at least one entry, for the function itself (index ~1), which is
541   // usually nounwind.
542   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
543   OS << "    255, // Invalid intrinsic\n";
544
545   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
546     const CodeGenIntrinsic &intrinsic = Ints[i];
547
548     OS << "    " << UniqAttributes[&intrinsic] << ", // "
549        << intrinsic.Name << "\n";
550   }
551   OS << "  };\n\n";
552
553   OS << "  AttributeWithIndex AWI[" << maxArgAttrs+1 << "];\n";
554   OS << "  unsigned NumAttrs = 0;\n";
555   OS << "  switch(IntrinsicsToAttributesMap[id]) {\n";
556   OS << "  default: llvm_unreachable(\"Invalid attribute number\");\n";
557   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
558        E = UniqAttributes.end(); I != E; ++I) {
559     OS << "  case " << I->second << ":\n";
560
561     const CodeGenIntrinsic &intrinsic = *(I->first);
562
563     // Keep track of the number of attributes we're writing out.
564     unsigned numAttrs = 0;
565
566     // The argument attributes are alreadys sorted by argument index.
567     for (unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size(); ai != ae;) {
568       unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
569
570       OS << "    AWI[" << numAttrs++ << "] = AttributeWithIndex::get("
571          << argNo+1 << ", ";
572
573       bool moreThanOne = false;
574
575       do {
576         if (moreThanOne) OS << '|';
577
578         switch (intrinsic.ArgumentAttributes[ai].second) {
579         case CodeGenIntrinsic::NoCapture:
580           OS << "Attribute::NoCapture";
581           break;
582         }
583
584         ++ai;
585         moreThanOne = true;
586       } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
587
588       OS << ");\n";
589     }
590
591     ModRefKind modRef = getModRefKind(intrinsic);
592
593     if (!intrinsic.canThrow || modRef) {
594       OS << "    AWI[" << numAttrs++ << "] = AttributeWithIndex::get(~0, ";
595       if (!intrinsic.canThrow) {
596         OS << "Attribute::NoUnwind";
597         if (modRef) OS << '|';
598       }
599       switch (modRef) {
600       case MRK_none: break;
601       case MRK_readonly: OS << "Attribute::ReadOnly"; break;
602       case MRK_readnone: OS << "Attribute::ReadNone"; break;
603       }
604       OS << ");\n";
605     }
606
607     if (numAttrs) {
608       OS << "    NumAttrs = " << numAttrs << ";\n";
609       OS << "    break;\n";
610     } else {
611       OS << "    return AttrListPtr();\n";
612     }
613   }
614   
615   OS << "  }\n";
616   OS << "  return AttrListPtr::get(AWI, NumAttrs);\n";
617   OS << "}\n";
618   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
619 }
620
621 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
622 void IntrinsicEmitter::
623 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
624   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
625      << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
626      << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && "
627      << "\"Unknown intrinsic.\");\n\n";
628
629   OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n"
630      << "  /* invalid */ UnknownModRefBehavior,\n";
631   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
632     OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
633     switch (Ints[i].ModRef) {
634     case CodeGenIntrinsic::NoMem:
635       OS << "DoesNotAccessMemory,\n";
636       break;
637     case CodeGenIntrinsic::ReadArgMem:
638       OS << "OnlyReadsArgumentPointees,\n";
639       break;
640     case CodeGenIntrinsic::ReadMem:
641       OS << "OnlyReadsMemory,\n";
642       break;
643     case CodeGenIntrinsic::ReadWriteArgMem:
644       OS << "OnlyAccessesArgumentPointees,\n";
645       break;
646     case CodeGenIntrinsic::ReadWriteMem:
647       OS << "UnknownModRefBehavior,\n";
648       break;
649     }
650   }
651   OS << "};\n\n"
652      << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n"
653      << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
654 }
655
656 void IntrinsicEmitter::
657 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
658   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
659   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
660   OS << "  switch (F->getIntrinsicID()) {\n";
661   OS << "  default: BuiltinName = \"\"; break;\n";
662   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
663     if (!Ints[i].GCCBuiltinName.empty()) {
664       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
665          << Ints[i].GCCBuiltinName << "\"; break;\n";
666     }
667   }
668   OS << "  }\n";
669   OS << "#endif\n\n";
670 }
671
672 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
673 /// same target, and we already checked it.
674 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
675                                const std::string &TargetPrefix,
676                                raw_ostream &OS) {
677   
678   std::vector<StringMatcher::StringPair> Results;
679   
680   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
681        E = BIM.end(); I != E; ++I) {
682     std::string ResultCode =
683     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
684     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
685   }
686
687   StringMatcher("BuiltinName", Results, OS).Emit();
688 }
689
690         
691 void IntrinsicEmitter::
692 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
693                              raw_ostream &OS) {
694   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
695   BIMTy BuiltinMap;
696   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
697     if (!Ints[i].GCCBuiltinName.empty()) {
698       // Get the map for this target prefix.
699       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
700       
701       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
702                                      Ints[i].EnumName)).second)
703         throw "Intrinsic '" + Ints[i].TheDef->getName() +
704               "': duplicate GCC builtin name!";
705     }
706   }
707   
708   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
709   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
710   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
711   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
712   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
713   
714   if (TargetOnly) {
715     OS << "static " << TargetPrefix << "Intrinsic::ID "
716        << "getIntrinsicForGCCBuiltin(const char "
717        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
718   } else {
719     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
720        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
721   }
722   
723   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
724   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
725   
726   // Note: this could emit significantly better code if we cared.
727   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
728     OS << "  ";
729     if (!I->first.empty())
730       OS << "if (TargetPrefix == \"" << I->first << "\") ";
731     else
732       OS << "/* Target Independent Builtins */ ";
733     OS << "{\n";
734
735     // Emit the comparisons for this target prefix.
736     EmitTargetBuiltins(I->second, TargetPrefix, OS);
737     OS << "  }\n";
738   }
739   OS << "  return ";
740   if (!TargetPrefix.empty())
741     OS << "(" << TargetPrefix << "Intrinsic::ID)";
742   OS << "Intrinsic::not_intrinsic;\n";
743   OS << "}\n";
744   OS << "#endif\n\n";
745 }