I forgot the #ifdef _MSC_VER guard in my last commit.
[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 "llvm/TableGen/Record.h"
17 #include "llvm/TableGen/StringMatcher.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 code to translate GCC builtins into LLVM intrinsics.
61   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
62
63   EmitSuffix(OS);
64 }
65
66 void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) {
67   OS << "// VisualStudio defines setjmp as _setjmp\n"
68         "#if defined(_MSC_VER) && defined(setjmp) && \\\n"
69         "                         !defined(setjmp_undefined_for_msvc)\n"
70         "#  pragma push_macro(\"setjmp\")\n"
71         "#  undef setjmp\n"
72         "#  define setjmp_undefined_for_msvc\n"
73         "#endif\n\n";
74 }
75
76 void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) {
77   OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)\n"
78         "// let's return it to _setjmp state\n"
79         "#  pragma pop_macro(\"setjmp\")\n"
80         "#  undef setjmp_undefined_for_msvc\n"
81         "#endif\n\n";
82 }
83
84 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
85                                     raw_ostream &OS) {
86   OS << "// Enum values for Intrinsics.h\n";
87   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
88   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
89     OS << "    " << Ints[i].EnumName;
90     OS << ((i != e-1) ? ", " : "  ");
91     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
92       << "// " << Ints[i].Name << "\n";
93   }
94   OS << "#endif\n\n";
95 }
96
97 void IntrinsicEmitter::
98 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
99                      raw_ostream &OS) {
100   // Build a 'first character of function name' -> intrinsic # mapping.
101   std::map<char, std::vector<unsigned> > IntMapping;
102   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
103     IntMapping[Ints[i].Name[5]].push_back(i);
104   
105   OS << "// Function name -> enum value recognizer code.\n";
106   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
107   OS << "  StringRef NameR(Name+6, Len-6);   // Skip over 'llvm.'\n";
108   OS << "  switch (Name[5]) {                  // Dispatch on first letter.\n";
109   OS << "  default: break;\n";
110   // Emit the intrinsic matching stuff by first letter.
111   for (std::map<char, std::vector<unsigned> >::iterator I = IntMapping.begin(),
112        E = IntMapping.end(); I != E; ++I) {
113     OS << "  case '" << I->first << "':\n";
114     std::vector<unsigned> &IntList = I->second;
115
116     // Emit all the overloaded intrinsics first, build a table of the
117     // non-overloaded ones.
118     std::vector<StringMatcher::StringPair> MatchTable;
119     
120     for (unsigned i = 0, e = IntList.size(); i != e; ++i) {
121       unsigned IntNo = IntList[i];
122       std::string Result = "return " + TargetPrefix + "Intrinsic::" +
123         Ints[IntNo].EnumName + ";";
124
125       if (!Ints[IntNo].isOverloaded) {
126         MatchTable.push_back(std::make_pair(Ints[IntNo].Name.substr(6),Result));
127         continue;
128       }
129
130       // For overloaded intrinsics, only the prefix needs to match
131       std::string TheStr = Ints[IntNo].Name.substr(6);
132       TheStr += '.';  // Require "bswap." instead of bswap.
133       OS << "    if (NameR.startswith(\"" << TheStr << "\")) "
134          << Result << '\n';
135     }
136     
137     // Emit the matcher logic for the fixed length strings.
138     StringMatcher("NameR", MatchTable, OS).Emit(1);
139     OS << "    break;  // end of '" << I->first << "' case.\n";
140   }
141   
142   OS << "  }\n";
143   OS << "#endif\n\n";
144 }
145
146 void IntrinsicEmitter::
147 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, 
148                          raw_ostream &OS) {
149   OS << "// Intrinsic ID to name table\n";
150   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
151   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
152   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
153     OS << "  \"" << Ints[i].Name << "\",\n";
154   OS << "#endif\n\n";
155 }
156
157 void IntrinsicEmitter::
158 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints, 
159                          raw_ostream &OS) {
160   OS << "// Intrinsic ID to overload bitset\n";
161   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
162   OS << "static const uint8_t OTable[] = {\n";
163   OS << "  0";
164   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
165     // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
166     if ((i+1)%8 == 0)
167       OS << ",\n  0";
168     if (Ints[i].isOverloaded)
169       OS << " | (1<<" << (i+1)%8 << ')';
170   }
171   OS << "\n};\n\n";
172   // OTable contains a true bit at the position if the intrinsic is overloaded.
173   OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
174   OS << "#endif\n\n";
175 }
176
177 /// RecordListComparator - Provide a deterministic comparator for lists of
178 /// records.
179 namespace {
180   typedef std::pair<std::vector<Record*>, std::vector<Record*> > RecPair;
181   struct RecordListComparator {
182     bool operator()(const RecPair &LHS,
183                     const RecPair &RHS) const {
184       unsigned i = 0;
185       const std::vector<Record*> *LHSVec = &LHS.first;
186       const std::vector<Record*> *RHSVec = &RHS.first;
187       unsigned RHSSize = RHSVec->size();
188       unsigned LHSSize = LHSVec->size();
189
190       for (; i != LHSSize; ++i) {
191         if (i == RHSSize) return false;  // RHS is shorter than LHS.
192         if ((*LHSVec)[i] != (*RHSVec)[i])
193           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
194       }
195
196       if (i != RHSSize) return true;
197
198       i = 0;
199       LHSVec = &LHS.second;
200       RHSVec = &RHS.second;
201       RHSSize = RHSVec->size();
202       LHSSize = LHSVec->size();
203
204       for (i = 0; i != LHSSize; ++i) {
205         if (i == RHSSize) return false;  // RHS is shorter than LHS.
206         if ((*LHSVec)[i] != (*RHSVec)[i])
207           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
208       }
209
210       return i != RHSSize;
211     }
212   };
213 }
214
215 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
216                                     raw_ostream &OS) {
217   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
218   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
219   OS << "  switch (ID) {\n";
220   OS << "  default: llvm_unreachable(\"Invalid intrinsic!\");\n";
221   
222   // This checking can emit a lot of very common code.  To reduce the amount of
223   // code that we emit, batch up cases that have identical types.  This avoids
224   // problems where GCC can run out of memory compiling Verifier.cpp.
225   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
226   MapTy UniqueArgInfos;
227   
228   // Compute the unique argument type info.
229   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
230     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
231                              Ints[i].IS.ParamTypeDefs)].push_back(i);
232
233   // Loop through the array, emitting one comparison for each batch.
234   for (MapTy::iterator I = UniqueArgInfos.begin(),
235        E = UniqueArgInfos.end(); I != E; ++I) {
236     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
237       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
238          << Ints[I->second[i]].Name << "\n";
239     
240     const RecPair &ArgTypes = I->first;
241     const std::vector<Record*> &RetTys = ArgTypes.first;
242     const std::vector<Record*> &ParamTys = ArgTypes.second;
243     std::vector<unsigned> OverloadedTypeIndices;
244
245     OS << "    VerifyIntrinsicPrototype(ID, IF, " << RetTys.size() << ", "
246        << ParamTys.size();
247
248     // Emit return types.
249     for (unsigned j = 0, je = RetTys.size(); j != je; ++j) {
250       Record *ArgType = RetTys[j];
251       OS << ", ";
252
253       if (ArgType->isSubClassOf("LLVMMatchType")) {
254         unsigned Number = ArgType->getValueAsInt("Number");
255         assert(Number < OverloadedTypeIndices.size() &&
256                "Invalid matching number!");
257         Number = OverloadedTypeIndices[Number];
258         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
259           OS << "~(ExtendedElementVectorType | " << Number << ")";
260         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
261           OS << "~(TruncatedElementVectorType | " << Number << ")";
262         else
263           OS << "~" << Number;
264       } else {
265         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
266         OS << getEnumName(VT);
267
268         if (EVT(VT).isOverloaded())
269           OverloadedTypeIndices.push_back(j);
270
271         if (VT == MVT::isVoid && j != 0 && j != je - 1)
272           throw "Var arg type not last argument";
273       }
274     }
275
276     // Emit the parameter types.
277     for (unsigned j = 0, je = ParamTys.size(); j != je; ++j) {
278       Record *ArgType = ParamTys[j];
279       OS << ", ";
280
281       if (ArgType->isSubClassOf("LLVMMatchType")) {
282         unsigned Number = ArgType->getValueAsInt("Number");
283         assert(Number < OverloadedTypeIndices.size() &&
284                "Invalid matching number!");
285         Number = OverloadedTypeIndices[Number];
286         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
287           OS << "~(ExtendedElementVectorType | " << Number << ")";
288         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
289           OS << "~(TruncatedElementVectorType | " << Number << ")";
290         else
291           OS << "~" << Number;
292       } else {
293         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
294         OS << getEnumName(VT);
295
296         if (EVT(VT).isOverloaded())
297           OverloadedTypeIndices.push_back(j + RetTys.size());
298
299         if (VT == MVT::isVoid && j != 0 && j != je - 1)
300           throw "Var arg type not last argument";
301       }
302     }
303       
304     OS << ");\n";
305     OS << "    break;\n";
306   }
307   OS << "  }\n";
308   OS << "#endif\n\n";
309 }
310
311 static void EmitTypeForValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
312   if (EVT(VT).isInteger()) {
313     unsigned BitWidth = EVT(VT).getSizeInBits();
314     OS << "IntegerType::get(Context, " << BitWidth << ")";
315   } else if (VT == MVT::Other) {
316     // MVT::OtherVT is used to mean the empty struct type here.
317     OS << "StructType::get(Context)";
318   } else if (VT == MVT::f16) {
319     OS << "Type::getHalfTy(Context)";
320   } else if (VT == MVT::f32) {
321     OS << "Type::getFloatTy(Context)";
322   } else if (VT == MVT::f64) {
323     OS << "Type::getDoubleTy(Context)";
324   } else if (VT == MVT::f80) {
325     OS << "Type::getX86_FP80Ty(Context)";
326   } else if (VT == MVT::f128) {
327     OS << "Type::getFP128Ty(Context)";
328   } else if (VT == MVT::ppcf128) {
329     OS << "Type::getPPC_FP128Ty(Context)";
330   } else if (VT == MVT::isVoid) {
331     OS << "Type::getVoidTy(Context)";
332   } else if (VT == MVT::Metadata) {
333     OS << "Type::getMetadataTy(Context)";
334   } else if (VT == MVT::x86mmx) {
335     OS << "Type::getX86_MMXTy(Context)";
336   } else {
337     assert(false && "Unsupported ValueType!");
338   }
339 }
340
341 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
342                              unsigned &ArgNo);
343
344 static void EmitTypeGenerate(raw_ostream &OS,
345                              const std::vector<Record*> &ArgTypes,
346                              unsigned &ArgNo) {
347   if (ArgTypes.empty())
348     return EmitTypeForValueType(OS, MVT::isVoid);
349   
350   if (ArgTypes.size() == 1)
351     return EmitTypeGenerate(OS, ArgTypes.front(), ArgNo);
352   
353   OS << "StructType::get(";
354   
355   for (std::vector<Record*>::const_iterator
356        I = ArgTypes.begin(), E = ArgTypes.end(); I != E; ++I) {
357     EmitTypeGenerate(OS, *I, ArgNo);
358     OS << ", ";
359   }
360   
361   OS << " NULL)";
362 }
363
364 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
365                              unsigned &ArgNo) {
366   MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
367   
368   if (ArgType->isSubClassOf("LLVMMatchType")) {
369     unsigned Number = ArgType->getValueAsInt("Number");
370     assert(Number < ArgNo && "Invalid matching number!");
371     if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
372       OS << "VectorType::getExtendedElementVectorType"
373       << "(cast<VectorType>(Tys[" << Number << "]))";
374     else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
375       OS << "VectorType::getTruncatedElementVectorType"
376       << "(cast<VectorType>(Tys[" << Number << "]))";
377     else
378       OS << "Tys[" << Number << "]";
379   } else if (VT == MVT::iAny || VT == MVT::fAny || VT == MVT::vAny) {
380     // NOTE: The ArgNo variable here is not the absolute argument number, it is
381     // the index of the "arbitrary" type in the Tys array passed to the
382     // Intrinsic::getDeclaration function. Consequently, we only want to
383     // increment it when we actually hit an overloaded type. Getting this wrong
384     // leads to very subtle bugs!
385     OS << "Tys[" << ArgNo++ << "]";
386   } else if (EVT(VT).isVector()) {
387     EVT VVT = VT;
388     OS << "VectorType::get(";
389     EmitTypeForValueType(OS, VVT.getVectorElementType().getSimpleVT().SimpleTy);
390     OS << ", " << VVT.getVectorNumElements() << ")";
391   } else if (VT == MVT::iPTR) {
392     OS << "PointerType::getUnqual(";
393     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
394     OS << ")";
395   } else if (VT == MVT::iPTRAny) {
396     // Make sure the user has passed us an argument type to overload. If not,
397     // treat it as an ordinary (not overloaded) intrinsic.
398     OS << "(" << ArgNo << " < Tys.size()) ? Tys[" << ArgNo
399     << "] : PointerType::getUnqual(";
400     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
401     OS << ")";
402     ++ArgNo;
403   } else if (VT == MVT::isVoid) {
404     assert(ArgNo == 0);
405     OS << "Type::getVoidTy(Context)";
406   } else {
407     EmitTypeForValueType(OS, VT);
408   }
409 }
410
411
412 // NOTE: This must be kept in synch with the version emitted to the .gen file!
413 enum IIT_Info {
414   IIT_Done = 0,
415   IIT_I1   = 1,
416   IIT_I8   = 2,
417   IIT_I16  = 3,
418   IIT_I32  = 4,
419   IIT_I64  = 5,
420   IIT_F32  = 6,
421   IIT_F64  = 7,
422   IIT_V2   = 8,
423   IIT_V4   = 9,
424   IIT_V8   = 10,
425   IIT_V16  = 11,
426   IIT_MMX  = 12,
427   IIT_PTR  = 13,
428   IIT_ARG  = 14
429 };
430
431 static void EncodeFixedValueType(MVT::SimpleValueType VT,
432                                  SmallVectorImpl<unsigned> &Sig) {
433   if (EVT(VT).isInteger()) {
434     unsigned BitWidth = EVT(VT).getSizeInBits();
435     switch (BitWidth) {
436     default: return Sig.push_back(~0U);
437     case 1: return Sig.push_back(IIT_I1);
438     case 8: return Sig.push_back(IIT_I8);
439     case 16: return Sig.push_back(IIT_I16);
440     case 32: return Sig.push_back(IIT_I32);
441     case 64: return Sig.push_back(IIT_I64);
442     }
443   }
444   
445 /*  } else if (VT == MVT::Other) {
446     // MVT::OtherVT is used to mean the empty struct type here.
447     OS << "StructType::get(Context)";
448   } else if (VT == MVT::f16) {
449     OS << "Type::getHalfTy(Context)";*/
450   if (VT == MVT::f32)
451     return Sig.push_back(IIT_F32);
452   if (VT == MVT::f64) 
453     return Sig.push_back(IIT_F64);
454   //if (VT == MVT::f80) {
455   //  OS << "Type::getX86_FP80Ty(Context)";
456   //if (VT == MVT::f128) {
457   //  OS << "Type::getFP128Ty(Context)";
458   // if (VT == MVT::ppcf128) {
459   //  OS << "Type::getPPC_FP128Ty(Context)";
460   //if (VT == MVT::Metadata) {
461   //  OS << "Type::getMetadataTy(Context)";
462   if (VT == MVT::x86mmx) 
463     return Sig.push_back(IIT_MMX);
464     
465   assert(VT != MVT::isVoid);
466   Sig.push_back(~0U);
467 }
468
469 #ifdef _MSC_VER
470 #pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function.
471 #endif 
472
473 static void EncodeFixedType(Record *R, SmallVectorImpl<unsigned> &Sig) {
474   
475   if (R->isSubClassOf("LLVMMatchType")) {
476     return Sig.push_back(~0U);
477 /*
478     unsigned Number = ArgType->getValueAsInt("Number");
479     assert(Number < ArgNo && "Invalid matching number!");
480     if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
481       OS << "VectorType::getExtendedElementVectorType"
482       << "(cast<VectorType>(Tys[" << Number << "]))";
483     else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
484       OS << "VectorType::getTruncatedElementVectorType"
485       << "(cast<VectorType>(Tys[" << Number << "]))";
486     else
487       OS << "Tys[" << Number << "]";
488  */
489   }
490   
491   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
492   
493   if (VT == MVT::iAny || VT == MVT::fAny || VT == MVT::vAny) {
494     return Sig.push_back(~0U);
495     /*
496     // NOTE: The ArgNo variable here is not the absolute argument number, it is
497     // the index of the "arbitrary" type in the Tys array passed to the
498     // Intrinsic::getDeclaration function. Consequently, we only want to
499     // increment it when we actually hit an overloaded type. Getting this wrong
500     // leads to very subtle bugs!
501     OS << "Tys[" << ArgNo++ << "]";
502     */
503   }
504   
505   if (EVT(VT).isVector()) {
506     EVT VVT = VT;
507     switch (VVT.getVectorNumElements()) {
508     default: Sig.push_back(~0U); return;
509     case 2: Sig.push_back(IIT_V2); break;
510     case 4: Sig.push_back(IIT_V4); break;
511     case 8: Sig.push_back(IIT_V8); break;
512     case 16: Sig.push_back(IIT_V16); break;
513     }
514     
515     return EncodeFixedValueType(VVT.getVectorElementType().
516                                 getSimpleVT().SimpleTy, Sig);
517   }
518   
519   if (VT == MVT::iPTR) {
520     Sig.push_back(IIT_PTR);
521     return EncodeFixedType(R->getValueAsDef("ElTy"), Sig);
522   }
523   
524   /*if (VT == MVT::iPTRAny) {
525     // Make sure the user has passed us an argument type to overload. If not,
526     // treat it as an ordinary (not overloaded) intrinsic.
527     OS << "(" << ArgNo << " < Tys.size()) ? Tys[" << ArgNo
528     << "] : PointerType::getUnqual(";
529     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
530     OS << ")";
531     ++ArgNo;
532   }*/
533   
534   assert(VT != MVT::isVoid);
535   EncodeFixedValueType(VT, Sig);
536 }
537
538 #ifdef _MSC_VER
539 #pragma optimize("",on)
540 #endif
541
542 /// ComputeFixedEncoding - If we can encode the type signature for this
543 /// intrinsic into 32 bits, return it.  If not, return ~0U.
544 static unsigned ComputeFixedEncoding(const CodeGenIntrinsic &Int) {
545   if (Int.IS.RetVTs.size() >= 2) return ~0U;
546   
547   SmallVector<unsigned, 8> TypeSig;
548   if (Int.IS.RetVTs.empty())
549     TypeSig.push_back(IIT_Done);
550   else if (Int.IS.RetVTs.size() == 1 &&
551            Int.IS.RetVTs[0] == MVT::isVoid)
552     TypeSig.push_back(IIT_Done);
553   else    
554     EncodeFixedType(Int.IS.RetTypeDefs[0], TypeSig);
555   
556   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
557     EncodeFixedType(Int.IS.ParamTypeDefs[i], TypeSig);
558   
559   // Can only encode 8 nibbles into a 32-bit word.
560   if (TypeSig.size() > 8) return ~0U;
561   
562   unsigned Result = 0;
563   for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
564     // If we had an unencodable argument, bail out.
565     if (TypeSig[i] == ~0U)
566       return ~0U;
567     Result = (Result << 4) | TypeSig[e-i-1];
568   }
569   
570   return Result;
571 }
572
573 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, 
574                                      raw_ostream &OS) {
575   OS << "// Global intrinsic function declaration type table.\n";
576   OS << "#ifdef GET_INTRINSTIC_GENERATOR_GLOBAL\n";
577   // NOTE: These enums must be kept in sync with the ones above!
578   OS << "enum IIT_Info {\n";
579   OS << "  IIT_Done = 0,\n";
580   OS << "  IIT_I1   = 1,\n";
581   OS << "  IIT_I8   = 2,\n";
582   OS << "  IIT_I16  = 3,\n";
583   OS << "  IIT_I32  = 4,\n";
584   OS << "  IIT_I64  = 5,\n";
585   OS << "  IIT_F32  = 6,\n";
586   OS << "  IIT_F64  = 7,\n";
587   OS << "  IIT_V2   = 8,\n";
588   OS << "  IIT_V4   = 9,\n";
589   OS << "  IIT_V8   = 10,\n";
590   OS << "  IIT_V16  = 11,\n";
591   OS << "  IIT_MMX  = 12,\n";
592   OS << "  IIT_PTR  = 13,\n";
593   OS << "  IIT_ARG  = 14\n";
594   // 15 is unassigned so far.
595   OS << "};\n\n";
596
597   
598   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
599   // types.
600   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
601   MapTy UniqueArgInfos;
602
603   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
604   // capture it in this vector, otherwise store a ~0U.
605   std::vector<unsigned> FixedEncodings;
606   
607   // Compute the unique argument type info.
608   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
609     FixedEncodings.push_back(ComputeFixedEncoding(Ints[i]));
610     
611     // If we didn't compute a compact encoding, emit a long-form variant.
612     if (FixedEncodings.back() == ~0U)
613       UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
614                                Ints[i].IS.ParamTypeDefs)].push_back(i);
615   }
616   
617   OS << "static const unsigned IIT_Table[] = {\n  ";
618   
619   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
620     if ((i & 7) == 7)
621       OS << "\n  ";
622     if (FixedEncodings[i] == ~0U) 
623       OS << "~0U, ";
624     else
625       OS << "0x" << utohexstr(FixedEncodings[i]) << ", ";
626   }
627   
628   OS << "0\n};\n\n#endif\n\n";  // End of GET_INTRINSTIC_GENERATOR_GLOBAL
629   
630   OS << "// Code for generating Intrinsic function declarations.\n";
631   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
632   OS << "  switch (id) {\n";
633   OS << "  default: llvm_unreachable(\"Invalid intrinsic!\");\n";
634
635   // Loop through the array, emitting one generator for each batch.
636   std::string IntrinsicStr = TargetPrefix + "Intrinsic::";
637   
638   for (MapTy::iterator I = UniqueArgInfos.begin(),
639        E = UniqueArgInfos.end(); I != E; ++I) {
640     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
641       OS << "  case " << IntrinsicStr << Ints[I->second[i]].EnumName 
642          << ":\t\t// " << Ints[I->second[i]].Name << "\n";
643     
644     const RecPair &ArgTypes = I->first;
645     const std::vector<Record*> &RetTys = ArgTypes.first;
646     const std::vector<Record*> &ParamTys = ArgTypes.second;
647
648     unsigned N = ParamTys.size();
649     unsigned ArgNo = 0;
650     OS << "    ResultTy = ";
651     EmitTypeGenerate(OS, RetTys, ArgNo);
652     OS << ";\n";
653     
654     for (unsigned j = 0; j != N; ++j) {
655       OS << "    ArgTys.push_back(";
656       EmitTypeGenerate(OS, ParamTys[j], ArgNo);
657       OS << ");\n";
658     }
659
660     OS << "    break;\n";
661   }
662
663   OS << "  }\n";
664   OS << "#endif\n\n";
665 }
666
667 namespace {
668   enum ModRefKind {
669     MRK_none,
670     MRK_readonly,
671     MRK_readnone
672   };
673
674   ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
675     switch (intrinsic.ModRef) {
676     case CodeGenIntrinsic::NoMem:
677       return MRK_readnone;
678     case CodeGenIntrinsic::ReadArgMem:
679     case CodeGenIntrinsic::ReadMem:
680       return MRK_readonly;
681     case CodeGenIntrinsic::ReadWriteArgMem:
682     case CodeGenIntrinsic::ReadWriteMem:
683       return MRK_none;
684     }
685     llvm_unreachable("bad mod-ref kind");
686   }
687
688   struct AttributeComparator {
689     bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
690       // Sort throwing intrinsics after non-throwing intrinsics.
691       if (L->canThrow != R->canThrow)
692         return R->canThrow;
693
694       // Try to order by readonly/readnone attribute.
695       ModRefKind LK = getModRefKind(*L);
696       ModRefKind RK = getModRefKind(*R);
697       if (LK != RK) return (LK > RK);
698
699       // Order by argument attributes.
700       // This is reliable because each side is already sorted internally.
701       return (L->ArgumentAttributes < R->ArgumentAttributes);
702     }
703   };
704 }
705
706 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
707 void IntrinsicEmitter::
708 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
709   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
710   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
711   if (TargetOnly)
712     OS << "static AttrListPtr getAttributes(" << TargetPrefix 
713        << "Intrinsic::ID id) {\n";
714   else
715     OS << "AttrListPtr Intrinsic::getAttributes(ID id) {\n";
716
717   // Compute the maximum number of attribute arguments and the map
718   typedef std::map<const CodeGenIntrinsic*, unsigned,
719                    AttributeComparator> UniqAttrMapTy;
720   UniqAttrMapTy UniqAttributes;
721   unsigned maxArgAttrs = 0;
722   unsigned AttrNum = 0;
723   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
724     const CodeGenIntrinsic &intrinsic = Ints[i];
725     maxArgAttrs =
726       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
727     unsigned &N = UniqAttributes[&intrinsic];
728     if (N) continue;
729     assert(AttrNum < 256 && "Too many unique attributes for table!");
730     N = ++AttrNum;
731   }
732
733   // Emit an array of AttributeWithIndex.  Most intrinsics will have
734   // at least one entry, for the function itself (index ~1), which is
735   // usually nounwind.
736   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
737
738   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
739     const CodeGenIntrinsic &intrinsic = Ints[i];
740
741     OS << "    " << UniqAttributes[&intrinsic] << ", // "
742        << intrinsic.Name << "\n";
743   }
744   OS << "  };\n\n";
745
746   OS << "  AttributeWithIndex AWI[" << maxArgAttrs+1 << "];\n";
747   OS << "  unsigned NumAttrs = 0;\n";
748   OS << "  if (id != 0) {\n";
749   OS << "    switch(IntrinsicsToAttributesMap[id - ";
750   if (TargetOnly)
751     OS << "Intrinsic::num_intrinsics";
752   else
753     OS << "1";
754   OS << "]) {\n";
755   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
756   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
757        E = UniqAttributes.end(); I != E; ++I) {
758     OS << "    case " << I->second << ":\n";
759
760     const CodeGenIntrinsic &intrinsic = *(I->first);
761
762     // Keep track of the number of attributes we're writing out.
763     unsigned numAttrs = 0;
764
765     // The argument attributes are alreadys sorted by argument index.
766     for (unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size(); ai != ae;) {
767       unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
768
769       OS << "      AWI[" << numAttrs++ << "] = AttributeWithIndex::get("
770          << argNo+1 << ", ";
771
772       bool moreThanOne = false;
773
774       do {
775         if (moreThanOne) OS << '|';
776
777         switch (intrinsic.ArgumentAttributes[ai].second) {
778         case CodeGenIntrinsic::NoCapture:
779           OS << "Attribute::NoCapture";
780           break;
781         }
782
783         ++ai;
784         moreThanOne = true;
785       } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
786
787       OS << ");\n";
788     }
789
790     ModRefKind modRef = getModRefKind(intrinsic);
791
792     if (!intrinsic.canThrow || modRef) {
793       OS << "      AWI[" << numAttrs++ << "] = AttributeWithIndex::get(~0, ";
794       if (!intrinsic.canThrow) {
795         OS << "Attribute::NoUnwind";
796         if (modRef) OS << '|';
797       }
798       switch (modRef) {
799       case MRK_none: break;
800       case MRK_readonly: OS << "Attribute::ReadOnly"; break;
801       case MRK_readnone: OS << "Attribute::ReadNone"; break;
802       }
803       OS << ");\n";
804     }
805
806     if (numAttrs) {
807       OS << "      NumAttrs = " << numAttrs << ";\n";
808       OS << "      break;\n";
809     } else {
810       OS << "      return AttrListPtr();\n";
811     }
812   }
813   
814   OS << "    }\n";
815   OS << "  }\n";
816   OS << "  return AttrListPtr::get(AWI, NumAttrs);\n";
817   OS << "}\n";
818   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
819 }
820
821 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
822 void IntrinsicEmitter::
823 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
824   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
825      << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
826      << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && "
827      << "\"Unknown intrinsic.\");\n\n";
828
829   OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n"
830      << "  /* invalid */ UnknownModRefBehavior,\n";
831   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
832     OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
833     switch (Ints[i].ModRef) {
834     case CodeGenIntrinsic::NoMem:
835       OS << "DoesNotAccessMemory,\n";
836       break;
837     case CodeGenIntrinsic::ReadArgMem:
838       OS << "OnlyReadsArgumentPointees,\n";
839       break;
840     case CodeGenIntrinsic::ReadMem:
841       OS << "OnlyReadsMemory,\n";
842       break;
843     case CodeGenIntrinsic::ReadWriteArgMem:
844       OS << "OnlyAccessesArgumentPointees,\n";
845       break;
846     case CodeGenIntrinsic::ReadWriteMem:
847       OS << "UnknownModRefBehavior,\n";
848       break;
849     }
850   }
851   OS << "};\n\n"
852      << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n"
853      << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
854 }
855
856 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
857 /// same target, and we already checked it.
858 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
859                                const std::string &TargetPrefix,
860                                raw_ostream &OS) {
861   
862   std::vector<StringMatcher::StringPair> Results;
863   
864   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
865        E = BIM.end(); I != E; ++I) {
866     std::string ResultCode =
867     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
868     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
869   }
870
871   StringMatcher("BuiltinName", Results, OS).Emit();
872 }
873
874         
875 void IntrinsicEmitter::
876 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
877                              raw_ostream &OS) {
878   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
879   BIMTy BuiltinMap;
880   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
881     if (!Ints[i].GCCBuiltinName.empty()) {
882       // Get the map for this target prefix.
883       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
884       
885       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
886                                      Ints[i].EnumName)).second)
887         throw "Intrinsic '" + Ints[i].TheDef->getName() +
888               "': duplicate GCC builtin name!";
889     }
890   }
891   
892   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
893   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
894   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
895   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
896   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
897   
898   if (TargetOnly) {
899     OS << "static " << TargetPrefix << "Intrinsic::ID "
900        << "getIntrinsicForGCCBuiltin(const char "
901        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
902   } else {
903     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
904        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
905   }
906   
907   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
908   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
909   
910   // Note: this could emit significantly better code if we cared.
911   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
912     OS << "  ";
913     if (!I->first.empty())
914       OS << "if (TargetPrefix == \"" << I->first << "\") ";
915     else
916       OS << "/* Target Independent Builtins */ ";
917     OS << "{\n";
918
919     // Emit the comparisons for this target prefix.
920     EmitTargetBuiltins(I->second, TargetPrefix, OS);
921     OS << "  }\n";
922   }
923   OS << "  return ";
924   if (!TargetPrefix.empty())
925     OS << "(" << TargetPrefix << "Intrinsic::ID)";
926   OS << "Intrinsic::not_intrinsic;\n";
927   OS << "}\n";
928   OS << "#endif\n\n";
929 }