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