Replace all target specific implicit def instructions with a target independent one...
[oota-llvm.git] / utils / TableGen / CodeGenTarget.cpp
1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
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 class wraps target description classes used by the various code
11 // generation TableGen backends.  This makes it easier to access the data and
12 // provides a single place that needs to check it for validity.  All of these
13 // classes throw exceptions on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "Record.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Streams.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 static cl::opt<unsigned>
27 AsmWriterNum("asmwriternum", cl::init(0),
28              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
29
30 /// getValueType - Return the MCV::ValueType that the specified TableGen record
31 /// corresponds to.
32 MVT::ValueType llvm::getValueType(Record *Rec) {
33   return (MVT::ValueType)Rec->getValueAsInt("Value");
34 }
35
36 std::string llvm::getName(MVT::ValueType T) {
37   switch (T) {
38   case MVT::Other: return "UNKNOWN";
39   case MVT::i1:    return "MVT::i1";
40   case MVT::i8:    return "MVT::i8";
41   case MVT::i16:   return "MVT::i16";
42   case MVT::i32:   return "MVT::i32";
43   case MVT::i64:   return "MVT::i64";
44   case MVT::i128:  return "MVT::i128";
45   case MVT::iAny:  return "MVT::iAny";
46   case MVT::fAny:  return "MVT::fAny";
47   case MVT::f32:   return "MVT::f32";
48   case MVT::f64:   return "MVT::f64";
49   case MVT::f80:   return "MVT::f80";
50   case MVT::f128:  return "MVT::f128";
51   case MVT::ppcf128:  return "MVT::ppcf128";
52   case MVT::Flag:  return "MVT::Flag";
53   case MVT::isVoid:return "MVT::void";
54   case MVT::v8i8:  return "MVT::v8i8";
55   case MVT::v4i16: return "MVT::v4i16";
56   case MVT::v2i32: return "MVT::v2i32";
57   case MVT::v1i64: return "MVT::v1i64";
58   case MVT::v16i8: return "MVT::v16i8";
59   case MVT::v8i16: return "MVT::v8i16";
60   case MVT::v4i32: return "MVT::v4i32";
61   case MVT::v2i64: return "MVT::v2i64";
62   case MVT::v2f32: return "MVT::v2f32";
63   case MVT::v4f32: return "MVT::v4f32";
64   case MVT::v2f64: return "MVT::v2f64";
65   case MVT::v3i32: return "MVT::v3i32";
66   case MVT::v3f32: return "MVT::v3f32";
67   case MVT::iPTR:  return "TLI.getPointerTy()";
68   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
69   }
70 }
71
72 std::string llvm::getEnumName(MVT::ValueType T) {
73   switch (T) {
74   case MVT::Other: return "MVT::Other";
75   case MVT::i1:    return "MVT::i1";
76   case MVT::i8:    return "MVT::i8";
77   case MVT::i16:   return "MVT::i16";
78   case MVT::i32:   return "MVT::i32";
79   case MVT::i64:   return "MVT::i64";
80   case MVT::i128:  return "MVT::i128";
81   case MVT::iAny:  return "MVT::iAny";
82   case MVT::fAny:  return "MVT::fAny";
83   case MVT::f32:   return "MVT::f32";
84   case MVT::f64:   return "MVT::f64";
85   case MVT::f80:   return "MVT::f80";
86   case MVT::f128:  return "MVT::f128";
87   case MVT::ppcf128:  return "MVT::ppcf128";
88   case MVT::Flag:  return "MVT::Flag";
89   case MVT::isVoid:return "MVT::isVoid";
90   case MVT::v8i8:  return "MVT::v8i8";
91   case MVT::v4i16: return "MVT::v4i16";
92   case MVT::v2i32: return "MVT::v2i32";
93   case MVT::v1i64: return "MVT::v1i64";
94   case MVT::v16i8: return "MVT::v16i8";
95   case MVT::v8i16: return "MVT::v8i16";
96   case MVT::v4i32: return "MVT::v4i32";
97   case MVT::v2i64: return "MVT::v2i64";
98   case MVT::v2f32: return "MVT::v2f32";
99   case MVT::v4f32: return "MVT::v4f32";
100   case MVT::v2f64: return "MVT::v2f64";
101   case MVT::v3i32: return "MVT::v3i32";
102   case MVT::v3f32: return "MVT::v3f32";
103   case MVT::iPTR:  return "MVT::iPTR";
104   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
105   }
106 }
107
108 /// getQualifiedName - Return the name of the specified record, with a
109 /// namespace qualifier if the record contains one.
110 ///
111 std::string llvm::getQualifiedName(const Record *R) {
112   std::string Namespace = R->getValueAsString("Namespace");
113   if (Namespace.empty()) return R->getName();
114   return Namespace + "::" + R->getName();
115 }
116
117
118
119
120 /// getTarget - Return the current instance of the Target class.
121 ///
122 CodeGenTarget::CodeGenTarget() {
123   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
124   if (Targets.size() == 0)
125     throw std::string("ERROR: No 'Target' subclasses defined!");
126   if (Targets.size() != 1)
127     throw std::string("ERROR: Multiple subclasses of Target defined!");
128   TargetRec = Targets[0];
129 }
130
131
132 const std::string &CodeGenTarget::getName() const {
133   return TargetRec->getName();
134 }
135
136 Record *CodeGenTarget::getInstructionSet() const {
137   return TargetRec->getValueAsDef("InstructionSet");
138 }
139
140 /// getAsmWriter - Return the AssemblyWriter definition for this target.
141 ///
142 Record *CodeGenTarget::getAsmWriter() const {
143   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
144   if (AsmWriterNum >= LI.size())
145     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
146   return LI[AsmWriterNum];
147 }
148
149 void CodeGenTarget::ReadRegisters() const {
150   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
151   if (Regs.empty())
152     throw std::string("No 'Register' subclasses defined!");
153
154   Registers.reserve(Regs.size());
155   Registers.assign(Regs.begin(), Regs.end());
156 }
157
158 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
159   DeclaredSpillSize = R->getValueAsInt("SpillSize");
160   DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
161 }
162
163 const std::string &CodeGenRegister::getName() const {
164   return TheDef->getName();
165 }
166
167 void CodeGenTarget::ReadRegisterClasses() const {
168   std::vector<Record*> RegClasses =
169     Records.getAllDerivedDefinitions("RegisterClass");
170   if (RegClasses.empty())
171     throw std::string("No 'RegisterClass' subclasses defined!");
172
173   RegisterClasses.reserve(RegClasses.size());
174   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
175 }
176
177 std::vector<unsigned char> CodeGenTarget::getRegisterVTs(Record *R) const {
178   std::vector<unsigned char> Result;
179   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
180   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
181     const CodeGenRegisterClass &RC = RegisterClasses[i];
182     for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
183       if (R == RC.Elements[ei]) {
184         const std::vector<MVT::ValueType> &InVTs = RC.getValueTypes();
185         for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
186           Result.push_back(InVTs[i]);
187       }
188     }
189   }
190   return Result;
191 }
192
193
194 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
195   // Rename anonymous register classes.
196   if (R->getName().size() > 9 && R->getName()[9] == '.') {
197     static unsigned AnonCounter = 0;
198     R->setName("AnonRegClass_"+utostr(AnonCounter++));
199   } 
200   
201   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
202   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
203     Record *Type = TypeList[i];
204     if (!Type->isSubClassOf("ValueType"))
205       throw "RegTypes list member '" + Type->getName() +
206         "' does not derive from the ValueType class!";
207     VTs.push_back(getValueType(Type));
208   }
209   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
210   
211   std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
212   for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
213     Record *Reg = RegList[i];
214     if (!Reg->isSubClassOf("Register"))
215       throw "Register Class member '" + Reg->getName() +
216             "' does not derive from the Register class!";
217     Elements.push_back(Reg);
218   }
219   
220   std::vector<Record*> SubRegClassList = 
221                         R->getValueAsListOfDefs("SubRegClassList");
222   for (unsigned i = 0, e = SubRegClassList.size(); i != e; ++i) {
223     Record *SubRegClass = SubRegClassList[i];
224     if (!SubRegClass->isSubClassOf("RegisterClass"))
225       throw "Register Class member '" + SubRegClass->getName() +
226             "' does not derive from the RegisterClass class!";
227     SubRegClasses.push_back(SubRegClass);
228   }  
229   
230   // Allow targets to override the size in bits of the RegisterClass.
231   unsigned Size = R->getValueAsInt("Size");
232
233   Namespace = R->getValueAsString("Namespace");
234   SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
235   SpillAlignment = R->getValueAsInt("Alignment");
236   CopyCost = R->getValueAsInt("CopyCost");
237   MethodBodies = R->getValueAsCode("MethodBodies");
238   MethodProtos = R->getValueAsCode("MethodProtos");
239 }
240
241 const std::string &CodeGenRegisterClass::getName() const {
242   return TheDef->getName();
243 }
244
245 void CodeGenTarget::ReadLegalValueTypes() const {
246   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
247   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
248     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
249       LegalValueTypes.push_back(RCs[i].VTs[ri]);
250   
251   // Remove duplicates.
252   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
253   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
254                                     LegalValueTypes.end()),
255                         LegalValueTypes.end());
256 }
257
258
259 void CodeGenTarget::ReadInstructions() const {
260   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
261   if (Insts.size() <= 2)
262     throw std::string("No 'Instruction' subclasses defined!");
263
264   // Parse the instructions defined in the .td file.
265   std::string InstFormatName =
266     getAsmWriter()->getValueAsString("InstFormatName");
267
268   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
269     std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
270     Instructions.insert(std::make_pair(Insts[i]->getName(),
271                                        CodeGenInstruction(Insts[i], AsmStr)));
272   }
273 }
274
275 /// getInstructionsByEnumValue - Return all of the instructions defined by the
276 /// target, ordered by their enum value.
277 void CodeGenTarget::
278 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
279                                                  &NumberedInstructions) {
280   std::map<std::string, CodeGenInstruction>::const_iterator I;
281   I = getInstructions().find("PHI");
282   if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
283   const CodeGenInstruction *PHI = &I->second;
284   
285   I = getInstructions().find("INLINEASM");
286   if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
287   const CodeGenInstruction *INLINEASM = &I->second;
288   
289   I = getInstructions().find("LABEL");
290   if (I == Instructions.end()) throw "Could not find 'LABEL' instruction!";
291   const CodeGenInstruction *LABEL = &I->second;
292   
293   I = getInstructions().find("DECLARE");
294   if (I == Instructions.end()) throw "Could not find 'DECLARE' instruction!";
295   const CodeGenInstruction *DECLARE = &I->second;
296   
297   I = getInstructions().find("EXTRACT_SUBREG");
298   if (I == Instructions.end()) 
299     throw "Could not find 'EXTRACT_SUBREG' instruction!";
300   const CodeGenInstruction *EXTRACT_SUBREG = &I->second;
301   
302   I = getInstructions().find("INSERT_SUBREG");
303   if (I == Instructions.end()) 
304     throw "Could not find 'INSERT_SUBREG' instruction!";
305   const CodeGenInstruction *INSERT_SUBREG = &I->second;
306   
307   I = getInstructions().find("IMPLICIT_DEF");
308   if (I == Instructions.end())
309     throw "Could not find 'IMPLICIT_DEF' instruction!";
310   const CodeGenInstruction *IMPLICIT_DEF = &I->second;
311   
312   // Print out the rest of the instructions now.
313   NumberedInstructions.push_back(PHI);
314   NumberedInstructions.push_back(INLINEASM);
315   NumberedInstructions.push_back(LABEL);
316   NumberedInstructions.push_back(DECLARE);
317   NumberedInstructions.push_back(EXTRACT_SUBREG);
318   NumberedInstructions.push_back(INSERT_SUBREG);
319   NumberedInstructions.push_back(IMPLICIT_DEF);
320   for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
321     if (&II->second != PHI &&
322         &II->second != INLINEASM &&
323         &II->second != LABEL &&
324         &II->second != DECLARE &&
325         &II->second != EXTRACT_SUBREG &&
326         &II->second != INSERT_SUBREG &&
327         &II->second != IMPLICIT_DEF)
328       NumberedInstructions.push_back(&II->second);
329 }
330
331
332 /// isLittleEndianEncoding - Return whether this target encodes its instruction
333 /// in little-endian format, i.e. bits laid out in the order [0..n]
334 ///
335 bool CodeGenTarget::isLittleEndianEncoding() const {
336   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
337 }
338
339 //===----------------------------------------------------------------------===//
340 // ComplexPattern implementation
341 //
342 ComplexPattern::ComplexPattern(Record *R) {
343   Ty          = ::getValueType(R->getValueAsDef("Ty"));
344   NumOperands = R->getValueAsInt("NumOperands");
345   SelectFunc  = R->getValueAsString("SelectFunc");
346   RootNodes   = R->getValueAsListOfDefs("RootNodes");
347
348   // Parse the properties.
349   Properties = 0;
350   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
351   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
352     if (PropList[i]->getName() == "SDNPHasChain") {
353       Properties |= 1 << SDNPHasChain;
354     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
355       Properties |= 1 << SDNPOptInFlag;
356     } else if (PropList[i]->getName() == "SDNPMayStore") {
357       Properties |= 1 << SDNPMayStore;
358     } else if (PropList[i]->getName() == "SDNPMayLoad") {
359       Properties |= 1 << SDNPMayLoad;
360     } else if (PropList[i]->getName() == "SDNPSideEffect") {
361       Properties |= 1 << SDNPSideEffect;
362     } else {
363       cerr << "Unsupported SD Node property '" << PropList[i]->getName()
364            << "' on ComplexPattern '" << R->getName() << "'!\n";
365       exit(1);
366     }
367   
368   // Parse the attributes.  
369   Attributes = 0;
370   PropList = R->getValueAsListOfDefs("Attributes");
371   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
372     if (PropList[i]->getName() == "CPAttrParentAsRoot") {
373       Attributes |= 1 << CPAttrParentAsRoot;
374     } else {
375       cerr << "Unsupported pattern attribute '" << PropList[i]->getName()
376            << "' on ComplexPattern '" << R->getName() << "'!\n";
377       exit(1);
378     }
379 }
380
381 //===----------------------------------------------------------------------===//
382 // CodeGenIntrinsic Implementation
383 //===----------------------------------------------------------------------===//
384
385 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
386   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
387   
388   std::vector<CodeGenIntrinsic> Result;
389
390   // If we are in the context of a target .td file, get the target info so that
391   // we can decode the current intptr_t.
392   CodeGenTarget *CGT = 0;
393   if (Records.getClass("Target") &&
394       Records.getAllDerivedDefinitions("Target").size() == 1)
395     CGT = new CodeGenTarget();
396   
397   for (unsigned i = 0, e = I.size(); i != e; ++i)
398     Result.push_back(CodeGenIntrinsic(I[i], CGT));
399   delete CGT;
400   return Result;
401 }
402
403 CodeGenIntrinsic::CodeGenIntrinsic(Record *R, CodeGenTarget *CGT) {
404   TheDef = R;
405   std::string DefName = R->getName();
406   ModRef = WriteMem;
407   isOverloaded = false;
408   
409   if (DefName.size() <= 4 || 
410       std::string(DefName.begin(), DefName.begin()+4) != "int_")
411     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
412   EnumName = std::string(DefName.begin()+4, DefName.end());
413   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
414     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
415   TargetPrefix   = R->getValueAsString("TargetPrefix");
416   Name = R->getValueAsString("LLVMName");
417   if (Name == "") {
418     // If an explicit name isn't specified, derive one from the DefName.
419     Name = "llvm.";
420     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
421       if (EnumName[i] == '_')
422         Name += '.';
423       else
424         Name += EnumName[i];
425   } else {
426     // Verify it starts with "llvm.".
427     if (Name.size() <= 5 || 
428         std::string(Name.begin(), Name.begin()+5) != "llvm.")
429       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
430   }
431   
432   // If TargetPrefix is specified, make sure that Name starts with
433   // "llvm.<targetprefix>.".
434   if (!TargetPrefix.empty()) {
435     if (Name.size() < 6+TargetPrefix.size() ||
436         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size()) 
437         != (TargetPrefix+"."))
438       throw "Intrinsic '" + DefName + "' does not start with 'llvm." + 
439         TargetPrefix + ".'!";
440   }
441   
442   // Parse the list of argument types.
443   ListInit *TypeList = R->getValueAsListInit("Types");
444   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
445     Record *TyEl = TypeList->getElementAsRecord(i);
446     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
447     MVT::ValueType VT = getValueType(TyEl->getValueAsDef("VT"));
448     isOverloaded |= VT == MVT::iAny || VT == MVT::fAny;
449     ArgVTs.push_back(VT);
450     ArgTypeDefs.push_back(TyEl);
451   }
452   if (ArgVTs.size() == 0)
453     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
454
455   
456   // Parse the intrinsic properties.
457   ListInit *PropList = R->getValueAsListInit("Properties");
458   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
459     Record *Property = PropList->getElementAsRecord(i);
460     assert(Property->isSubClassOf("IntrinsicProperty") &&
461            "Expected a property!");
462     
463     if (Property->getName() == "IntrNoMem")
464       ModRef = NoMem;
465     else if (Property->getName() == "IntrReadArgMem")
466       ModRef = ReadArgMem;
467     else if (Property->getName() == "IntrReadMem")
468       ModRef = ReadMem;
469     else if (Property->getName() == "IntrWriteArgMem")
470       ModRef = WriteArgMem;
471     else if (Property->getName() == "IntrWriteMem")
472       ModRef = WriteMem;
473     else
474       assert(0 && "Unknown property!");
475   }
476 }