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