278a1eefb8649601d87ec24e8c96b1c071c77710
[oota-llvm.git] / utils / TableGen / IntrinsicEmitter.cpp
1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits information about intrinsic functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "IntrinsicEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 using namespace llvm;
18
19 //===----------------------------------------------------------------------===//
20 // CodeGenIntrinsic Implementation
21 //===----------------------------------------------------------------------===//
22
23 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
24   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
25   return std::vector<CodeGenIntrinsic>(I.begin(), I.end());
26 }
27
28 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
29   std::string DefName = R->getName();
30   ModRef = WriteMem;
31   
32   if (DefName.size() <= 4 || 
33       std::string(DefName.begin(), DefName.begin()+4) != "int_")
34     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
35   EnumName = std::string(DefName.begin()+4, DefName.end());
36   GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
37   TargetPrefix   = R->getValueAsString("TargetPrefix");
38   Name = R->getValueAsString("LLVMName");
39   if (Name == "") {
40     // If an explicit name isn't specified, derive one from the DefName.
41     Name = "llvm.";
42     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
43       if (EnumName[i] == '_')
44         Name += '.';
45       else
46         Name += EnumName[i];
47   } else {
48     // Verify it starts with "llvm.".
49     if (Name.size() <= 5 || 
50         std::string(Name.begin(), Name.begin()+5) != "llvm.")
51       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
52   }
53   
54   // If TargetPrefix is specified, make sure that Name starts with
55   // "llvm.<targetprefix>.".
56   if (!TargetPrefix.empty()) {
57     if (Name.size() < 6+TargetPrefix.size() ||
58         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size()) 
59           != (TargetPrefix+"."))
60       throw "Intrinsic '" + DefName + "' does not start with 'llvm." + 
61             TargetPrefix + ".'!";
62   }
63   
64   // Parse the list of argument types.
65   ListInit *TypeList = R->getValueAsListInit("Types");
66   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
67     DefInit *DI = dynamic_cast<DefInit*>(TypeList->getElement(i));
68     assert(DI && "Invalid list type!");
69     Record *TyEl = DI->getDef();
70     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
71     ArgTypes.push_back(TyEl->getValueAsString("TypeVal"));
72     ArgTypeDefs.push_back(TyEl);
73   }
74   if (ArgTypes.size() == 0)
75     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
76   
77   // Parse the intrinsic properties.
78   ListInit *PropList = R->getValueAsListInit("Properties");
79   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
80     DefInit *DI = dynamic_cast<DefInit*>(PropList->getElement(i));
81     assert(DI && "Invalid list type!");
82     Record *Property = DI->getDef();
83     assert(Property->isSubClassOf("IntrinsicProperty") &&
84            "Expected a property!");
85
86     if (Property->getName() == "InstrNoMem")
87       ModRef = NoMem;
88     else if (Property->getName() == "InstrReadArgMem")
89       ModRef = ReadArgMem;
90     else if (Property->getName() == "IntrReadMem")
91       ModRef = ReadMem;
92     else if (Property->getName() == "InstrWriteArgMem")
93       ModRef = WriteArgMem;
94     else if (Property->getName() == "IntrWriteMem")
95       ModRef = WriteMem;
96     else
97       assert(0 && "Unknown property!");
98   }
99 }
100
101 //===----------------------------------------------------------------------===//
102 // IntrinsicEmitter Implementation
103 //===----------------------------------------------------------------------===//
104
105 void IntrinsicEmitter::run(std::ostream &OS) {
106   EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
107   
108   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records);
109
110   // Emit the enum information.
111   EmitEnumInfo(Ints, OS);
112   
113   // Emit the function name recognizer.
114   EmitFnNameRecognizer(Ints, OS);
115
116   // Emit the intrinsic verifier.
117   EmitVerifier(Ints, OS);
118   
119   // Emit mod/ref info for each function.
120   EmitModRefInfo(Ints, OS);
121   
122   // Emit side effect info for each function.
123   EmitSideEffectInfo(Ints, OS);
124
125   // Emit a list of intrinsics with corresponding GCC builtins.
126   EmitGCCBuiltinList(Ints, OS);
127
128   // Emit code to translate GCC builtins into LLVM intrinsics.
129   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
130 }
131
132 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
133                                     std::ostream &OS) {
134   OS << "// Enum values for Intrinsics.h\n";
135   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
136   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
137     OS << "    " << Ints[i].EnumName;
138     OS << ((i != e-1) ? ", " : "  ");
139     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
140       << "// " << Ints[i].Name << "\n";
141   }
142   OS << "#endif\n\n";
143 }
144
145 void IntrinsicEmitter::
146 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
147                      std::ostream &OS) {
148   // Build a function name -> intrinsic name mapping.
149   std::map<std::string, std::string> IntMapping;
150   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
151     IntMapping[Ints[i].Name] = Ints[i].EnumName;
152     
153   OS << "// Function name -> enum value recognizer code.\n";
154   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
155   OS << "  switch (Name[5]) {\n";
156   OS << "  default: break;\n";
157   // Emit the intrinsics in sorted order.
158   char LastChar = 0;
159   for (std::map<std::string, std::string>::iterator I = IntMapping.begin(),
160        E = IntMapping.end(); I != E; ++I) {
161     assert(I->first.size() > 5 && std::string(I->first.begin(),
162                                               I->first.begin()+5) == "llvm." &&
163            "Invalid intrinsic name!");
164     if (I->first[5] != LastChar) {
165       LastChar = I->first[5];
166       OS << "  case '" << LastChar << "':\n";
167     }
168     
169     OS << "    if (Name == \"" << I->first << "\") return Intrinsic::"
170        << I->second << ";\n";
171   }
172   OS << "  }\n";
173   OS << "  // The 'llvm.' namespace is reserved!\n";
174   OS << "  assert(0 && \"Unknown LLVM intrinsic function!\");\n";
175   OS << "#endif\n\n";
176 }
177
178 static void EmitTypeVerify(std::ostream &OS, const std::string &Val,
179                            Record *ArgType) {
180   OS << "    Assert1(" << Val << "->getTypeID() == "
181      << ArgType->getValueAsString("TypeVal") << ",\n"
182      << "            \"Illegal intrinsic type!\", IF);\n";
183
184   // If this is a packed type, check that the subtype and size are correct.
185   if (ArgType->isSubClassOf("LLVMPackedType")) {
186     Record *SubType = ArgType->getValueAsDef("ElTy");
187     OS << "    Assert1(cast<PackedType>(" << Val
188        << ")->getElementType()->getTypeID() == "
189        << SubType->getValueAsString("TypeVal") << ",\n"
190        << "            \"Illegal intrinsic type!\", IF);\n";
191     OS << "    Assert1(cast<PackedType>(" << Val << ")->getNumElements() == "
192        << ArgType->getValueAsInt("NumElts") << ",\n"
193        << "            \"Illegal intrinsic type!\", IF);\n";
194   }
195 }
196
197 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
198                                     std::ostream &OS) {
199   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
200   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
201   OS << "  switch (ID) {\n";
202   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
203   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
204     OS << "  case Intrinsic::" << Ints[i].EnumName << ":\t\t// "
205        << Ints[i].Name << "\n";
206     OS << "    Assert1(FTy->getNumParams() == " << Ints[i].ArgTypes.size()-1
207        << ",\n"
208        << "            \"Illegal # arguments for intrinsic function!\", IF);\n";
209     EmitTypeVerify(OS, "FTy->getReturnType()", Ints[i].ArgTypeDefs[0]);
210     for (unsigned j = 1; j != Ints[i].ArgTypes.size(); ++j)
211       EmitTypeVerify(OS, "FTy->getParamType(" + utostr(j-1) + ")",
212                      Ints[i].ArgTypeDefs[j]);
213     OS << "    break;\n";
214   }
215   OS << "  }\n";
216   OS << "#endif\n\n";
217 }
218
219 void IntrinsicEmitter::EmitModRefInfo(const std::vector<CodeGenIntrinsic> &Ints,
220                                       std::ostream &OS) {
221   OS << "// BasicAliasAnalysis code.\n";
222   OS << "#ifdef GET_MODREF_BEHAVIOR\n";
223   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
224     switch (Ints[i].ModRef) {
225     default: break;
226     case CodeGenIntrinsic::NoMem:
227       OS << "  NoMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
228       break;
229     case CodeGenIntrinsic::ReadArgMem:
230     case CodeGenIntrinsic::ReadMem:
231       OS << "  OnlyReadsMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
232       break;
233     }
234   }
235   OS << "#endif\n\n";
236 }
237
238 void IntrinsicEmitter::
239 EmitSideEffectInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
240   OS << "// isInstructionTriviallyDead code.\n";
241   OS << "#ifdef GET_SIDE_EFFECT_INFO\n";
242   OS << "  switch (F->getIntrinsicID()) {\n";
243   OS << "  default: break;\n";
244   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
245     switch (Ints[i].ModRef) {
246     default: break;
247     case CodeGenIntrinsic::NoMem:
248     case CodeGenIntrinsic::ReadArgMem:
249     case CodeGenIntrinsic::ReadMem:
250       OS << "  case Intrinsic::" << Ints[i].EnumName << ":\n";
251       break;
252     }
253   }
254   OS << "    return true; // These intrinsics have no side effects.\n";
255   OS << "  }\n";
256   OS << "#endif\n\n";
257 }
258
259 void IntrinsicEmitter::
260 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
261   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
262   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
263   OS << "  switch (F->getIntrinsicID()) {\n";
264   OS << "  default: BuiltinName = \"\"; break;\n";
265   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
266     if (!Ints[i].GCCBuiltinName.empty()) {
267       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
268          << Ints[i].GCCBuiltinName << "\"; break;\n";
269     }
270   }
271   OS << "  }\n";
272   OS << "#endif\n\n";
273 }
274
275 void IntrinsicEmitter::
276 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
277                              std::ostream &OS) {
278   typedef std::map<std::pair<std::string, std::string>, std::string> BIMTy;
279   BIMTy BuiltinMap;
280   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
281     if (!Ints[i].GCCBuiltinName.empty()) {
282       std::pair<std::string, std::string> Key(Ints[i].GCCBuiltinName,
283                                               Ints[i].TargetPrefix);
284       if (!BuiltinMap.insert(std::make_pair(Key, Ints[i].EnumName)).second)
285         throw "Intrinsic '" + Ints[i].TheDef->getName() +
286               "': duplicate GCC builtin name!";
287     }
288   }
289   
290   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
291   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
292   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
293   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
294   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
295   OS << "  if (0);\n";
296   // Note: this could emit significantly better code if we cared.
297   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
298     OS << "  else if (";
299     if (!I->first.second.empty()) {
300       // Emit this as a strcmp, so it can be constant folded by the FE.
301       OS << "!strcmp(TargetPrefix, \"" << I->first.second << "\") &&\n"
302          << "           ";
303     }
304     OS << "!strcmp(BuiltinName, \"" << I->first.first << "\"))\n";
305     OS << "    IntrinsicID = Intrinsic::" << I->second << "\";\n";
306   }
307   OS << "  else\n";
308   OS << "    IntrinsicID = Intrinsic::not_intrinsic;\n";
309   OS << "#endif\n\n";
310 }