1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class wraps 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 abort on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "CodeGenSchedule.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include <algorithm>
26 using namespace llvm;
27 
28 cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
29 cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
30 
31 static cl::opt<unsigned>
32     AsmParserNum("asmparsernum", cl::init(0),
33                  cl::desc("Make -gen-asm-parser emit assembly parser #N"),
34                  cl::cat(AsmParserCat));
35 
36 static cl::opt<unsigned>
37     AsmWriterNum("asmwriternum", cl::init(0),
38                  cl::desc("Make -gen-asm-writer emit assembly writer #N"),
39                  cl::cat(AsmWriterCat));
40 
41 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
42 /// record corresponds to.
43 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
44   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
45 }
46 
47 StringRef llvm::getName(MVT::SimpleValueType T) {
48   switch (T) {
49   case MVT::Other:   return "UNKNOWN";
50   case MVT::iPTR:    return "TLI.getPointerTy()";
51   case MVT::iPTRAny: return "TLI.getPointerTy()";
52   default: return getEnumName(T);
53   }
54 }
55 
56 StringRef llvm::getEnumName(MVT::SimpleValueType T) {
57   switch (T) {
58   case MVT::Other:    return "MVT::Other";
59   case MVT::i1:       return "MVT::i1";
60   case MVT::i8:       return "MVT::i8";
61   case MVT::i16:      return "MVT::i16";
62   case MVT::i32:      return "MVT::i32";
63   case MVT::i64:      return "MVT::i64";
64   case MVT::i128:     return "MVT::i128";
65   case MVT::Any:      return "MVT::Any";
66   case MVT::iAny:     return "MVT::iAny";
67   case MVT::fAny:     return "MVT::fAny";
68   case MVT::vAny:     return "MVT::vAny";
69   case MVT::f16:      return "MVT::f16";
70   case MVT::f32:      return "MVT::f32";
71   case MVT::f64:      return "MVT::f64";
72   case MVT::f80:      return "MVT::f80";
73   case MVT::f128:     return "MVT::f128";
74   case MVT::ppcf128:  return "MVT::ppcf128";
75   case MVT::x86mmx:   return "MVT::x86mmx";
76   case MVT::Glue:     return "MVT::Glue";
77   case MVT::isVoid:   return "MVT::isVoid";
78   case MVT::v1i1:     return "MVT::v1i1";
79   case MVT::v2i1:     return "MVT::v2i1";
80   case MVT::v4i1:     return "MVT::v4i1";
81   case MVT::v8i1:     return "MVT::v8i1";
82   case MVT::v16i1:    return "MVT::v16i1";
83   case MVT::v32i1:    return "MVT::v32i1";
84   case MVT::v64i1:    return "MVT::v64i1";
85   case MVT::v128i1:   return "MVT::v128i1";
86   case MVT::v512i1:   return "MVT::v512i1";
87   case MVT::v1024i1:  return "MVT::v1024i1";
88   case MVT::v1i8:     return "MVT::v1i8";
89   case MVT::v2i8:     return "MVT::v2i8";
90   case MVT::v4i8:     return "MVT::v4i8";
91   case MVT::v8i8:     return "MVT::v8i8";
92   case MVT::v16i8:    return "MVT::v16i8";
93   case MVT::v32i8:    return "MVT::v32i8";
94   case MVT::v64i8:    return "MVT::v64i8";
95   case MVT::v128i8:   return "MVT::v128i8";
96   case MVT::v256i8:   return "MVT::v256i8";
97   case MVT::v1i16:    return "MVT::v1i16";
98   case MVT::v2i16:    return "MVT::v2i16";
99   case MVT::v4i16:    return "MVT::v4i16";
100   case MVT::v8i16:    return "MVT::v8i16";
101   case MVT::v16i16:   return "MVT::v16i16";
102   case MVT::v32i16:   return "MVT::v32i16";
103   case MVT::v64i16:   return "MVT::v64i16";
104   case MVT::v128i16:  return "MVT::v128i16";
105   case MVT::v1i32:    return "MVT::v1i32";
106   case MVT::v2i32:    return "MVT::v2i32";
107   case MVT::v4i32:    return "MVT::v4i32";
108   case MVT::v8i32:    return "MVT::v8i32";
109   case MVT::v16i32:   return "MVT::v16i32";
110   case MVT::v32i32:   return "MVT::v32i32";
111   case MVT::v64i32:   return "MVT::v64i32";
112   case MVT::v1i64:    return "MVT::v1i64";
113   case MVT::v2i64:    return "MVT::v2i64";
114   case MVT::v4i64:    return "MVT::v4i64";
115   case MVT::v8i64:    return "MVT::v8i64";
116   case MVT::v16i64:   return "MVT::v16i64";
117   case MVT::v32i64:   return "MVT::v32i64";
118   case MVT::v1i128:   return "MVT::v1i128";
119   case MVT::v2f16:    return "MVT::v2f16";
120   case MVT::v4f16:    return "MVT::v4f16";
121   case MVT::v8f16:    return "MVT::v8f16";
122   case MVT::v1f32:    return "MVT::v1f32";
123   case MVT::v2f32:    return "MVT::v2f32";
124   case MVT::v4f32:    return "MVT::v4f32";
125   case MVT::v8f32:    return "MVT::v8f32";
126   case MVT::v16f32:   return "MVT::v16f32";
127   case MVT::v1f64:    return "MVT::v1f64";
128   case MVT::v2f64:    return "MVT::v2f64";
129   case MVT::v4f64:    return "MVT::v4f64";
130   case MVT::v8f64:    return "MVT::v8f64";
131   case MVT::nxv1i1:   return "MVT::nxv1i1";
132   case MVT::nxv2i1:   return "MVT::nxv2i1";
133   case MVT::nxv4i1:   return "MVT::nxv4i1";
134   case MVT::nxv8i1:   return "MVT::nxv8i1";
135   case MVT::nxv16i1:  return "MVT::nxv16i1";
136   case MVT::nxv32i1:  return "MVT::nxv32i1";
137   case MVT::nxv1i8:   return "MVT::nxv1i8";
138   case MVT::nxv2i8:   return "MVT::nxv2i8";
139   case MVT::nxv4i8:   return "MVT::nxv4i8";
140   case MVT::nxv8i8:   return "MVT::nxv8i8";
141   case MVT::nxv16i8:  return "MVT::nxv16i8";
142   case MVT::nxv32i8:  return "MVT::nxv32i8";
143   case MVT::nxv1i16:  return "MVT::nxv1i16";
144   case MVT::nxv2i16:  return "MVT::nxv2i16";
145   case MVT::nxv4i16:  return "MVT::nxv4i16";
146   case MVT::nxv8i16:  return "MVT::nxv8i16";
147   case MVT::nxv16i16: return "MVT::nxv16i16";
148   case MVT::nxv32i16: return "MVT::nxv32i16";
149   case MVT::nxv1i32:  return "MVT::nxv1i32";
150   case MVT::nxv2i32:  return "MVT::nxv2i32";
151   case MVT::nxv4i32:  return "MVT::nxv4i32";
152   case MVT::nxv8i32:  return "MVT::nxv8i32";
153   case MVT::nxv16i32: return "MVT::nxv16i32";
154   case MVT::nxv1i64:  return "MVT::nxv1i64";
155   case MVT::nxv2i64:  return "MVT::nxv2i64";
156   case MVT::nxv4i64:  return "MVT::nxv4i64";
157   case MVT::nxv8i64:  return "MVT::nxv8i64";
158   case MVT::nxv16i64: return "MVT::nxv16i64";
159   case MVT::nxv2f16:  return "MVT::nxv2f16";
160   case MVT::nxv4f16:  return "MVT::nxv4f16";
161   case MVT::nxv8f16:  return "MVT::nxv8f16";
162   case MVT::nxv1f32:  return "MVT::nxv1f32";
163   case MVT::nxv2f32:  return "MVT::nxv2f32";
164   case MVT::nxv4f32:  return "MVT::nxv4f32";
165   case MVT::nxv8f32:  return "MVT::nxv8f32";
166   case MVT::nxv16f32: return "MVT::nxv16f32";
167   case MVT::nxv1f64:  return "MVT::nxv1f64";
168   case MVT::nxv2f64:  return "MVT::nxv2f64";
169   case MVT::nxv4f64:  return "MVT::nxv4f64";
170   case MVT::nxv8f64:  return "MVT::nxv8f64";
171   case MVT::token:    return "MVT::token";
172   case MVT::Metadata: return "MVT::Metadata";
173   case MVT::iPTR:     return "MVT::iPTR";
174   case MVT::iPTRAny:  return "MVT::iPTRAny";
175   case MVT::Untyped:  return "MVT::Untyped";
176   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
177   }
178 }
179 
180 /// getQualifiedName - Return the name of the specified record, with a
181 /// namespace qualifier if the record contains one.
182 ///
183 std::string llvm::getQualifiedName(const Record *R) {
184   std::string Namespace;
185   if (R->getValue("Namespace"))
186      Namespace = R->getValueAsString("Namespace");
187   if (Namespace.empty()) return R->getName();
188   return Namespace + "::" + R->getName().str();
189 }
190 
191 
192 /// getTarget - Return the current instance of the Target class.
193 ///
194 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
195   : Records(records), CGH(records) {
196   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
197   if (Targets.size() == 0)
198     PrintFatalError("ERROR: No 'Target' subclasses defined!");
199   if (Targets.size() != 1)
200     PrintFatalError("ERROR: Multiple subclasses of Target defined!");
201   TargetRec = Targets[0];
202 }
203 
204 CodeGenTarget::~CodeGenTarget() {
205 }
206 
207 const StringRef CodeGenTarget::getName() const {
208   return TargetRec->getName();
209 }
210 
211 StringRef CodeGenTarget::getInstNamespace() const {
212   for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
213     // Make sure not to pick up "TargetOpcode" by accidentally getting
214     // the namespace off the PHI instruction or something.
215     if (Inst->Namespace != "TargetOpcode")
216       return Inst->Namespace;
217   }
218 
219   return "";
220 }
221 
222 Record *CodeGenTarget::getInstructionSet() const {
223   return TargetRec->getValueAsDef("InstructionSet");
224 }
225 
226 
227 /// getAsmParser - Return the AssemblyParser definition for this target.
228 ///
229 Record *CodeGenTarget::getAsmParser() const {
230   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
231   if (AsmParserNum >= LI.size())
232     PrintFatalError("Target does not have an AsmParser #" +
233                     Twine(AsmParserNum) + "!");
234   return LI[AsmParserNum];
235 }
236 
237 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
238 /// this target.
239 ///
240 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
241   std::vector<Record*> LI =
242     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
243   if (i >= LI.size())
244     PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
245                     "!");
246   return LI[i];
247 }
248 
249 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
250 /// available for this target.
251 ///
252 unsigned CodeGenTarget::getAsmParserVariantCount() const {
253   std::vector<Record*> LI =
254     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
255   return LI.size();
256 }
257 
258 /// getAsmWriter - Return the AssemblyWriter definition for this target.
259 ///
260 Record *CodeGenTarget::getAsmWriter() const {
261   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
262   if (AsmWriterNum >= LI.size())
263     PrintFatalError("Target does not have an AsmWriter #" +
264                     Twine(AsmWriterNum) + "!");
265   return LI[AsmWriterNum];
266 }
267 
268 CodeGenRegBank &CodeGenTarget::getRegBank() const {
269   if (!RegBank)
270     RegBank = llvm::make_unique<CodeGenRegBank>(Records, getHwModes());
271   return *RegBank;
272 }
273 
274 void CodeGenTarget::ReadRegAltNameIndices() const {
275   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
276   std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
277 }
278 
279 /// getRegisterByName - If there is a register with the specific AsmName,
280 /// return it.
281 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
282   const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
283   StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
284   if (I == Regs.end())
285     return nullptr;
286   return I->second;
287 }
288 
289 std::vector<ValueTypeByHwMode> CodeGenTarget::getRegisterVTs(Record *R)
290       const {
291   const CodeGenRegister *Reg = getRegBank().getReg(R);
292   std::vector<ValueTypeByHwMode> Result;
293   for (const auto &RC : getRegBank().getRegClasses()) {
294     if (RC.contains(Reg)) {
295       ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
296       Result.insert(Result.end(), InVTs.begin(), InVTs.end());
297     }
298   }
299 
300   // Remove duplicates.
301   std::sort(Result.begin(), Result.end());
302   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
303   return Result;
304 }
305 
306 
307 void CodeGenTarget::ReadLegalValueTypes() const {
308   for (const auto &RC : getRegBank().getRegClasses())
309     LegalValueTypes.insert(LegalValueTypes.end(), RC.VTs.begin(), RC.VTs.end());
310 
311   // Remove duplicates.
312   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
313   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
314                                     LegalValueTypes.end()),
315                         LegalValueTypes.end());
316 }
317 
318 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
319   if (!SchedModels)
320     SchedModels = llvm::make_unique<CodeGenSchedModels>(Records, *this);
321   return *SchedModels;
322 }
323 
324 void CodeGenTarget::ReadInstructions() const {
325   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
326   if (Insts.size() <= 2)
327     PrintFatalError("No 'Instruction' subclasses defined!");
328 
329   // Parse the instructions defined in the .td file.
330   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
331     Instructions[Insts[i]] = llvm::make_unique<CodeGenInstruction>(Insts[i]);
332 }
333 
334 static const CodeGenInstruction *
335 GetInstByName(const char *Name,
336               const DenseMap<const Record*,
337                              std::unique_ptr<CodeGenInstruction>> &Insts,
338               RecordKeeper &Records) {
339   const Record *Rec = Records.getDef(Name);
340 
341   const auto I = Insts.find(Rec);
342   if (!Rec || I == Insts.end())
343     PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
344   return I->second.get();
345 }
346 
347 /// \brief Return all of the instructions defined by the target, ordered by
348 /// their enum value.
349 void CodeGenTarget::ComputeInstrsByEnum() const {
350   static const char *const FixedInstrs[] = {
351 #define HANDLE_TARGET_OPCODE(OPC) #OPC,
352 #include "llvm/CodeGen/TargetOpcodes.def"
353       nullptr};
354   const auto &Insts = getInstructions();
355   for (const char *const *p = FixedInstrs; *p; ++p) {
356     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
357     assert(Instr && "Missing target independent instruction");
358     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
359     InstrsByEnum.push_back(Instr);
360   }
361   unsigned EndOfPredefines = InstrsByEnum.size();
362 
363   for (const auto &I : Insts) {
364     const CodeGenInstruction *CGI = I.second.get();
365     if (CGI->Namespace != "TargetOpcode")
366       InstrsByEnum.push_back(CGI);
367   }
368 
369   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
370 
371   // All of the instructions are now in random order based on the map iteration.
372   // Sort them by name.
373   std::sort(InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
374             [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
375     return Rec1->TheDef->getName() < Rec2->TheDef->getName();
376   });
377 }
378 
379 
380 /// isLittleEndianEncoding - Return whether this target encodes its instruction
381 /// in little-endian format, i.e. bits laid out in the order [0..n]
382 ///
383 bool CodeGenTarget::isLittleEndianEncoding() const {
384   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
385 }
386 
387 /// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
388 /// encodings, reverse the bit order of all instructions.
389 void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
390   if (!isLittleEndianEncoding())
391     return;
392 
393   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
394   for (Record *R : Insts) {
395     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
396         R->getValueAsBit("isPseudo"))
397       continue;
398 
399     BitsInit *BI = R->getValueAsBitsInit("Inst");
400 
401     unsigned numBits = BI->getNumBits();
402 
403     SmallVector<Init *, 16> NewBits(numBits);
404 
405     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
406       unsigned bitSwapIdx = numBits - bit - 1;
407       Init *OrigBit = BI->getBit(bit);
408       Init *BitSwap = BI->getBit(bitSwapIdx);
409       NewBits[bit]        = BitSwap;
410       NewBits[bitSwapIdx] = OrigBit;
411     }
412     if (numBits % 2) {
413       unsigned middle = (numBits + 1) / 2;
414       NewBits[middle] = BI->getBit(middle);
415     }
416 
417     BitsInit *NewBI = BitsInit::get(NewBits);
418 
419     // Update the bits in reversed order so that emitInstrOpBits will get the
420     // correct endianness.
421     R->getValue("Inst")->setValue(NewBI);
422   }
423 }
424 
425 /// guessInstructionProperties - Return true if it's OK to guess instruction
426 /// properties instead of raising an error.
427 ///
428 /// This is configurable as a temporary migration aid. It will eventually be
429 /// permanently false.
430 bool CodeGenTarget::guessInstructionProperties() const {
431   return getInstructionSet()->getValueAsBit("guessInstructionProperties");
432 }
433 
434 //===----------------------------------------------------------------------===//
435 // ComplexPattern implementation
436 //
437 ComplexPattern::ComplexPattern(Record *R) {
438   Ty          = ::getValueType(R->getValueAsDef("Ty"));
439   NumOperands = R->getValueAsInt("NumOperands");
440   SelectFunc  = R->getValueAsString("SelectFunc");
441   RootNodes   = R->getValueAsListOfDefs("RootNodes");
442 
443   // FIXME: This is a hack to statically increase the priority of patterns which
444   // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
445   // possible pattern match we'll need to dynamically calculate the complexity
446   // of all patterns a dag can potentially map to.
447   int64_t RawComplexity = R->getValueAsInt("Complexity");
448   if (RawComplexity == -1)
449     Complexity = NumOperands * 3;
450   else
451     Complexity = RawComplexity;
452 
453   // Parse the properties.
454   Properties = 0;
455   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
456   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
457     if (PropList[i]->getName() == "SDNPHasChain") {
458       Properties |= 1 << SDNPHasChain;
459     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
460       Properties |= 1 << SDNPOptInGlue;
461     } else if (PropList[i]->getName() == "SDNPMayStore") {
462       Properties |= 1 << SDNPMayStore;
463     } else if (PropList[i]->getName() == "SDNPMayLoad") {
464       Properties |= 1 << SDNPMayLoad;
465     } else if (PropList[i]->getName() == "SDNPSideEffect") {
466       Properties |= 1 << SDNPSideEffect;
467     } else if (PropList[i]->getName() == "SDNPMemOperand") {
468       Properties |= 1 << SDNPMemOperand;
469     } else if (PropList[i]->getName() == "SDNPVariadic") {
470       Properties |= 1 << SDNPVariadic;
471     } else if (PropList[i]->getName() == "SDNPWantRoot") {
472       Properties |= 1 << SDNPWantRoot;
473     } else if (PropList[i]->getName() == "SDNPWantParent") {
474       Properties |= 1 << SDNPWantParent;
475     } else {
476       PrintFatalError("Unsupported SD Node property '" +
477                       PropList[i]->getName() + "' on ComplexPattern '" +
478                       R->getName() + "'!");
479     }
480 }
481 
482 //===----------------------------------------------------------------------===//
483 // CodeGenIntrinsic Implementation
484 //===----------------------------------------------------------------------===//
485 
486 CodeGenIntrinsicTable::CodeGenIntrinsicTable(const RecordKeeper &RC,
487                                              bool TargetOnly) {
488   std::vector<Record*> Defs = RC.getAllDerivedDefinitions("Intrinsic");
489 
490   Intrinsics.reserve(Defs.size());
491 
492   for (unsigned I = 0, e = Defs.size(); I != e; ++I) {
493     bool isTarget = Defs[I]->getValueAsBit("isTarget");
494     if (isTarget == TargetOnly)
495       Intrinsics.push_back(CodeGenIntrinsic(Defs[I]));
496   }
497   std::sort(Intrinsics.begin(), Intrinsics.end(),
498             [](const CodeGenIntrinsic &LHS, const CodeGenIntrinsic &RHS) {
499               return std::tie(LHS.TargetPrefix, LHS.Name) <
500                      std::tie(RHS.TargetPrefix, RHS.Name);
501             });
502   Targets.push_back({"", 0, 0});
503   for (size_t I = 0, E = Intrinsics.size(); I < E; ++I)
504     if (Intrinsics[I].TargetPrefix != Targets.back().Name) {
505       Targets.back().Count = I - Targets.back().Offset;
506       Targets.push_back({Intrinsics[I].TargetPrefix, I, 0});
507     }
508   Targets.back().Count = Intrinsics.size() - Targets.back().Offset;
509 }
510 
511 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
512   TheDef = R;
513   std::string DefName = R->getName();
514   ModRef = ReadWriteMem;
515   isOverloaded = false;
516   isCommutative = false;
517   canThrow = false;
518   isNoReturn = false;
519   isNoDuplicate = false;
520   isConvergent = false;
521   isSpeculatable = false;
522   hasSideEffects = false;
523 
524   if (DefName.size() <= 4 ||
525       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
526     PrintFatalError("Intrinsic '" + DefName + "' does not start with 'int_'!");
527 
528   EnumName = std::string(DefName.begin()+4, DefName.end());
529 
530   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
531     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
532   if (R->getValue("MSBuiltinName"))   // Ignore a missing MSBuiltinName field.
533     MSBuiltinName = R->getValueAsString("MSBuiltinName");
534 
535   TargetPrefix = R->getValueAsString("TargetPrefix");
536   Name = R->getValueAsString("LLVMName");
537 
538   if (Name == "") {
539     // If an explicit name isn't specified, derive one from the DefName.
540     Name = "llvm.";
541 
542     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
543       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
544   } else {
545     // Verify it starts with "llvm.".
546     if (Name.size() <= 5 ||
547         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
548       PrintFatalError("Intrinsic '" + DefName + "'s name does not start with 'llvm.'!");
549   }
550 
551   // If TargetPrefix is specified, make sure that Name starts with
552   // "llvm.<targetprefix>.".
553   if (!TargetPrefix.empty()) {
554     if (Name.size() < 6+TargetPrefix.size() ||
555         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
556         != (TargetPrefix + "."))
557       PrintFatalError("Intrinsic '" + DefName + "' does not start with 'llvm." +
558         TargetPrefix + ".'!");
559   }
560 
561   // Parse the list of return types.
562   std::vector<MVT::SimpleValueType> OverloadedVTs;
563   ListInit *TypeList = R->getValueAsListInit("RetTypes");
564   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
565     Record *TyEl = TypeList->getElementAsRecord(i);
566     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
567     MVT::SimpleValueType VT;
568     if (TyEl->isSubClassOf("LLVMMatchType")) {
569       unsigned MatchTy = TyEl->getValueAsInt("Number");
570       assert(MatchTy < OverloadedVTs.size() &&
571              "Invalid matching number!");
572       VT = OverloadedVTs[MatchTy];
573       // It only makes sense to use the extended and truncated vector element
574       // variants with iAny types; otherwise, if the intrinsic is not
575       // overloaded, all the types can be specified directly.
576       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
577                !TyEl->isSubClassOf("LLVMTruncatedType")) ||
578               VT == MVT::iAny || VT == MVT::vAny) &&
579              "Expected iAny or vAny type");
580     } else {
581       VT = getValueType(TyEl->getValueAsDef("VT"));
582     }
583     if (MVT(VT).isOverloaded()) {
584       OverloadedVTs.push_back(VT);
585       isOverloaded = true;
586     }
587 
588     // Reject invalid types.
589     if (VT == MVT::isVoid)
590       PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
591 
592     IS.RetVTs.push_back(VT);
593     IS.RetTypeDefs.push_back(TyEl);
594   }
595 
596   // Parse the list of parameter types.
597   TypeList = R->getValueAsListInit("ParamTypes");
598   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
599     Record *TyEl = TypeList->getElementAsRecord(i);
600     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
601     MVT::SimpleValueType VT;
602     if (TyEl->isSubClassOf("LLVMMatchType")) {
603       unsigned MatchTy = TyEl->getValueAsInt("Number");
604       assert(MatchTy < OverloadedVTs.size() &&
605              "Invalid matching number!");
606       VT = OverloadedVTs[MatchTy];
607       // It only makes sense to use the extended and truncated vector element
608       // variants with iAny types; otherwise, if the intrinsic is not
609       // overloaded, all the types can be specified directly.
610       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
611                !TyEl->isSubClassOf("LLVMTruncatedType") &&
612                !TyEl->isSubClassOf("LLVMVectorSameWidth")) ||
613               VT == MVT::iAny || VT == MVT::vAny) &&
614              "Expected iAny or vAny type");
615     } else
616       VT = getValueType(TyEl->getValueAsDef("VT"));
617 
618     if (MVT(VT).isOverloaded()) {
619       OverloadedVTs.push_back(VT);
620       isOverloaded = true;
621     }
622 
623     // Reject invalid types.
624     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
625       PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
626 
627     IS.ParamVTs.push_back(VT);
628     IS.ParamTypeDefs.push_back(TyEl);
629   }
630 
631   // Parse the intrinsic properties.
632   ListInit *PropList = R->getValueAsListInit("IntrProperties");
633   for (unsigned i = 0, e = PropList->size(); i != e; ++i) {
634     Record *Property = PropList->getElementAsRecord(i);
635     assert(Property->isSubClassOf("IntrinsicProperty") &&
636            "Expected a property!");
637 
638     if (Property->getName() == "IntrNoMem")
639       ModRef = NoMem;
640     else if (Property->getName() == "IntrReadMem")
641       ModRef = ModRefBehavior(ModRef & ~MR_Mod);
642     else if (Property->getName() == "IntrWriteMem")
643       ModRef = ModRefBehavior(ModRef & ~MR_Ref);
644     else if (Property->getName() == "IntrArgMemOnly")
645       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem);
646     else if (Property->getName() == "IntrInaccessibleMemOnly")
647       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_InaccessibleMem);
648     else if (Property->getName() == "IntrInaccessibleMemOrArgMemOnly")
649       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem |
650                               MR_InaccessibleMem);
651     else if (Property->getName() == "Commutative")
652       isCommutative = true;
653     else if (Property->getName() == "Throws")
654       canThrow = true;
655     else if (Property->getName() == "IntrNoDuplicate")
656       isNoDuplicate = true;
657     else if (Property->getName() == "IntrConvergent")
658       isConvergent = true;
659     else if (Property->getName() == "IntrNoReturn")
660       isNoReturn = true;
661     else if (Property->getName() == "IntrSpeculatable")
662       isSpeculatable = true;
663     else if (Property->getName() == "IntrHasSideEffects")
664       hasSideEffects = true;
665     else if (Property->isSubClassOf("NoCapture")) {
666       unsigned ArgNo = Property->getValueAsInt("ArgNo");
667       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
668     } else if (Property->isSubClassOf("Returned")) {
669       unsigned ArgNo = Property->getValueAsInt("ArgNo");
670       ArgumentAttributes.push_back(std::make_pair(ArgNo, Returned));
671     } else if (Property->isSubClassOf("ReadOnly")) {
672       unsigned ArgNo = Property->getValueAsInt("ArgNo");
673       ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadOnly));
674     } else if (Property->isSubClassOf("WriteOnly")) {
675       unsigned ArgNo = Property->getValueAsInt("ArgNo");
676       ArgumentAttributes.push_back(std::make_pair(ArgNo, WriteOnly));
677     } else if (Property->isSubClassOf("ReadNone")) {
678       unsigned ArgNo = Property->getValueAsInt("ArgNo");
679       ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadNone));
680     } else
681       llvm_unreachable("Unknown property!");
682   }
683 
684   // Sort the argument attributes for later benefit.
685   std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
686 }
687