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