This is the patch to provide clean intrinsic function overloading support in LLVM...
[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 "llvm/Support/Streams.h"
23 #include <set>
24 #include <algorithm>
25 using namespace llvm;
26
27 static cl::opt<unsigned>
28 AsmWriterNum("asmwriternum", cl::init(0),
29              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
30
31 /// getValueType - Return the MCV::ValueType that the specified TableGen record
32 /// corresponds to.
33 MVT::ValueType llvm::getValueType(Record *Rec) {
34   return (MVT::ValueType)Rec->getValueAsInt("Value");
35 }
36
37 std::string llvm::getName(MVT::ValueType T) {
38   switch (T) {
39   case MVT::Other: return "UNKNOWN";
40   case MVT::i1:    return "MVT::i1";
41   case MVT::i8:    return "MVT::i8";
42   case MVT::i16:   return "MVT::i16";
43   case MVT::i32:   return "MVT::i32";
44   case MVT::i64:   return "MVT::i64";
45   case MVT::i128:  return "MVT::i128";
46   case MVT::iAny:  return "MVT::iAny";
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::Flag:  return "MVT::Flag";
52   case MVT::isVoid:return "MVT::void";
53   case MVT::v8i8:  return "MVT::v8i8";
54   case MVT::v4i16: return "MVT::v4i16";
55   case MVT::v2i32: return "MVT::v2i32";
56   case MVT::v1i64: return "MVT::v1i64";
57   case MVT::v16i8: return "MVT::v16i8";
58   case MVT::v8i16: return "MVT::v8i16";
59   case MVT::v4i32: return "MVT::v4i32";
60   case MVT::v2i64: return "MVT::v2i64";
61   case MVT::v2f32: return "MVT::v2f32";
62   case MVT::v4f32: return "MVT::v4f32";
63   case MVT::v2f64: return "MVT::v2f64";
64   case MVT::v3i32: return "MVT::v3i32";
65   case MVT::v3f32: return "MVT::v3f32";
66   case MVT::iPTR:  return "TLI.getPointerTy()";
67   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
68   }
69 }
70
71 std::string llvm::getEnumName(MVT::ValueType T) {
72   switch (T) {
73   case MVT::Other: return "MVT::Other";
74   case MVT::i1:    return "MVT::i1";
75   case MVT::i8:    return "MVT::i8";
76   case MVT::i16:   return "MVT::i16";
77   case MVT::i32:   return "MVT::i32";
78   case MVT::i64:   return "MVT::i64";
79   case MVT::i128:  return "MVT::i128";
80   case MVT::iAny:  return "MVT::iAny";
81   case MVT::f32:   return "MVT::f32";
82   case MVT::f64:   return "MVT::f64";
83   case MVT::f80:   return "MVT::f80";
84   case MVT::f128:  return "MVT::f128";
85   case MVT::Flag:  return "MVT::Flag";
86   case MVT::isVoid:return "MVT::isVoid";
87   case MVT::v8i8:  return "MVT::v8i8";
88   case MVT::v4i16: return "MVT::v4i16";
89   case MVT::v2i32: return "MVT::v2i32";
90   case MVT::v1i64: return "MVT::v1i64";
91   case MVT::v16i8: return "MVT::v16i8";
92   case MVT::v8i16: return "MVT::v8i16";
93   case MVT::v4i32: return "MVT::v4i32";
94   case MVT::v2i64: return "MVT::v2i64";
95   case MVT::v2f32: return "MVT::v2f32";
96   case MVT::v4f32: return "MVT::v4f32";
97   case MVT::v2f64: return "MVT::v2f64";
98   case MVT::v3i32: return "MVT::v3i32";
99   case MVT::v3f32: return "MVT::v3f32";
100   case MVT::iPTR:  return "MVT::iPTR";
101   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
102   }
103 }
104
105
106 /// getTarget - Return the current instance of the Target class.
107 ///
108 CodeGenTarget::CodeGenTarget() {
109   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
110   if (Targets.size() == 0)
111     throw std::string("ERROR: No 'Target' subclasses defined!");
112   if (Targets.size() != 1)
113     throw std::string("ERROR: Multiple subclasses of Target defined!");
114   TargetRec = Targets[0];
115 }
116
117
118 const std::string &CodeGenTarget::getName() const {
119   return TargetRec->getName();
120 }
121
122 Record *CodeGenTarget::getInstructionSet() const {
123   return TargetRec->getValueAsDef("InstructionSet");
124 }
125
126 /// getAsmWriter - Return the AssemblyWriter definition for this target.
127 ///
128 Record *CodeGenTarget::getAsmWriter() const {
129   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
130   if (AsmWriterNum >= LI.size())
131     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
132   return LI[AsmWriterNum];
133 }
134
135 void CodeGenTarget::ReadRegisters() const {
136   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
137   if (Regs.empty())
138     throw std::string("No 'Register' subclasses defined!");
139
140   Registers.reserve(Regs.size());
141   Registers.assign(Regs.begin(), Regs.end());
142 }
143
144 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
145   DeclaredSpillSize = R->getValueAsInt("SpillSize");
146   DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
147 }
148
149 const std::string &CodeGenRegister::getName() const {
150   return TheDef->getName();
151 }
152
153 void CodeGenTarget::ReadRegisterClasses() const {
154   std::vector<Record*> RegClasses =
155     Records.getAllDerivedDefinitions("RegisterClass");
156   if (RegClasses.empty())
157     throw std::string("No 'RegisterClass' subclasses defined!");
158
159   RegisterClasses.reserve(RegClasses.size());
160   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
161 }
162
163 std::vector<unsigned char> CodeGenTarget::getRegisterVTs(Record *R) const {
164   std::vector<unsigned char> Result;
165   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
166   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
167     const CodeGenRegisterClass &RC = RegisterClasses[i];
168     for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
169       if (R == RC.Elements[ei]) {
170         const std::vector<MVT::ValueType> &InVTs = RC.getValueTypes();
171         for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
172           Result.push_back(InVTs[i]);
173       }
174     }
175   }
176   return Result;
177 }
178
179
180 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
181   // Rename anonymous register classes.
182   if (R->getName().size() > 9 && R->getName()[9] == '.') {
183     static unsigned AnonCounter = 0;
184     R->setName("AnonRegClass_"+utostr(AnonCounter++));
185   } 
186   
187   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
188   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
189     Record *Type = TypeList[i];
190     if (!Type->isSubClassOf("ValueType"))
191       throw "RegTypes list member '" + Type->getName() +
192         "' does not derive from the ValueType class!";
193     VTs.push_back(getValueType(Type));
194   }
195   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
196   
197   std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
198   for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
199     Record *Reg = RegList[i];
200     if (!Reg->isSubClassOf("Register"))
201       throw "Register Class member '" + Reg->getName() +
202             "' does not derive from the Register class!";
203     Elements.push_back(Reg);
204   }
205   
206   std::vector<Record*> SubRegClassList = 
207                         R->getValueAsListOfDefs("SubRegClassList");
208   for (unsigned i = 0, e = SubRegClassList.size(); i != e; ++i) {
209     Record *SubRegClass = SubRegClassList[i];
210     if (!SubRegClass->isSubClassOf("RegisterClass"))
211       throw "Register Class member '" + SubRegClass->getName() +
212             "' does not derive from the RegisterClass class!";
213     SubRegClasses.push_back(SubRegClass);
214   }  
215   
216   // Allow targets to override the size in bits of the RegisterClass.
217   unsigned Size = R->getValueAsInt("Size");
218
219   Namespace = R->getValueAsString("Namespace");
220   SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
221   SpillAlignment = R->getValueAsInt("Alignment");
222   MethodBodies = R->getValueAsCode("MethodBodies");
223   MethodProtos = R->getValueAsCode("MethodProtos");
224 }
225
226 const std::string &CodeGenRegisterClass::getName() const {
227   return TheDef->getName();
228 }
229
230 void CodeGenTarget::ReadLegalValueTypes() const {
231   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
232   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
233     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
234       LegalValueTypes.push_back(RCs[i].VTs[ri]);
235   
236   // Remove duplicates.
237   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
238   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
239                                     LegalValueTypes.end()),
240                         LegalValueTypes.end());
241 }
242
243
244 void CodeGenTarget::ReadInstructions() const {
245   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
246   if (Insts.size() <= 2)
247     throw std::string("No 'Instruction' subclasses defined!");
248
249   // Parse the instructions defined in the .td file.
250   std::string InstFormatName =
251     getAsmWriter()->getValueAsString("InstFormatName");
252
253   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
254     std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
255     Instructions.insert(std::make_pair(Insts[i]->getName(),
256                                        CodeGenInstruction(Insts[i], AsmStr)));
257   }
258 }
259
260 /// getInstructionsByEnumValue - Return all of the instructions defined by the
261 /// target, ordered by their enum value.
262 void CodeGenTarget::
263 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
264                                                  &NumberedInstructions) {
265   std::map<std::string, CodeGenInstruction>::const_iterator I;
266   I = getInstructions().find("PHI");
267   if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
268   const CodeGenInstruction *PHI = &I->second;
269   
270   I = getInstructions().find("INLINEASM");
271   if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
272   const CodeGenInstruction *INLINEASM = &I->second;
273   
274   I = getInstructions().find("LABEL");
275   if (I == Instructions.end()) throw "Could not find 'LABEL' instruction!";
276   const CodeGenInstruction *LABEL = &I->second;
277   
278   I = getInstructions().find("EXTRACT_SUBREG");
279   if (I == Instructions.end()) 
280     throw "Could not find 'EXTRACT_SUBREG' instruction!";
281   const CodeGenInstruction *EXTRACT_SUBREG = &I->second;
282   
283   I = getInstructions().find("INSERT_SUBREG");
284   if (I == Instructions.end()) 
285     throw "Could not find 'INSERT_SUBREG' instruction!";
286   const CodeGenInstruction *INSERT_SUBREG = &I->second;
287   
288   // Print out the rest of the instructions now.
289   NumberedInstructions.push_back(PHI);
290   NumberedInstructions.push_back(INLINEASM);
291   NumberedInstructions.push_back(LABEL);
292   NumberedInstructions.push_back(EXTRACT_SUBREG);
293   NumberedInstructions.push_back(INSERT_SUBREG);
294   for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
295     if (&II->second != PHI &&
296         &II->second != INLINEASM &&
297         &II->second != LABEL &&
298         &II->second != EXTRACT_SUBREG &&
299         &II->second != INSERT_SUBREG)
300       NumberedInstructions.push_back(&II->second);
301 }
302
303
304 /// isLittleEndianEncoding - Return whether this target encodes its instruction
305 /// in little-endian format, i.e. bits laid out in the order [0..n]
306 ///
307 bool CodeGenTarget::isLittleEndianEncoding() const {
308   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
309 }
310
311
312
313 static void ParseConstraint(const std::string &CStr, CodeGenInstruction *I) {
314   // FIXME: Only supports TIED_TO for now.
315   std::string::size_type pos = CStr.find_first_of('=');
316   assert(pos != std::string::npos && "Unrecognized constraint");
317   std::string Name = CStr.substr(0, pos);
318
319   // TIED_TO: $src1 = $dst
320   std::string::size_type wpos = Name.find_first_of(" \t");
321   if (wpos == std::string::npos)
322     throw "Illegal format for tied-to constraint: '" + CStr + "'";
323   std::string DestOpName = Name.substr(0, wpos);
324   std::pair<unsigned,unsigned> DestOp = I->ParseOperandName(DestOpName, false);
325
326   Name = CStr.substr(pos+1);
327   wpos = Name.find_first_not_of(" \t");
328   if (wpos == std::string::npos)
329     throw "Illegal format for tied-to constraint: '" + CStr + "'";
330     
331   std::pair<unsigned,unsigned> SrcOp =
332     I->ParseOperandName(Name.substr(wpos), false);
333   if (SrcOp > DestOp)
334     throw "Illegal tied-to operand constraint '" + CStr + "'";
335   
336   
337   unsigned FlatOpNo = I->getFlattenedOperandNumber(SrcOp);
338   // Build the string for the operand.
339   std::string OpConstraint =
340     "((" + utostr(FlatOpNo) + " << 16) | (1 << TOI::TIED_TO))";
341
342   
343   if (!I->OperandList[DestOp.first].Constraints[DestOp.second].empty())
344     throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
345   I->OperandList[DestOp.first].Constraints[DestOp.second] = OpConstraint;
346 }
347
348 static void ParseConstraints(const std::string &CStr, CodeGenInstruction *I) {
349   // Make sure the constraints list for each operand is large enough to hold
350   // constraint info, even if none is present.
351   for (unsigned i = 0, e = I->OperandList.size(); i != e; ++i) 
352     I->OperandList[i].Constraints.resize(I->OperandList[i].MINumOperands);
353   
354   if (CStr.empty()) return;
355   
356   const std::string delims(",");
357   std::string::size_type bidx, eidx;
358
359   bidx = CStr.find_first_not_of(delims);
360   while (bidx != std::string::npos) {
361     eidx = CStr.find_first_of(delims, bidx);
362     if (eidx == std::string::npos)
363       eidx = CStr.length();
364     
365     ParseConstraint(CStr.substr(bidx, eidx), I);
366     bidx = CStr.find_first_not_of(delims, eidx);
367   }
368 }
369
370 CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)
371   : TheDef(R), AsmString(AsmStr) {
372   Name      = R->getValueAsString("Name");
373   Namespace = R->getValueAsString("Namespace");
374
375   isReturn     = R->getValueAsBit("isReturn");
376   isBranch     = R->getValueAsBit("isBranch");
377   isBarrier    = R->getValueAsBit("isBarrier");
378   isCall       = R->getValueAsBit("isCall");
379   isLoad       = R->getValueAsBit("isLoad");
380   isStore      = R->getValueAsBit("isStore");
381   bool isTwoAddress = R->getValueAsBit("isTwoAddress");
382   isPredicable = R->getValueAsBit("isPredicable");
383   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
384   isCommutable = R->getValueAsBit("isCommutable");
385   isTerminator = R->getValueAsBit("isTerminator");
386   isReMaterializable = R->getValueAsBit("isReMaterializable");
387   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
388   usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter");
389   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
390   isNotDuplicable = R->getValueAsBit("isNotDuplicable");
391   hasOptionalDef = false;
392   hasVariableNumberOfOperands = false;
393   
394   DagInit *DI;
395   try {
396     DI = R->getValueAsDag("OutOperandList");
397   } catch (...) {
398     // Error getting operand list, just ignore it (sparcv9).
399     AsmString.clear();
400     OperandList.clear();
401     return;
402   }
403   NumDefs = DI->getNumArgs();
404
405   DagInit *IDI;
406   try {
407     IDI = R->getValueAsDag("InOperandList");
408   } catch (...) {
409     // Error getting operand list, just ignore it (sparcv9).
410     AsmString.clear();
411     OperandList.clear();
412     return;
413   }
414   DI = (DagInit*)(new BinOpInit(BinOpInit::CONCAT, DI, IDI))->Fold();
415
416   unsigned MIOperandNo = 0;
417   std::set<std::string> OperandNames;
418   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
419     DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));
420     if (!Arg)
421       throw "Illegal operand for the '" + R->getName() + "' instruction!";
422
423     Record *Rec = Arg->getDef();
424     std::string PrintMethod = "printOperand";
425     unsigned NumOps = 1;
426     DagInit *MIOpInfo = 0;
427     if (Rec->isSubClassOf("Operand")) {
428       PrintMethod = Rec->getValueAsString("PrintMethod");
429       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
430       
431       // Verify that MIOpInfo has an 'ops' root value.
432       if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ||
433           dynamic_cast<DefInit*>(MIOpInfo->getOperator())
434                ->getDef()->getName() != "ops")
435         throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
436               "'\n";
437
438       // If we have MIOpInfo, then we have #operands equal to number of entries
439       // in MIOperandInfo.
440       if (unsigned NumArgs = MIOpInfo->getNumArgs())
441         NumOps = NumArgs;
442
443       if (Rec->isSubClassOf("PredicateOperand"))
444         isPredicable = true;
445       else if (Rec->isSubClassOf("OptionalDefOperand"))
446         hasOptionalDef = true;
447     } else if (Rec->getName() == "variable_ops") {
448       hasVariableNumberOfOperands = true;
449       continue;
450     } else if (!Rec->isSubClassOf("RegisterClass") && 
451                Rec->getName() != "ptr_rc")
452       throw "Unknown operand class '" + Rec->getName() +
453             "' in instruction '" + R->getName() + "' instruction!";
454
455     // Check that the operand has a name and that it's unique.
456     if (DI->getArgName(i).empty())
457       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
458         " has no name!";
459     if (!OperandNames.insert(DI->getArgName(i)).second)
460       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
461         " has the same name as a previous operand!";
462     
463     OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, 
464                                       MIOperandNo, NumOps, MIOpInfo));
465     MIOperandNo += NumOps;
466   }
467
468   // Parse Constraints.
469   ParseConstraints(R->getValueAsString("Constraints"), this);
470   
471   // For backward compatibility: isTwoAddress means operand 1 is tied to
472   // operand 0.
473   if (isTwoAddress) {
474     if (!OperandList[1].Constraints[0].empty())
475       throw R->getName() + ": cannot use isTwoAddress property: instruction "
476             "already has constraint set!";
477     OperandList[1].Constraints[0] = "((0 << 16) | (1 << TOI::TIED_TO))";
478   }
479   
480   // Any operands with unset constraints get 0 as their constraint.
481   for (unsigned op = 0, e = OperandList.size(); op != e; ++op)
482     for (unsigned j = 0, e = OperandList[op].MINumOperands; j != e; ++j)
483       if (OperandList[op].Constraints[j].empty())
484         OperandList[op].Constraints[j] = "0";
485   
486   // Parse the DisableEncoding field.
487   std::string DisableEncoding = R->getValueAsString("DisableEncoding");
488   while (1) {
489     std::string OpName = getToken(DisableEncoding, " ,\t");
490     if (OpName.empty()) break;
491
492     // Figure out which operand this is.
493     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
494
495     // Mark the operand as not-to-be encoded.
496     if (Op.second >= OperandList[Op.first].DoNotEncode.size())
497       OperandList[Op.first].DoNotEncode.resize(Op.second+1);
498     OperandList[Op.first].DoNotEncode[Op.second] = true;
499   }
500 }
501
502
503
504 /// getOperandNamed - Return the index of the operand with the specified
505 /// non-empty name.  If the instruction does not have an operand with the
506 /// specified name, throw an exception.
507 ///
508 unsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {
509   assert(!Name.empty() && "Cannot search for operand with no name!");
510   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
511     if (OperandList[i].Name == Name) return i;
512   throw "Instruction '" + TheDef->getName() +
513         "' does not have an operand named '$" + Name + "'!";
514 }
515
516 std::pair<unsigned,unsigned> 
517 CodeGenInstruction::ParseOperandName(const std::string &Op,
518                                      bool AllowWholeOp) {
519   if (Op.empty() || Op[0] != '$')
520     throw TheDef->getName() + ": Illegal operand name: '" + Op + "'";
521   
522   std::string OpName = Op.substr(1);
523   std::string SubOpName;
524   
525   // Check to see if this is $foo.bar.
526   std::string::size_type DotIdx = OpName.find_first_of(".");
527   if (DotIdx != std::string::npos) {
528     SubOpName = OpName.substr(DotIdx+1);
529     if (SubOpName.empty())
530       throw TheDef->getName() + ": illegal empty suboperand name in '" +Op +"'";
531     OpName = OpName.substr(0, DotIdx);
532   }
533   
534   unsigned OpIdx = getOperandNamed(OpName);
535
536   if (SubOpName.empty()) {  // If no suboperand name was specified:
537     // If one was needed, throw.
538     if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
539         SubOpName.empty())
540       throw TheDef->getName() + ": Illegal to refer to"
541             " whole operand part of complex operand '" + Op + "'";
542   
543     // Otherwise, return the operand.
544     return std::make_pair(OpIdx, 0U);
545   }
546   
547   // Find the suboperand number involved.
548   DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
549   if (MIOpInfo == 0)
550     throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
551   
552   // Find the operand with the right name.
553   for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
554     if (MIOpInfo->getArgName(i) == SubOpName)
555       return std::make_pair(OpIdx, i);
556
557   // Otherwise, didn't find it!
558   throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
559 }
560
561
562
563
564 //===----------------------------------------------------------------------===//
565 // ComplexPattern implementation
566 //
567 ComplexPattern::ComplexPattern(Record *R) {
568   Ty          = ::getValueType(R->getValueAsDef("Ty"));
569   NumOperands = R->getValueAsInt("NumOperands");
570   SelectFunc  = R->getValueAsString("SelectFunc");
571   RootNodes   = R->getValueAsListOfDefs("RootNodes");
572
573   // Parse the properties.
574   Properties = 0;
575   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
576   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
577     if (PropList[i]->getName() == "SDNPHasChain") {
578       Properties |= 1 << SDNPHasChain;
579     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
580       Properties |= 1 << SDNPOptInFlag;
581     } else {
582       cerr << "Unsupported SD Node property '" << PropList[i]->getName()
583            << "' on ComplexPattern '" << R->getName() << "'!\n";
584       exit(1);
585     }
586 }
587
588 //===----------------------------------------------------------------------===//
589 // CodeGenIntrinsic Implementation
590 //===----------------------------------------------------------------------===//
591
592 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
593   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
594   
595   std::vector<CodeGenIntrinsic> Result;
596
597   // If we are in the context of a target .td file, get the target info so that
598   // we can decode the current intptr_t.
599   CodeGenTarget *CGT = 0;
600   if (Records.getClass("Target") &&
601       Records.getAllDerivedDefinitions("Target").size() == 1)
602     CGT = new CodeGenTarget();
603   
604   for (unsigned i = 0, e = I.size(); i != e; ++i)
605     Result.push_back(CodeGenIntrinsic(I[i], CGT));
606   delete CGT;
607   return Result;
608 }
609
610 CodeGenIntrinsic::CodeGenIntrinsic(Record *R, CodeGenTarget *CGT) {
611   TheDef = R;
612   std::string DefName = R->getName();
613   ModRef = WriteMem;
614   isOverloaded = false;
615   
616   if (DefName.size() <= 4 || 
617       std::string(DefName.begin(), DefName.begin()+4) != "int_")
618     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
619   EnumName = std::string(DefName.begin()+4, DefName.end());
620   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
621     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
622   TargetPrefix   = R->getValueAsString("TargetPrefix");
623   Name = R->getValueAsString("LLVMName");
624   if (Name == "") {
625     // If an explicit name isn't specified, derive one from the DefName.
626     Name = "llvm.";
627     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
628       if (EnumName[i] == '_')
629         Name += '.';
630       else
631         Name += EnumName[i];
632   } else {
633     // Verify it starts with "llvm.".
634     if (Name.size() <= 5 || 
635         std::string(Name.begin(), Name.begin()+5) != "llvm.")
636       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
637   }
638   
639   // If TargetPrefix is specified, make sure that Name starts with
640   // "llvm.<targetprefix>.".
641   if (!TargetPrefix.empty()) {
642     if (Name.size() < 6+TargetPrefix.size() ||
643         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size()) 
644         != (TargetPrefix+"."))
645       throw "Intrinsic '" + DefName + "' does not start with 'llvm." + 
646         TargetPrefix + ".'!";
647   }
648   
649   // Parse the list of argument types.
650   ListInit *TypeList = R->getValueAsListInit("Types");
651   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
652     Record *TyEl = TypeList->getElementAsRecord(i);
653     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
654     MVT::ValueType VT = getValueType(TyEl->getValueAsDef("VT"));
655     isOverloaded |= VT == MVT::iAny;
656     ArgVTs.push_back(VT);
657     ArgTypeDefs.push_back(TyEl);
658   }
659   if (ArgVTs.size() == 0)
660     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
661
662   
663   // Parse the intrinsic properties.
664   ListInit *PropList = R->getValueAsListInit("Properties");
665   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
666     Record *Property = PropList->getElementAsRecord(i);
667     assert(Property->isSubClassOf("IntrinsicProperty") &&
668            "Expected a property!");
669     
670     if (Property->getName() == "IntrNoMem")
671       ModRef = NoMem;
672     else if (Property->getName() == "IntrReadArgMem")
673       ModRef = ReadArgMem;
674     else if (Property->getName() == "IntrReadMem")
675       ModRef = ReadMem;
676     else if (Property->getName() == "IntrWriteArgMem")
677       ModRef = WriteArgMem;
678     else if (Property->getName() == "IntrWriteMem")
679       ModRef = WriteMem;
680     else
681       assert(0 && "Unknown property!");
682   }
683 }