Implement Regression/TableGen/DagDefSubst.ll
[oota-llvm.git] / utils / TableGen / CodeGenTarget.cpp
1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class wrap 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 <set>
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, const CodeGenTarget *CGT) {
33   MVT::ValueType VT = (MVT::ValueType)Rec->getValueAsInt("Value");
34   if (VT == MVT::iPTR) {
35     assert(CGT && "Use a pointer type in a place that isn't supported yet!");
36     VT = CGT->getPointerType();
37   }
38   return VT;
39 }
40
41 std::string llvm::getName(MVT::ValueType T) {
42   switch (T) {
43   case MVT::Other: return "UNKNOWN";
44   case MVT::i1:    return "i1";
45   case MVT::i8:    return "i8";
46   case MVT::i16:   return "i16";
47   case MVT::i32:   return "i32";
48   case MVT::i64:   return "i64";
49   case MVT::i128:  return "i128";
50   case MVT::f32:   return "f32";
51   case MVT::f64:   return "f64";
52   case MVT::f80:   return "f80";
53   case MVT::f128:  return "f128";
54   case MVT::Flag:  return "Flag";
55   case MVT::isVoid:return "void";
56   case MVT::v8i8:  return "v8i8";
57   case MVT::v4i16: return "v4i16";
58   case MVT::v2i32: return "v2i32";
59   case MVT::v16i8: return "v16i8";
60   case MVT::v8i16: return "v8i16";
61   case MVT::v4i32: return "v4i32";
62   case MVT::v2i64: return "v2i64";
63   case MVT::v2f32: return "v2f32";
64   case MVT::v4f32: return "v4f32";
65   case MVT::v2f64: return "v2f64";
66   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
67   }
68 }
69
70 std::string llvm::getEnumName(MVT::ValueType T) {
71   switch (T) {
72   case MVT::Other: return "Other";
73   case MVT::i1:    return "i1";
74   case MVT::i8:    return "i8";
75   case MVT::i16:   return "i16";
76   case MVT::i32:   return "i32";
77   case MVT::i64:   return "i64";
78   case MVT::i128:  return "i128";
79   case MVT::f32:   return "f32";
80   case MVT::f64:   return "f64";
81   case MVT::f80:   return "f80";
82   case MVT::f128:  return "f128";
83   case MVT::Flag:  return "Flag";
84   case MVT::isVoid:return "isVoid";
85   case MVT::v8i8:  return "v8i8";
86   case MVT::v4i16: return "v4i16";
87   case MVT::v2i32: return "v2i32";
88   case MVT::v16i8: return "v16i8";
89   case MVT::v8i16: return "v8i16";
90   case MVT::v4i32: return "v4i32";
91   case MVT::v2i64: return "v2i64";
92   case MVT::v2f32: return "v2f32";
93   case MVT::v4f32: return "v4f32";
94   case MVT::v2f64: return "v2f64";
95   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
96   }
97 }
98
99
100 std::ostream &llvm::operator<<(std::ostream &OS, MVT::ValueType T) {
101   return OS << getName(T);
102 }
103
104
105 /// getTarget - Return the current instance of the Target class.
106 ///
107 CodeGenTarget::CodeGenTarget() : PointerType(MVT::Other) {
108   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
109   if (Targets.size() == 0)
110     throw std::string("ERROR: No 'Target' subclasses defined!");
111   if (Targets.size() != 1)
112     throw std::string("ERROR: Multiple subclasses of Target defined!");
113   TargetRec = Targets[0];
114
115   // Read in all of the CalleeSavedRegisters.
116   CalleeSavedRegisters =TargetRec->getValueAsListOfDefs("CalleeSavedRegisters");
117   PointerType = getValueType(TargetRec->getValueAsDef("PointerType"));
118 }
119
120
121 const std::string &CodeGenTarget::getName() const {
122   return TargetRec->getName();
123 }
124
125 Record *CodeGenTarget::getInstructionSet() const {
126   return TargetRec->getValueAsDef("InstructionSet");
127 }
128
129 /// getAsmWriter - Return the AssemblyWriter definition for this target.
130 ///
131 Record *CodeGenTarget::getAsmWriter() const {
132   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
133   if (AsmWriterNum >= LI.size())
134     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
135   return LI[AsmWriterNum];
136 }
137
138 void CodeGenTarget::ReadRegisters() const {
139   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
140   if (Regs.empty())
141     throw std::string("No 'Register' subclasses defined!");
142
143   Registers.reserve(Regs.size());
144   Registers.assign(Regs.begin(), Regs.end());
145 }
146
147 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
148   DeclaredSpillSize = R->getValueAsInt("SpillSize");
149   DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
150 }
151
152 const std::string &CodeGenRegister::getName() const {
153   return TheDef->getName();
154 }
155
156 void CodeGenTarget::ReadRegisterClasses() const {
157   std::vector<Record*> RegClasses =
158     Records.getAllDerivedDefinitions("RegisterClass");
159   if (RegClasses.empty())
160     throw std::string("No 'RegisterClass' subclasses defined!");
161
162   RegisterClasses.reserve(RegClasses.size());
163   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
164 }
165
166 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
167   // Rename anonymous register classes.
168   if (R->getName().size() > 9 && R->getName()[9] == '.') {
169     static unsigned AnonCounter = 0;
170     R->setName("AnonRegClass_"+utostr(AnonCounter++));
171   } 
172   
173   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
174   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
175     Record *Type = TypeList[i];
176     if (!Type->isSubClassOf("ValueType"))
177       throw "RegTypes list member '" + Type->getName() +
178         "' does not derive from the ValueType class!";
179     VTs.push_back(getValueType(Type));
180   }
181   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
182   
183   std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
184   for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
185     Record *Reg = RegList[i];
186     if (!Reg->isSubClassOf("Register"))
187       throw "Register Class member '" + Reg->getName() +
188             "' does not derive from the Register class!";
189     Elements.push_back(Reg);
190   }
191   
192   // Allow targets to override the size in bits of the RegisterClass.
193   unsigned Size = R->getValueAsInt("Size");
194
195   Namespace = R->getValueAsString("Namespace");
196   SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
197   SpillAlignment = R->getValueAsInt("Alignment");
198   MethodBodies = R->getValueAsCode("MethodBodies");
199   MethodProtos = R->getValueAsCode("MethodProtos");
200 }
201
202 const std::string &CodeGenRegisterClass::getName() const {
203   return TheDef->getName();
204 }
205
206 void CodeGenTarget::ReadLegalValueTypes() const {
207   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
208   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
209     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
210       LegalValueTypes.push_back(RCs[i].VTs[ri]);
211   
212   // Remove duplicates.
213   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
214   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
215                                     LegalValueTypes.end()),
216                         LegalValueTypes.end());
217 }
218
219
220 void CodeGenTarget::ReadInstructions() const {
221   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
222   if (Insts.size() <= 2)
223     throw std::string("No 'Instruction' subclasses defined!");
224
225   // Parse the instructions defined in the .td file.
226   std::string InstFormatName =
227     getAsmWriter()->getValueAsString("InstFormatName");
228
229   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
230     std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
231     Instructions.insert(std::make_pair(Insts[i]->getName(),
232                                        CodeGenInstruction(Insts[i], AsmStr)));
233   }
234 }
235
236 /// getInstructionsByEnumValue - Return all of the instructions defined by the
237 /// target, ordered by their enum value.
238 void CodeGenTarget::
239 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
240                                                  &NumberedInstructions) {
241   std::map<std::string, CodeGenInstruction>::const_iterator I;
242   I = getInstructions().find("PHI");
243   if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
244   const CodeGenInstruction *PHI = &I->second;
245   
246   I = getInstructions().find("INLINEASM");
247   if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
248   const CodeGenInstruction *INLINEASM = &I->second;
249   
250   // Print out the rest of the instructions now.
251   NumberedInstructions.push_back(PHI);
252   NumberedInstructions.push_back(INLINEASM);
253   for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
254     if (&II->second != PHI &&&II->second != INLINEASM)
255       NumberedInstructions.push_back(&II->second);
256 }
257
258
259 /// isLittleEndianEncoding - Return whether this target encodes its instruction
260 /// in little-endian format, i.e. bits laid out in the order [0..n]
261 ///
262 bool CodeGenTarget::isLittleEndianEncoding() const {
263   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
264 }
265
266 CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)
267   : TheDef(R), AsmString(AsmStr) {
268   Name      = R->getValueAsString("Name");
269   Namespace = R->getValueAsString("Namespace");
270
271   isReturn     = R->getValueAsBit("isReturn");
272   isBranch     = R->getValueAsBit("isBranch");
273   isBarrier    = R->getValueAsBit("isBarrier");
274   isCall       = R->getValueAsBit("isCall");
275   isLoad       = R->getValueAsBit("isLoad");
276   isStore      = R->getValueAsBit("isStore");
277   isTwoAddress = R->getValueAsBit("isTwoAddress");
278   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
279   isCommutable = R->getValueAsBit("isCommutable");
280   isTerminator = R->getValueAsBit("isTerminator");
281   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
282   usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter");
283   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
284   noResults    = R->getValueAsBit("noResults");
285   hasVariableNumberOfOperands = false;
286   
287   DagInit *DI;
288   try {
289     DI = R->getValueAsDag("OperandList");
290   } catch (...) {
291     // Error getting operand list, just ignore it (sparcv9).
292     AsmString.clear();
293     OperandList.clear();
294     return;
295   }
296
297   unsigned MIOperandNo = 0;
298   std::set<std::string> OperandNames;
299   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
300     DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));
301     if (!Arg)
302       throw "Illegal operand for the '" + R->getName() + "' instruction!";
303
304     Record *Rec = Arg->getDef();
305     std::string PrintMethod = "printOperand";
306     unsigned NumOps = 1;
307     DagInit *MIOpInfo = 0;
308     if (Rec->isSubClassOf("Operand")) {
309       PrintMethod = Rec->getValueAsString("PrintMethod");
310       NumOps = Rec->getValueAsInt("NumMIOperands");
311       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
312     } else if (Rec->getName() == "variable_ops") {
313       hasVariableNumberOfOperands = true;
314       continue;
315     } else if (!Rec->isSubClassOf("RegisterClass"))
316       throw "Unknown operand class '" + Rec->getName() +
317             "' in instruction '" + R->getName() + "' instruction!";
318
319     // Check that the operand has a name and that it's unique.
320     if (DI->getArgName(i).empty())
321       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
322         " has no name!";
323     if (!OperandNames.insert(DI->getArgName(i)).second)
324       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
325         " has the same name as a previous operand!";
326     
327     OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, 
328                                       MIOperandNo, NumOps, MIOpInfo));
329     MIOperandNo += NumOps;
330   }
331 }
332
333
334
335 /// getOperandNamed - Return the index of the operand with the specified
336 /// non-empty name.  If the instruction does not have an operand with the
337 /// specified name, throw an exception.
338 ///
339 unsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {
340   assert(!Name.empty() && "Cannot search for operand with no name!");
341   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
342     if (OperandList[i].Name == Name) return i;
343   throw "Instruction '" + TheDef->getName() +
344         "' does not have an operand named '$" + Name + "'!";
345 }
346
347 //===----------------------------------------------------------------------===//
348 // ComplexPattern implementation
349 //
350 ComplexPattern::ComplexPattern(Record *R) {
351   Ty          = ::getValueType(R->getValueAsDef("Ty"));
352   NumOperands = R->getValueAsInt("NumOperands");
353   SelectFunc  = R->getValueAsString("SelectFunc");
354   RootNodes   = R->getValueAsListOfDefs("RootNodes");
355 }
356
357 //===----------------------------------------------------------------------===//
358 // CodeGenIntrinsic Implementation
359 //===----------------------------------------------------------------------===//
360
361 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
362   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
363   
364   std::vector<CodeGenIntrinsic> Result;
365
366   // If we are in the context of a target .td file, get the target info so that
367   // we can decode the current intptr_t.
368   CodeGenTarget *CGT = 0;
369   if (Records.getClass("Target") &&
370       Records.getAllDerivedDefinitions("Target").size() == 1)
371     CGT = new CodeGenTarget();
372   
373   for (unsigned i = 0, e = I.size(); i != e; ++i)
374     Result.push_back(CodeGenIntrinsic(I[i], CGT));
375   delete CGT;
376   return Result;
377 }
378
379 CodeGenIntrinsic::CodeGenIntrinsic(Record *R, CodeGenTarget *CGT) {
380   TheDef = R;
381   std::string DefName = R->getName();
382   ModRef = WriteMem;
383   
384   if (DefName.size() <= 4 || 
385       std::string(DefName.begin(), DefName.begin()+4) != "int_")
386     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
387   EnumName = std::string(DefName.begin()+4, DefName.end());
388   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
389     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
390   TargetPrefix   = R->getValueAsString("TargetPrefix");
391   Name = R->getValueAsString("LLVMName");
392   if (Name == "") {
393     // If an explicit name isn't specified, derive one from the DefName.
394     Name = "llvm.";
395     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
396       if (EnumName[i] == '_')
397         Name += '.';
398       else
399         Name += EnumName[i];
400   } else {
401     // Verify it starts with "llvm.".
402     if (Name.size() <= 5 || 
403         std::string(Name.begin(), Name.begin()+5) != "llvm.")
404       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
405   }
406   
407   // If TargetPrefix is specified, make sure that Name starts with
408   // "llvm.<targetprefix>.".
409   if (!TargetPrefix.empty()) {
410     if (Name.size() < 6+TargetPrefix.size() ||
411         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size()) 
412         != (TargetPrefix+"."))
413       throw "Intrinsic '" + DefName + "' does not start with 'llvm." + 
414         TargetPrefix + ".'!";
415   }
416   
417   // Parse the list of argument types.
418   ListInit *TypeList = R->getValueAsListInit("Types");
419   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
420     DefInit *DI = dynamic_cast<DefInit*>(TypeList->getElement(i));
421     assert(DI && "Invalid list type!");
422     Record *TyEl = DI->getDef();
423     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
424     ArgTypes.push_back(TyEl->getValueAsString("TypeVal"));
425     
426     if (CGT)
427       ArgVTs.push_back(getValueType(TyEl->getValueAsDef("VT"), CGT));
428     ArgTypeDefs.push_back(TyEl);
429   }
430   if (ArgTypes.size() == 0)
431     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
432   
433   // Parse the intrinsic properties.
434   ListInit *PropList = R->getValueAsListInit("Properties");
435   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
436     DefInit *DI = dynamic_cast<DefInit*>(PropList->getElement(i));
437     assert(DI && "Invalid list type!");
438     Record *Property = DI->getDef();
439     assert(Property->isSubClassOf("IntrinsicProperty") &&
440            "Expected a property!");
441     
442     if (Property->getName() == "InstrNoMem")
443       ModRef = NoMem;
444     else if (Property->getName() == "InstrReadArgMem")
445       ModRef = ReadArgMem;
446     else if (Property->getName() == "IntrReadMem")
447       ModRef = ReadMem;
448     else if (Property->getName() == "InstrWriteArgMem")
449       ModRef = WriteArgMem;
450     else if (Property->getName() == "IntrWriteMem")
451       ModRef = WriteMem;
452     else
453       assert(0 && "Unknown property!");
454   }
455 }