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