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