• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
run(raw_ostream & OS)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 
EmitPrefix(raw_ostream & OS)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 
EmitSuffix(raw_ostream & OS)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 
EmitEnumInfo(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)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::
EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)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::
EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)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::
EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)161 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,
162                          raw_ostream &OS) {
163   OS << "// Intrinsic ID to overload table\n";
164   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
165   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
166   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
167     OS << "  ";
168     if (Ints[i].isOverloaded)
169       OS << "true";
170     else
171       OS << "false";
172     OS << ",\n";
173   }
174   OS << "#endif\n\n";
175 }
176 
EmitTypeForValueType(raw_ostream & OS,MVT::SimpleValueType VT)177 static void EmitTypeForValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
178   if (EVT(VT).isInteger()) {
179     unsigned BitWidth = EVT(VT).getSizeInBits();
180     OS << "IntegerType::get(Context, " << BitWidth << ")";
181   } else if (VT == MVT::Other) {
182     // MVT::OtherVT is used to mean the empty struct type here.
183     OS << "StructType::get(Context)";
184   } else if (VT == MVT::f32) {
185     OS << "Type::getFloatTy(Context)";
186   } else if (VT == MVT::f64) {
187     OS << "Type::getDoubleTy(Context)";
188   } else if (VT == MVT::f80) {
189     OS << "Type::getX86_FP80Ty(Context)";
190   } else if (VT == MVT::f128) {
191     OS << "Type::getFP128Ty(Context)";
192   } else if (VT == MVT::ppcf128) {
193     OS << "Type::getPPC_FP128Ty(Context)";
194   } else if (VT == MVT::isVoid) {
195     OS << "Type::getVoidTy(Context)";
196   } else if (VT == MVT::Metadata) {
197     OS << "Type::getMetadataTy(Context)";
198   } else if (VT == MVT::x86mmx) {
199     OS << "Type::getX86_MMXTy(Context)";
200   } else {
201     assert(false && "Unsupported ValueType!");
202   }
203 }
204 
205 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
206                              unsigned &ArgNo);
207 
EmitTypeGenerate(raw_ostream & OS,const std::vector<Record * > & ArgTypes,unsigned & ArgNo)208 static void EmitTypeGenerate(raw_ostream &OS,
209                              const std::vector<Record*> &ArgTypes,
210                              unsigned &ArgNo) {
211   if (ArgTypes.empty())
212     return EmitTypeForValueType(OS, MVT::isVoid);
213 
214   if (ArgTypes.size() == 1)
215     return EmitTypeGenerate(OS, ArgTypes.front(), ArgNo);
216 
217   OS << "StructType::get(";
218 
219   for (std::vector<Record*>::const_iterator
220          I = ArgTypes.begin(), E = ArgTypes.end(); I != E; ++I) {
221     EmitTypeGenerate(OS, *I, ArgNo);
222     OS << ", ";
223   }
224 
225   OS << " NULL)";
226 }
227 
EmitTypeGenerate(raw_ostream & OS,const Record * ArgType,unsigned & ArgNo)228 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
229                              unsigned &ArgNo) {
230   MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
231 
232   if (ArgType->isSubClassOf("LLVMMatchType")) {
233     unsigned Number = ArgType->getValueAsInt("Number");
234     assert(Number < ArgNo && "Invalid matching number!");
235     if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
236       OS << "VectorType::getExtendedElementVectorType"
237          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
238     else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
239       OS << "VectorType::getTruncatedElementVectorType"
240          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
241     else
242       OS << "Tys[" << Number << "]";
243   } else if (VT == MVT::iAny || VT == MVT::fAny || VT == MVT::vAny) {
244     // NOTE: The ArgNo variable here is not the absolute argument number, it is
245     // the index of the "arbitrary" type in the Tys array passed to the
246     // Intrinsic::getDeclaration function. Consequently, we only want to
247     // increment it when we actually hit an overloaded type. Getting this wrong
248     // leads to very subtle bugs!
249     OS << "Tys[" << ArgNo++ << "]";
250   } else if (EVT(VT).isVector()) {
251     EVT VVT = VT;
252     OS << "VectorType::get(";
253     EmitTypeForValueType(OS, VVT.getVectorElementType().getSimpleVT().SimpleTy);
254     OS << ", " << VVT.getVectorNumElements() << ")";
255   } else if (VT == MVT::iPTR) {
256     OS << "PointerType::getUnqual(";
257     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
258     OS << ")";
259   } else if (VT == MVT::iPTRAny) {
260     // Make sure the user has passed us an argument type to overload. If not,
261     // treat it as an ordinary (not overloaded) intrinsic.
262     OS << "(" << ArgNo << " < Tys.size()) ? Tys[" << ArgNo
263     << "] : PointerType::getUnqual(";
264     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
265     OS << ")";
266     ++ArgNo;
267   } else if (VT == MVT::isVoid) {
268     if (ArgNo == 0)
269       OS << "Type::getVoidTy(Context)";
270     else
271       // MVT::isVoid is used to mean varargs here.
272       OS << "...";
273   } else {
274     EmitTypeForValueType(OS, VT);
275   }
276 }
277 
278 /// RecordListComparator - Provide a deterministic comparator for lists of
279 /// records.
280 namespace {
281   typedef std::pair<std::vector<Record*>, std::vector<Record*> > RecPair;
282   struct RecordListComparator {
operator ()__anon67d043df0111::RecordListComparator283     bool operator()(const RecPair &LHS,
284                     const RecPair &RHS) const {
285       unsigned i = 0;
286       const std::vector<Record*> *LHSVec = &LHS.first;
287       const std::vector<Record*> *RHSVec = &RHS.first;
288       unsigned RHSSize = RHSVec->size();
289       unsigned LHSSize = LHSVec->size();
290 
291       for (; i != LHSSize; ++i) {
292         if (i == RHSSize) return false;  // RHS is shorter than LHS.
293         if ((*LHSVec)[i] != (*RHSVec)[i])
294           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
295       }
296 
297       if (i != RHSSize) return true;
298 
299       i = 0;
300       LHSVec = &LHS.second;
301       RHSVec = &RHS.second;
302       RHSSize = RHSVec->size();
303       LHSSize = LHSVec->size();
304 
305       for (i = 0; i != LHSSize; ++i) {
306         if (i == RHSSize) return false;  // RHS is shorter than LHS.
307         if ((*LHSVec)[i] != (*RHSVec)[i])
308           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
309       }
310 
311       return i != RHSSize;
312     }
313   };
314 }
315 
EmitVerifier(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)316 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints,
317                                     raw_ostream &OS) {
318   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
319   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
320   OS << "  switch (ID) {\n";
321   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
322 
323   // This checking can emit a lot of very common code.  To reduce the amount of
324   // code that we emit, batch up cases that have identical types.  This avoids
325   // problems where GCC can run out of memory compiling Verifier.cpp.
326   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
327   MapTy UniqueArgInfos;
328 
329   // Compute the unique argument type info.
330   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
331     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
332                              Ints[i].IS.ParamTypeDefs)].push_back(i);
333 
334   // Loop through the array, emitting one comparison for each batch.
335   for (MapTy::iterator I = UniqueArgInfos.begin(),
336        E = UniqueArgInfos.end(); I != E; ++I) {
337     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
338       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
339          << Ints[I->second[i]].Name << "\n";
340 
341     const RecPair &ArgTypes = I->first;
342     const std::vector<Record*> &RetTys = ArgTypes.first;
343     const std::vector<Record*> &ParamTys = ArgTypes.second;
344     std::vector<unsigned> OverloadedTypeIndices;
345 
346     OS << "    VerifyIntrinsicPrototype(ID, IF, " << RetTys.size() << ", "
347        << ParamTys.size();
348 
349     // Emit return types.
350     for (unsigned j = 0, je = RetTys.size(); j != je; ++j) {
351       Record *ArgType = RetTys[j];
352       OS << ", ";
353 
354       if (ArgType->isSubClassOf("LLVMMatchType")) {
355         unsigned Number = ArgType->getValueAsInt("Number");
356         assert(Number < OverloadedTypeIndices.size() &&
357                "Invalid matching number!");
358         Number = OverloadedTypeIndices[Number];
359         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
360           OS << "~(ExtendedElementVectorType | " << Number << ")";
361         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
362           OS << "~(TruncatedElementVectorType | " << Number << ")";
363         else
364           OS << "~" << Number;
365       } else {
366         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
367         OS << getEnumName(VT);
368 
369         if (EVT(VT).isOverloaded())
370           OverloadedTypeIndices.push_back(j);
371 
372         if (VT == MVT::isVoid && j != 0 && j != je - 1)
373           throw "Var arg type not last argument";
374       }
375     }
376 
377     // Emit the parameter types.
378     for (unsigned j = 0, je = ParamTys.size(); j != je; ++j) {
379       Record *ArgType = ParamTys[j];
380       OS << ", ";
381 
382       if (ArgType->isSubClassOf("LLVMMatchType")) {
383         unsigned Number = ArgType->getValueAsInt("Number");
384         assert(Number < OverloadedTypeIndices.size() &&
385                "Invalid matching number!");
386         Number = OverloadedTypeIndices[Number];
387         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
388           OS << "~(ExtendedElementVectorType | " << Number << ")";
389         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
390           OS << "~(TruncatedElementVectorType | " << Number << ")";
391         else
392           OS << "~" << Number;
393       } else {
394         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
395         OS << getEnumName(VT);
396 
397         if (EVT(VT).isOverloaded())
398           OverloadedTypeIndices.push_back(j + RetTys.size());
399 
400         if (VT == MVT::isVoid && j != 0 && j != je - 1)
401           throw "Var arg type not last argument";
402       }
403     }
404 
405     OS << ");\n";
406     OS << "    break;\n";
407   }
408   OS << "  }\n";
409   OS << "#endif\n\n";
410 }
411 
EmitGenerator(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)412 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
413                                      raw_ostream &OS) {
414   OS << "// Code for generating Intrinsic function declarations.\n";
415   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
416   OS << "  switch (id) {\n";
417   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
418 
419   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
420   // types.
421   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
422   MapTy UniqueArgInfos;
423 
424   // Compute the unique argument type info.
425   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
426     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
427                              Ints[i].IS.ParamTypeDefs)].push_back(i);
428 
429   // Loop through the array, emitting one generator for each batch.
430   std::string IntrinsicStr = TargetPrefix + "Intrinsic::";
431 
432   for (MapTy::iterator I = UniqueArgInfos.begin(),
433        E = UniqueArgInfos.end(); I != E; ++I) {
434     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
435       OS << "  case " << IntrinsicStr << Ints[I->second[i]].EnumName
436          << ":\t\t// " << Ints[I->second[i]].Name << "\n";
437 
438     const RecPair &ArgTypes = I->first;
439     const std::vector<Record*> &RetTys = ArgTypes.first;
440     const std::vector<Record*> &ParamTys = ArgTypes.second;
441 
442     unsigned N = ParamTys.size();
443 
444     if (N > 1 &&
445         getValueType(ParamTys[N - 1]->getValueAsDef("VT")) == MVT::isVoid) {
446       OS << "    IsVarArg = true;\n";
447       --N;
448     }
449 
450     unsigned ArgNo = 0;
451     OS << "    ResultTy = ";
452     EmitTypeGenerate(OS, RetTys, ArgNo);
453     OS << ";\n";
454 
455     for (unsigned j = 0; j != N; ++j) {
456       OS << "    ArgTys.push_back(";
457       EmitTypeGenerate(OS, ParamTys[j], ArgNo);
458       OS << ");\n";
459     }
460 
461     OS << "    break;\n";
462   }
463 
464   OS << "  }\n";
465   OS << "#endif\n\n";
466 }
467 
468 namespace {
469   enum ModRefKind {
470     MRK_none,
471     MRK_readonly,
472     MRK_readnone
473   };
474 
getModRefKind(const CodeGenIntrinsic & intrinsic)475   ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
476     switch (intrinsic.ModRef) {
477     case CodeGenIntrinsic::NoMem:
478       return MRK_readnone;
479     case CodeGenIntrinsic::ReadArgMem:
480     case CodeGenIntrinsic::ReadMem:
481       return MRK_readonly;
482     case CodeGenIntrinsic::ReadWriteArgMem:
483     case CodeGenIntrinsic::ReadWriteMem:
484       return MRK_none;
485     }
486     assert(0 && "bad mod-ref kind");
487     return MRK_none;
488   }
489 
490   struct AttributeComparator {
operator ()__anon67d043df0211::AttributeComparator491     bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
492       // Sort throwing intrinsics after non-throwing intrinsics.
493       if (L->canThrow != R->canThrow)
494         return R->canThrow;
495 
496       // Try to order by readonly/readnone attribute.
497       ModRefKind LK = getModRefKind(*L);
498       ModRefKind RK = getModRefKind(*R);
499       if (LK != RK) return (LK > RK);
500 
501       // Order by argument attributes.
502       // This is reliable because each side is already sorted internally.
503       return (L->ArgumentAttributes < R->ArgumentAttributes);
504     }
505   };
506 }
507 
508 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
509 void IntrinsicEmitter::
EmitAttributes(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)510 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
511   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
512   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
513   if (TargetOnly)
514     OS << "static AttrListPtr getAttributes(" << TargetPrefix
515        << "Intrinsic::ID id) {\n";
516   else
517     OS << "AttrListPtr Intrinsic::getAttributes(ID id) {\n";
518 
519   // Compute the maximum number of attribute arguments.
520   std::vector<const CodeGenIntrinsic*> sortedIntrinsics(Ints.size());
521   unsigned maxArgAttrs = 0;
522   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
523     const CodeGenIntrinsic &intrinsic = Ints[i];
524     sortedIntrinsics[i] = &intrinsic;
525     maxArgAttrs =
526       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
527   }
528 
529   // Emit an array of AttributeWithIndex.  Most intrinsics will have
530   // at least one entry, for the function itself (index ~1), which is
531   // usually nounwind.
532   OS << "  AttributeWithIndex AWI[" << maxArgAttrs+1 << "];\n";
533   OS << "  unsigned NumAttrs = 0;\n";
534   OS << "  switch (id) {\n";
535   OS << "    default: break;\n";
536 
537   AttributeComparator precedes;
538 
539   std::stable_sort(sortedIntrinsics.begin(), sortedIntrinsics.end(), precedes);
540 
541   for (unsigned i = 0, e = sortedIntrinsics.size(); i != e; ++i) {
542     const CodeGenIntrinsic &intrinsic = *sortedIntrinsics[i];
543     OS << "  case " << TargetPrefix << "Intrinsic::"
544        << intrinsic.EnumName << ":\n";
545 
546     // Fill out the case if this is the last case for this range of
547     // intrinsics.
548     if (i + 1 != e && !precedes(&intrinsic, sortedIntrinsics[i + 1]))
549       continue;
550 
551     // Keep track of the number of attributes we're writing out.
552     unsigned numAttrs = 0;
553 
554     // The argument attributes are alreadys sorted by argument index.
555     for (unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size(); ai != ae;) {
556       unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
557 
558       OS << "    AWI[" << numAttrs++ << "] = AttributeWithIndex::get("
559          << argNo+1 << ", ";
560 
561       bool moreThanOne = false;
562 
563       do {
564         if (moreThanOne) OS << '|';
565 
566         switch (intrinsic.ArgumentAttributes[ai].second) {
567         case CodeGenIntrinsic::NoCapture:
568           OS << "Attribute::NoCapture";
569           break;
570         }
571 
572         ++ai;
573         moreThanOne = true;
574       } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
575 
576       OS << ");\n";
577     }
578 
579     ModRefKind modRef = getModRefKind(intrinsic);
580 
581     if (!intrinsic.canThrow || modRef) {
582       OS << "    AWI[" << numAttrs++ << "] = AttributeWithIndex::get(~0, ";
583       if (!intrinsic.canThrow) {
584         OS << "Attribute::NoUnwind";
585         if (modRef) OS << '|';
586       }
587       switch (modRef) {
588       case MRK_none: break;
589       case MRK_readonly: OS << "Attribute::ReadOnly"; break;
590       case MRK_readnone: OS << "Attribute::ReadNone"; break;
591       }
592       OS << ");\n";
593     }
594 
595     if (numAttrs) {
596       OS << "    NumAttrs = " << numAttrs << ";\n";
597       OS << "    break;\n";
598     } else {
599       OS << "    return AttrListPtr();\n";
600     }
601   }
602 
603   OS << "  }\n";
604   OS << "  return AttrListPtr::get(AWI, NumAttrs);\n";
605   OS << "}\n";
606   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
607 }
608 
609 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
610 void IntrinsicEmitter::
EmitModRefBehavior(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)611 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
612   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n";
613   OS << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n";
614   OS << "switch (iid) {\n";
615   OS << "default:\n    return UnknownModRefBehavior;\n";
616   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
617     if (Ints[i].ModRef == CodeGenIntrinsic::ReadWriteMem)
618       continue;
619     OS << "case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName
620       << ":\n";
621     switch (Ints[i].ModRef) {
622     default:
623       assert(false && "Unknown Mod/Ref type!");
624     case CodeGenIntrinsic::NoMem:
625       OS << "  return DoesNotAccessMemory;\n";
626       break;
627     case CodeGenIntrinsic::ReadArgMem:
628       OS << "  return OnlyReadsArgumentPointees;\n";
629       break;
630     case CodeGenIntrinsic::ReadMem:
631       OS << "  return OnlyReadsMemory;\n";
632       break;
633     case CodeGenIntrinsic::ReadWriteArgMem:
634       OS << "  return OnlyAccessesArgumentPointees;\n";
635       break;
636     }
637   }
638   OS << "}\n";
639   OS << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
640 }
641 
642 void IntrinsicEmitter::
EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)643 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
644   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
645   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
646   OS << "  switch (F->getIntrinsicID()) {\n";
647   OS << "  default: BuiltinName = \"\"; break;\n";
648   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
649     if (!Ints[i].GCCBuiltinName.empty()) {
650       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
651          << Ints[i].GCCBuiltinName << "\"; break;\n";
652     }
653   }
654   OS << "  }\n";
655   OS << "#endif\n\n";
656 }
657 
658 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
659 /// same target, and we already checked it.
EmitTargetBuiltins(const std::map<std::string,std::string> & BIM,const std::string & TargetPrefix,raw_ostream & OS)660 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
661                                const std::string &TargetPrefix,
662                                raw_ostream &OS) {
663 
664   std::vector<StringMatcher::StringPair> Results;
665 
666   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
667        E = BIM.end(); I != E; ++I) {
668     std::string ResultCode =
669     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
670     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
671   }
672 
673   StringMatcher("BuiltinName", Results, OS).Emit();
674 }
675 
676 
677 void IntrinsicEmitter::
EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> & Ints,raw_ostream & OS)678 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
679                              raw_ostream &OS) {
680   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
681   BIMTy BuiltinMap;
682   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
683     if (!Ints[i].GCCBuiltinName.empty()) {
684       // Get the map for this target prefix.
685       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
686 
687       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
688                                      Ints[i].EnumName)).second)
689         throw "Intrinsic '" + Ints[i].TheDef->getName() +
690               "': duplicate GCC builtin name!";
691     }
692   }
693 
694   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
695   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
696   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
697   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
698   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
699 
700   if (TargetOnly) {
701     OS << "static " << TargetPrefix << "Intrinsic::ID "
702        << "getIntrinsicForGCCBuiltin(const char "
703        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
704   } else {
705     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
706        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
707   }
708 
709   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
710   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
711 
712   // Note: this could emit significantly better code if we cared.
713   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
714     OS << "  ";
715     if (!I->first.empty())
716       OS << "if (TargetPrefix == \"" << I->first << "\") ";
717     else
718       OS << "/* Target Independent Builtins */ ";
719     OS << "{\n";
720 
721     // Emit the comparisons for this target prefix.
722     EmitTargetBuiltins(I->second, TargetPrefix, OS);
723     OS << "  }\n";
724   }
725   OS << "  return ";
726   if (!TargetPrefix.empty())
727     OS << "(" << TargetPrefix << "Intrinsic::ID)";
728   OS << "Intrinsic::not_intrinsic;\n";
729   OS << "}\n";
730   OS << "#endif\n\n";
731 }
732