1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits information about intrinsic functions.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenTarget.h"
15 #include "IntrinsicEmitter.h"
17 #include "llvm/ADT/StringExtras.h"
21 //===----------------------------------------------------------------------===//
22 // IntrinsicEmitter Implementation
23 //===----------------------------------------------------------------------===//
25 void IntrinsicEmitter::run(std::ostream &OS) {
26 EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
28 std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records);
30 // Emit the enum information.
31 EmitEnumInfo(Ints, OS);
33 // Emit the intrinsic ID -> name table.
34 EmitIntrinsicToNameTable(Ints, OS);
36 // Emit the function name recognizer.
37 EmitFnNameRecognizer(Ints, OS);
39 // Emit the intrinsic verifier.
40 EmitVerifier(Ints, OS);
42 // Emit the intrinsic declaration generator.
43 EmitGenerator(Ints, OS);
45 // Emit the intrinsic parameter attributes.
46 EmitAttributes(Ints, OS);
48 // Emit a list of intrinsics with corresponding GCC builtins.
49 EmitGCCBuiltinList(Ints, OS);
51 // Emit code to translate GCC builtins into LLVM intrinsics.
52 EmitIntrinsicToGCCBuiltinMap(Ints, OS);
55 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
57 OS << "// Enum values for Intrinsics.h\n";
58 OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
59 for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
60 OS << " " << Ints[i].EnumName;
61 OS << ((i != e-1) ? ", " : " ");
62 OS << std::string(40-Ints[i].EnumName.size(), ' ')
63 << "// " << Ints[i].Name << "\n";
68 void IntrinsicEmitter::
69 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
71 // Build a function name -> intrinsic name mapping.
72 std::map<std::string, unsigned> IntMapping;
73 for (unsigned i = 0, e = Ints.size(); i != e; ++i)
74 IntMapping[Ints[i].Name] = i;
76 OS << "// Function name -> enum value recognizer code.\n";
77 OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
78 OS << " switch (Name[5]) {\n";
80 // Emit the intrinsics in sorted order.
82 for (std::map<std::string, unsigned>::iterator I = IntMapping.begin(),
83 E = IntMapping.end(); I != E; ++I) {
84 if (I->first[5] != LastChar) {
85 LastChar = I->first[5];
87 OS << " case '" << LastChar << "':\n";
90 // For overloaded intrinsics, only the prefix needs to match
91 if (Ints[I->second].isOverloaded)
92 OS << " if (Len > " << I->first.size()
93 << " && !memcmp(Name, \"" << I->first << ".\", "
94 << (I->first.size() + 1) << ")) return Intrinsic::"
95 << Ints[I->second].EnumName << ";\n";
97 OS << " if (Len == " << I->first.size()
98 << " && !memcmp(Name, \"" << I->first << "\", "
99 << I->first.size() << ")) return Intrinsic::"
100 << Ints[I->second].EnumName << ";\n";
106 void IntrinsicEmitter::
107 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
109 OS << "// Intrinsic ID to name table\n";
110 OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
111 OS << " // Note that entry #0 is the invalid intrinsic!\n";
112 for (unsigned i = 0, e = Ints.size(); i != e; ++i)
113 OS << " \"" << Ints[i].Name << "\",\n";
117 static void EmitTypeForValueType(std::ostream &OS, MVT::SimpleValueType VT) {
118 if (MVT(VT).isInteger()) {
119 unsigned BitWidth = MVT(VT).getSizeInBits();
120 OS << "IntegerType::get(" << BitWidth << ")";
121 } else if (VT == MVT::Other) {
122 // MVT::OtherVT is used to mean the empty struct type here.
123 OS << "StructType::get(std::vector<const Type *>())";
124 } else if (VT == MVT::f32) {
125 OS << "Type::FloatTy";
126 } else if (VT == MVT::f64) {
127 OS << "Type::DoubleTy";
128 } else if (VT == MVT::f80) {
129 OS << "Type::X86_FP80Ty";
130 } else if (VT == MVT::f128) {
131 OS << "Type::FP128Ty";
132 } else if (VT == MVT::ppcf128) {
133 OS << "Type::PPC_FP128Ty";
134 } else if (VT == MVT::isVoid) {
135 OS << "Type::VoidTy";
137 assert(false && "Unsupported ValueType!");
141 static void EmitTypeGenerate(std::ostream &OS, const Record *ArgType,
144 static void EmitTypeGenerate(std::ostream &OS,
145 const std::vector<Record*> &ArgTypes,
147 if (ArgTypes.size() == 1) {
148 EmitTypeGenerate(OS, ArgTypes.front(), ArgNo);
152 OS << "StructType::get(";
154 for (std::vector<Record*>::const_iterator
155 I = ArgTypes.begin(), E = ArgTypes.end(); I != E; ++I) {
156 EmitTypeGenerate(OS, *I, ArgNo);
163 static void EmitTypeGenerate(std::ostream &OS, const Record *ArgType,
165 MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
167 if (ArgType->isSubClassOf("LLVMMatchType")) {
168 unsigned Number = ArgType->getValueAsInt("Number");
169 assert(Number < ArgNo && "Invalid matching number!");
170 if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
171 OS << "VectorType::getExtendedElementVectorType"
172 << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
173 else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
174 OS << "VectorType::getTruncatedElementVectorType"
175 << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
177 OS << "Tys[" << Number << "]";
178 } else if (VT == MVT::iAny || VT == MVT::fAny) {
179 // NOTE: The ArgNo variable here is not the absolute argument number, it is
180 // the index of the "arbitrary" type in the Tys array passed to the
181 // Intrinsic::getDeclaration function. Consequently, we only want to
182 // increment it when we actually hit an overloaded type. Getting this wrong
183 // leads to very subtle bugs!
184 OS << "Tys[" << ArgNo++ << "]";
185 } else if (MVT(VT).isVector()) {
187 OS << "VectorType::get(";
188 EmitTypeForValueType(OS, VVT.getVectorElementType().getSimpleVT());
189 OS << ", " << VVT.getVectorNumElements() << ")";
190 } else if (VT == MVT::iPTR) {
191 OS << "PointerType::getUnqual(";
192 EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
194 } else if (VT == MVT::iPTRAny) {
195 // Make sure the user has passed us an argument type to overload. If not,
196 // treat it as an ordinary (not overloaded) intrinsic.
197 OS << "(" << ArgNo << " < numTys) ? Tys[" << ArgNo
198 << "] : PointerType::getUnqual(";
199 EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
202 } else if (VT == MVT::isVoid) {
204 OS << "Type::VoidTy";
206 // MVT::isVoid is used to mean varargs here.
209 EmitTypeForValueType(OS, VT);
213 /// RecordListComparator - Provide a determinstic comparator for lists of
216 typedef std::pair<std::vector<Record*>, std::vector<Record*> > RecPair;
217 struct RecordListComparator {
218 bool operator()(const RecPair &LHS,
219 const RecPair &RHS) const {
221 const std::vector<Record*> *LHSVec = &LHS.first;
222 const std::vector<Record*> *RHSVec = &RHS.first;
223 unsigned RHSSize = RHSVec->size();
224 unsigned LHSSize = LHSVec->size();
227 if (i == RHSSize) return false; // RHS is shorter than LHS.
228 if ((*LHSVec)[i] != (*RHSVec)[i])
229 return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
230 } while (++i != LHSSize);
232 if (i != RHSSize) return true;
235 LHSVec = &LHS.second;
236 RHSVec = &RHS.second;
237 RHSSize = RHSVec->size();
238 LHSSize = LHSVec->size();
240 for (i = 0; i != LHSSize; ++i) {
241 if (i == RHSSize) return false; // RHS is shorter than LHS.
242 if ((*LHSVec)[i] != (*RHSVec)[i])
243 return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
251 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints,
253 OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
254 OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
255 OS << " switch (ID) {\n";
256 OS << " default: assert(0 && \"Invalid intrinsic!\");\n";
258 // This checking can emit a lot of very common code. To reduce the amount of
259 // code that we emit, batch up cases that have identical types. This avoids
260 // problems where GCC can run out of memory compiling Verifier.cpp.
261 typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
262 MapTy UniqueArgInfos;
264 // Compute the unique argument type info.
265 for (unsigned i = 0, e = Ints.size(); i != e; ++i)
266 UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
267 Ints[i].IS.ParamTypeDefs)].push_back(i);
269 // Loop through the array, emitting one comparison for each batch.
270 for (MapTy::iterator I = UniqueArgInfos.begin(),
271 E = UniqueArgInfos.end(); I != E; ++I) {
272 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
273 OS << " case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
274 << Ints[I->second[i]].Name << "\n";
276 const RecPair &ArgTypes = I->first;
277 const std::vector<Record*> &RetTys = ArgTypes.first;
278 const std::vector<Record*> &ParamTys = ArgTypes.second;
280 OS << " VerifyIntrinsicPrototype(ID, IF, " << RetTys.size() << ", "
283 // Emit return types.
284 for (unsigned j = 0, je = RetTys.size(); j != je; ++j) {
285 Record *ArgType = RetTys[j];
288 if (ArgType->isSubClassOf("LLVMMatchType")) {
289 unsigned Number = ArgType->getValueAsInt("Number");
290 assert(Number < j && "Invalid matching number!");
291 if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
292 OS << "~(ExtendedElementVectorType | " << Number << ")";
293 else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
294 OS << "~(TruncatedElementVectorType | " << Number << ")";
298 MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
299 OS << getEnumName(VT);
301 if (VT == MVT::isVoid && j != 0 && j != je - 1)
302 throw "Var arg type not last argument";
306 // Emit the parameter types.
307 for (unsigned j = 0, je = ParamTys.size(); j != je; ++j) {
308 Record *ArgType = ParamTys[j];
311 if (ArgType->isSubClassOf("LLVMMatchType")) {
312 unsigned Number = ArgType->getValueAsInt("Number");
313 assert(Number < j + RetTys.size() && "Invalid matching number!");
314 if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
315 OS << "~(ExtendedElementVectorType | " << Number << ")";
316 else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
317 OS << "~(TruncatedElementVectorType | " << Number << ")";
321 MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
322 OS << getEnumName(VT);
324 if (VT == MVT::isVoid && j != 0 && j != je - 1)
325 throw "Var arg type not last argument";
336 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
338 OS << "// Code for generating Intrinsic function declarations.\n";
339 OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
340 OS << " switch (id) {\n";
341 OS << " default: assert(0 && \"Invalid intrinsic!\");\n";
343 // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
345 typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
346 MapTy UniqueArgInfos;
348 // Compute the unique argument type info.
349 for (unsigned i = 0, e = Ints.size(); i != e; ++i)
350 UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
351 Ints[i].IS.ParamTypeDefs)].push_back(i);
353 // Loop through the array, emitting one generator for each batch.
354 for (MapTy::iterator I = UniqueArgInfos.begin(),
355 E = UniqueArgInfos.end(); I != E; ++I) {
356 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
357 OS << " case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
358 << Ints[I->second[i]].Name << "\n";
360 const RecPair &ArgTypes = I->first;
361 const std::vector<Record*> &RetTys = ArgTypes.first;
362 const std::vector<Record*> &ParamTys = ArgTypes.second;
364 unsigned N = ParamTys.size();
367 getValueType(ParamTys[N - 1]->getValueAsDef("VT")) == MVT::isVoid) {
368 OS << " IsVarArg = true;\n";
373 OS << " ResultTy = ";
374 EmitTypeGenerate(OS, RetTys, ArgNo);
377 for (unsigned j = 0; j != N; ++j) {
378 OS << " ArgTys.push_back(";
379 EmitTypeGenerate(OS, ParamTys[j], ArgNo);
390 void IntrinsicEmitter::
391 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) {
392 OS << "// Add parameter attributes that are not common to all intrinsics.\n";
393 OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
394 OS << " switch (id) {\n";
395 OS << " default: break;\n";
396 for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
397 switch (Ints[i].ModRef) {
399 case CodeGenIntrinsic::NoMem:
400 OS << " case Intrinsic::" << Ints[i].EnumName << ":\n";
404 OS << " Attr |= Attribute::ReadNone; // These do not access memory.\n";
406 for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
407 switch (Ints[i].ModRef) {
409 case CodeGenIntrinsic::ReadArgMem:
410 case CodeGenIntrinsic::ReadMem:
411 OS << " case Intrinsic::" << Ints[i].EnumName << ":\n";
415 OS << " Attr |= Attribute::ReadOnly; // These do not write memory.\n";
421 void IntrinsicEmitter::
422 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
423 OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
424 OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
425 OS << " switch (F->getIntrinsicID()) {\n";
426 OS << " default: BuiltinName = \"\"; break;\n";
427 for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
428 if (!Ints[i].GCCBuiltinName.empty()) {
429 OS << " case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
430 << Ints[i].GCCBuiltinName << "\"; break;\n";
437 /// EmitBuiltinComparisons - Emit comparisons to determine whether the specified
438 /// sorted range of builtin names is equal to the current builtin. This breaks
439 /// it down into a simple tree.
441 /// At this point, we know that all the builtins in the range have the same name
442 /// for the first 'CharStart' characters. Only the end of the name needs to be
444 typedef std::map<std::string, std::string>::const_iterator StrMapIterator;
445 static void EmitBuiltinComparisons(StrMapIterator Start, StrMapIterator End,
446 unsigned CharStart, unsigned Indent,
448 if (Start == End) return; // empty range.
450 // Determine what, if anything, is the same about all these strings.
451 std::string CommonString = Start->first;
452 unsigned NumInRange = 0;
453 for (StrMapIterator I = Start; I != End; ++I, ++NumInRange) {
454 // Find the first character that doesn't match.
455 const std::string &ThisStr = I->first;
456 unsigned NonMatchChar = CharStart;
457 while (NonMatchChar < CommonString.size() &&
458 NonMatchChar < ThisStr.size() &&
459 CommonString[NonMatchChar] == ThisStr[NonMatchChar])
461 // Truncate off pieces that don't match.
462 CommonString.resize(NonMatchChar);
465 // Just compare the rest of the string.
466 if (NumInRange == 1) {
467 if (CharStart != CommonString.size()) {
468 OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
469 if (CharStart) OS << "+" << CharStart;
470 OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
471 OS << CommonString.size() - CharStart << "))\n";
474 OS << std::string(Indent*2, ' ') << "IntrinsicID = Intrinsic::";
475 OS << Start->second << ";\n";
479 // At this point, we potentially have a common prefix for these builtins, emit
480 // a check for this common prefix.
481 if (CommonString.size() != CharStart) {
482 OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
483 if (CharStart) OS << "+" << CharStart;
484 OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
485 OS << CommonString.size()-CharStart << ")) {\n";
487 EmitBuiltinComparisons(Start, End, CommonString.size(), Indent+1, OS);
488 OS << std::string(Indent*2, ' ') << "}\n";
492 // Output a switch on the character that differs across the set.
493 OS << std::string(Indent*2, ' ') << "switch (BuiltinName[" << CharStart
496 OS << " // \"" << std::string(Start->first.begin(),
497 Start->first.begin()+CharStart) << "\"";
500 for (StrMapIterator I = Start; I != End; ) {
501 char ThisChar = I->first[CharStart];
502 OS << std::string(Indent*2, ' ') << "case '" << ThisChar << "':\n";
503 // Figure out the range that has this common character.
504 StrMapIterator NextChar = I;
505 for (++NextChar; NextChar != End && NextChar->first[CharStart] == ThisChar;
508 EmitBuiltinComparisons(I, NextChar, CharStart+1, Indent+1, OS);
509 OS << std::string(Indent*2, ' ') << " break;\n";
512 OS << std::string(Indent*2, ' ') << "}\n";
515 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
516 /// same target, and we already checked it.
517 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
519 // Rearrange the builtins by length.
520 std::vector<std::map<std::string, std::string> > BuiltinsByLen;
521 BuiltinsByLen.reserve(100);
523 for (StrMapIterator I = BIM.begin(), E = BIM.end(); I != E; ++I) {
524 if (I->first.size() >= BuiltinsByLen.size())
525 BuiltinsByLen.resize(I->first.size()+1);
526 BuiltinsByLen[I->first.size()].insert(*I);
529 // Now that we have all the builtins by their length, emit a switch stmt.
530 OS << " switch (strlen(BuiltinName)) {\n";
531 OS << " default: break;\n";
532 for (unsigned i = 0, e = BuiltinsByLen.size(); i != e; ++i) {
533 if (BuiltinsByLen[i].empty()) continue;
534 OS << " case " << i << ":\n";
535 EmitBuiltinComparisons(BuiltinsByLen[i].begin(), BuiltinsByLen[i].end(),
543 void IntrinsicEmitter::
544 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
546 typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
548 for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
549 if (!Ints[i].GCCBuiltinName.empty()) {
550 // Get the map for this target prefix.
551 std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
553 if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
554 Ints[i].EnumName)).second)
555 throw "Intrinsic '" + Ints[i].TheDef->getName() +
556 "': duplicate GCC builtin name!";
560 OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
561 OS << "// This is used by the C front-end. The GCC builtin name is passed\n";
562 OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
563 OS << "// in as TargetPrefix. The result is assigned to 'IntrinsicID'.\n";
564 OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
565 OS << " IntrinsicID = Intrinsic::not_intrinsic;\n";
567 // Note: this could emit significantly better code if we cared.
568 for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
570 if (!I->first.empty())
571 OS << "if (!strcmp(TargetPrefix, \"" << I->first << "\")) ";
573 OS << "/* Target Independent Builtins */ ";
576 // Emit the comparisons for this target prefix.
577 EmitTargetBuiltins(I->second, OS);