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