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