xref: /llvm-project/llvm/utils/TableGen/Common/CodeGenTarget.cpp (revision fa3d789df15bd1f58fb8ba4ea3be909218cf7f03)
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 "CodeGenInstruction.h"
18 #include "CodeGenRegisters.h"
19 #include "CodeGenSchedule.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 #include <algorithm>
27 #include <iterator>
28 #include <tuple>
29 using namespace llvm;
30 
31 cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
32 cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
33 
34 static cl::opt<unsigned>
35     AsmParserNum("asmparsernum", cl::init(0),
36                  cl::desc("Make -gen-asm-parser emit assembly parser #N"),
37                  cl::cat(AsmParserCat));
38 
39 static cl::opt<unsigned>
40     AsmWriterNum("asmwriternum", cl::init(0),
41                  cl::desc("Make -gen-asm-writer emit assembly writer #N"),
42                  cl::cat(AsmWriterCat));
43 
44 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
45 /// record corresponds to.
46 MVT::SimpleValueType llvm::getValueType(const Record *Rec) {
47   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
48 }
49 
50 StringRef llvm::getName(MVT::SimpleValueType T) {
51   switch (T) {
52   case MVT::Other:
53     return "UNKNOWN";
54   case MVT::iPTR:
55     return "TLI.getPointerTy()";
56   case MVT::iPTRAny:
57     return "TLI.getPointerTy()";
58   default:
59     return getEnumName(T);
60   }
61 }
62 
63 StringRef llvm::getEnumName(MVT::SimpleValueType T) {
64   // clang-format off
65   switch (T) {
66   case MVT::Other:    return "MVT::Other";
67   case MVT::i1:       return "MVT::i1";
68   case MVT::i2:       return "MVT::i2";
69   case MVT::i4:       return "MVT::i4";
70   case MVT::i8:       return "MVT::i8";
71   case MVT::i16:      return "MVT::i16";
72   case MVT::i32:      return "MVT::i32";
73   case MVT::i64:      return "MVT::i64";
74   case MVT::i128:     return "MVT::i128";
75   case MVT::Any:      return "MVT::Any";
76   case MVT::iAny:     return "MVT::iAny";
77   case MVT::fAny:     return "MVT::fAny";
78   case MVT::vAny:     return "MVT::vAny";
79   case MVT::f16:      return "MVT::f16";
80   case MVT::bf16:     return "MVT::bf16";
81   case MVT::f32:      return "MVT::f32";
82   case MVT::f64:      return "MVT::f64";
83   case MVT::f80:      return "MVT::f80";
84   case MVT::f128:     return "MVT::f128";
85   case MVT::ppcf128:  return "MVT::ppcf128";
86   case MVT::x86mmx:   return "MVT::x86mmx";
87   case MVT::x86amx:   return "MVT::x86amx";
88   case MVT::aarch64svcount:   return "MVT::aarch64svcount";
89   case MVT::i64x8:    return "MVT::i64x8";
90   case MVT::Glue:     return "MVT::Glue";
91   case MVT::isVoid:   return "MVT::isVoid";
92   case MVT::v1i1:     return "MVT::v1i1";
93   case MVT::v2i1:     return "MVT::v2i1";
94   case MVT::v3i1:     return "MVT::v3i1";
95   case MVT::v4i1:     return "MVT::v4i1";
96   case MVT::v8i1:     return "MVT::v8i1";
97   case MVT::v16i1:    return "MVT::v16i1";
98   case MVT::v32i1:    return "MVT::v32i1";
99   case MVT::v64i1:    return "MVT::v64i1";
100   case MVT::v128i1:   return "MVT::v128i1";
101   case MVT::v256i1:   return "MVT::v256i1";
102   case MVT::v512i1:   return "MVT::v512i1";
103   case MVT::v1024i1:  return "MVT::v1024i1";
104   case MVT::v2048i1:  return "MVT::v2048i1";
105   case MVT::v128i2:   return "MVT::v128i2";
106   case MVT::v256i2:   return "MVT::v256i2";
107   case MVT::v64i4:    return "MVT::v64i4";
108   case MVT::v128i4:   return "MVT::v128i4";
109   case MVT::v1i8:     return "MVT::v1i8";
110   case MVT::v2i8:     return "MVT::v2i8";
111   case MVT::v3i8:     return "MVT::v3i8";
112   case MVT::v4i8:     return "MVT::v4i8";
113   case MVT::v8i8:     return "MVT::v8i8";
114   case MVT::v16i8:    return "MVT::v16i8";
115   case MVT::v32i8:    return "MVT::v32i8";
116   case MVT::v64i8:    return "MVT::v64i8";
117   case MVT::v128i8:   return "MVT::v128i8";
118   case MVT::v256i8:   return "MVT::v256i8";
119   case MVT::v512i8:   return "MVT::v512i8";
120   case MVT::v1024i8:  return "MVT::v1024i8";
121   case MVT::v1i16:    return "MVT::v1i16";
122   case MVT::v2i16:    return "MVT::v2i16";
123   case MVT::v3i16:    return "MVT::v3i16";
124   case MVT::v4i16:    return "MVT::v4i16";
125   case MVT::v8i16:    return "MVT::v8i16";
126   case MVT::v16i16:   return "MVT::v16i16";
127   case MVT::v32i16:   return "MVT::v32i16";
128   case MVT::v64i16:   return "MVT::v64i16";
129   case MVT::v128i16:  return "MVT::v128i16";
130   case MVT::v256i16:  return "MVT::v256i16";
131   case MVT::v512i16:  return "MVT::v512i16";
132   case MVT::v1i32:    return "MVT::v1i32";
133   case MVT::v2i32:    return "MVT::v2i32";
134   case MVT::v3i32:    return "MVT::v3i32";
135   case MVT::v4i32:    return "MVT::v4i32";
136   case MVT::v5i32:    return "MVT::v5i32";
137   case MVT::v6i32:    return "MVT::v6i32";
138   case MVT::v7i32:    return "MVT::v7i32";
139   case MVT::v8i32:    return "MVT::v8i32";
140   case MVT::v9i32:    return "MVT::v9i32";
141   case MVT::v10i32:   return "MVT::v10i32";
142   case MVT::v11i32:   return "MVT::v11i32";
143   case MVT::v12i32:   return "MVT::v12i32";
144   case MVT::v16i32:   return "MVT::v16i32";
145   case MVT::v32i32:   return "MVT::v32i32";
146   case MVT::v64i32:   return "MVT::v64i32";
147   case MVT::v128i32:  return "MVT::v128i32";
148   case MVT::v256i32:  return "MVT::v256i32";
149   case MVT::v512i32:  return "MVT::v512i32";
150   case MVT::v1024i32: return "MVT::v1024i32";
151   case MVT::v2048i32: return "MVT::v2048i32";
152   case MVT::v1i64:    return "MVT::v1i64";
153   case MVT::v2i64:    return "MVT::v2i64";
154   case MVT::v3i64:    return "MVT::v3i64";
155   case MVT::v4i64:    return "MVT::v4i64";
156   case MVT::v8i64:    return "MVT::v8i64";
157   case MVT::v16i64:   return "MVT::v16i64";
158   case MVT::v32i64:   return "MVT::v32i64";
159   case MVT::v64i64:   return "MVT::v64i64";
160   case MVT::v128i64:  return "MVT::v128i64";
161   case MVT::v256i64:  return "MVT::v256i64";
162   case MVT::v1i128:   return "MVT::v1i128";
163   case MVT::v1f16:    return "MVT::v1f16";
164   case MVT::v2f16:    return "MVT::v2f16";
165   case MVT::v3f16:    return "MVT::v3f16";
166   case MVT::v4f16:    return "MVT::v4f16";
167   case MVT::v8f16:    return "MVT::v8f16";
168   case MVT::v16f16:   return "MVT::v16f16";
169   case MVT::v32f16:   return "MVT::v32f16";
170   case MVT::v64f16:   return "MVT::v64f16";
171   case MVT::v128f16:  return "MVT::v128f16";
172   case MVT::v256f16:  return "MVT::v256f16";
173   case MVT::v512f16:  return "MVT::v512f16";
174   case MVT::v2bf16:   return "MVT::v2bf16";
175   case MVT::v3bf16:   return "MVT::v3bf16";
176   case MVT::v4bf16:   return "MVT::v4bf16";
177   case MVT::v8bf16:   return "MVT::v8bf16";
178   case MVT::v16bf16:  return "MVT::v16bf16";
179   case MVT::v32bf16:  return "MVT::v32bf16";
180   case MVT::v64bf16:  return "MVT::v64bf16";
181   case MVT::v128bf16: return "MVT::v128bf16";
182   case MVT::v1f32:    return "MVT::v1f32";
183   case MVT::v2f32:    return "MVT::v2f32";
184   case MVT::v3f32:    return "MVT::v3f32";
185   case MVT::v4f32:    return "MVT::v4f32";
186   case MVT::v5f32:    return "MVT::v5f32";
187   case MVT::v6f32:    return "MVT::v6f32";
188   case MVT::v7f32:    return "MVT::v7f32";
189   case MVT::v8f32:    return "MVT::v8f32";
190   case MVT::v9f32:    return "MVT::v9f32";
191   case MVT::v10f32:   return "MVT::v10f32";
192   case MVT::v11f32:   return "MVT::v11f32";
193   case MVT::v12f32:   return "MVT::v12f32";
194   case MVT::v16f32:   return "MVT::v16f32";
195   case MVT::v32f32:   return "MVT::v32f32";
196   case MVT::v64f32:   return "MVT::v64f32";
197   case MVT::v128f32:  return "MVT::v128f32";
198   case MVT::v256f32:  return "MVT::v256f32";
199   case MVT::v512f32:  return "MVT::v512f32";
200   case MVT::v1024f32: return "MVT::v1024f32";
201   case MVT::v2048f32: return "MVT::v2048f32";
202   case MVT::v1f64:    return "MVT::v1f64";
203   case MVT::v2f64:    return "MVT::v2f64";
204   case MVT::v3f64:    return "MVT::v3f64";
205   case MVT::v4f64:    return "MVT::v4f64";
206   case MVT::v8f64:    return "MVT::v8f64";
207   case MVT::v16f64:   return "MVT::v16f64";
208   case MVT::v32f64:   return "MVT::v32f64";
209   case MVT::v64f64:   return "MVT::v64f64";
210   case MVT::v128f64:  return "MVT::v128f64";
211   case MVT::v256f64:  return "MVT::v256f64";
212   case MVT::nxv1i1:   return "MVT::nxv1i1";
213   case MVT::nxv2i1:   return "MVT::nxv2i1";
214   case MVT::nxv4i1:   return "MVT::nxv4i1";
215   case MVT::nxv8i1:   return "MVT::nxv8i1";
216   case MVT::nxv16i1:  return "MVT::nxv16i1";
217   case MVT::nxv32i1:  return "MVT::nxv32i1";
218   case MVT::nxv64i1:  return "MVT::nxv64i1";
219   case MVT::nxv1i8:   return "MVT::nxv1i8";
220   case MVT::nxv2i8:   return "MVT::nxv2i8";
221   case MVT::nxv4i8:   return "MVT::nxv4i8";
222   case MVT::nxv8i8:   return "MVT::nxv8i8";
223   case MVT::nxv16i8:  return "MVT::nxv16i8";
224   case MVT::nxv32i8:  return "MVT::nxv32i8";
225   case MVT::nxv64i8:  return "MVT::nxv64i8";
226   case MVT::nxv1i16:  return "MVT::nxv1i16";
227   case MVT::nxv2i16:  return "MVT::nxv2i16";
228   case MVT::nxv4i16:  return "MVT::nxv4i16";
229   case MVT::nxv8i16:  return "MVT::nxv8i16";
230   case MVT::nxv16i16: return "MVT::nxv16i16";
231   case MVT::nxv32i16: return "MVT::nxv32i16";
232   case MVT::nxv1i32:  return "MVT::nxv1i32";
233   case MVT::nxv2i32:  return "MVT::nxv2i32";
234   case MVT::nxv4i32:  return "MVT::nxv4i32";
235   case MVT::nxv8i32:  return "MVT::nxv8i32";
236   case MVT::nxv16i32: return "MVT::nxv16i32";
237   case MVT::nxv32i32: return "MVT::nxv32i32";
238   case MVT::nxv1i64:  return "MVT::nxv1i64";
239   case MVT::nxv2i64:  return "MVT::nxv2i64";
240   case MVT::nxv4i64:  return "MVT::nxv4i64";
241   case MVT::nxv8i64:  return "MVT::nxv8i64";
242   case MVT::nxv16i64: return "MVT::nxv16i64";
243   case MVT::nxv32i64: return "MVT::nxv32i64";
244   case MVT::nxv1f16:  return "MVT::nxv1f16";
245   case MVT::nxv2f16:  return "MVT::nxv2f16";
246   case MVT::nxv4f16:  return "MVT::nxv4f16";
247   case MVT::nxv8f16:  return "MVT::nxv8f16";
248   case MVT::nxv16f16: return "MVT::nxv16f16";
249   case MVT::nxv32f16: return "MVT::nxv32f16";
250   case MVT::nxv1bf16:  return "MVT::nxv1bf16";
251   case MVT::nxv2bf16:  return "MVT::nxv2bf16";
252   case MVT::nxv4bf16:  return "MVT::nxv4bf16";
253   case MVT::nxv8bf16:  return "MVT::nxv8bf16";
254   case MVT::nxv16bf16: return "MVT::nxv16bf16";
255   case MVT::nxv32bf16: return "MVT::nxv32bf16";
256   case MVT::nxv1f32:   return "MVT::nxv1f32";
257   case MVT::nxv2f32:   return "MVT::nxv2f32";
258   case MVT::nxv4f32:   return "MVT::nxv4f32";
259   case MVT::nxv8f32:   return "MVT::nxv8f32";
260   case MVT::nxv16f32:  return "MVT::nxv16f32";
261   case MVT::nxv1f64:   return "MVT::nxv1f64";
262   case MVT::nxv2f64:   return "MVT::nxv2f64";
263   case MVT::nxv4f64:   return "MVT::nxv4f64";
264   case MVT::nxv8f64:   return "MVT::nxv8f64";
265   case MVT::token:     return "MVT::token";
266   case MVT::Metadata:  return "MVT::Metadata";
267   case MVT::iPTR:      return "MVT::iPTR";
268   case MVT::iPTRAny:   return "MVT::iPTRAny";
269   case MVT::Untyped:   return "MVT::Untyped";
270   case MVT::funcref:   return "MVT::funcref";
271   case MVT::externref: return "MVT::externref";
272   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
273   }
274   // clang-format on
275 }
276 
277 /// getQualifiedName - Return the name of the specified record, with a
278 /// namespace qualifier if the record contains one.
279 ///
280 std::string llvm::getQualifiedName(const Record *R) {
281   std::string Namespace;
282   if (R->getValue("Namespace"))
283     Namespace = std::string(R->getValueAsString("Namespace"));
284   if (Namespace.empty())
285     return std::string(R->getName());
286   return Namespace + "::" + R->getName().str();
287 }
288 
289 /// getTarget - Return the current instance of the Target class.
290 ///
291 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
292     : Records(records), CGH(records) {
293   std::vector<Record *> Targets = Records.getAllDerivedDefinitions("Target");
294   if (Targets.size() == 0)
295     PrintFatalError("No 'Target' subclasses defined!");
296   if (Targets.size() != 1)
297     PrintFatalError("Multiple subclasses of Target defined!");
298   TargetRec = Targets[0];
299   MacroFusions = Records.getAllDerivedDefinitions("Fusion");
300 }
301 
302 CodeGenTarget::~CodeGenTarget() {}
303 
304 StringRef CodeGenTarget::getName() const { return TargetRec->getName(); }
305 
306 /// getInstNamespace - Find and return the target machine's instruction
307 /// namespace. The namespace is cached because it is requested multiple times.
308 StringRef CodeGenTarget::getInstNamespace() const {
309   if (InstNamespace.empty()) {
310     for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
311       // We are not interested in the "TargetOpcode" namespace.
312       if (Inst->Namespace != "TargetOpcode") {
313         InstNamespace = Inst->Namespace;
314         break;
315       }
316     }
317   }
318 
319   return InstNamespace;
320 }
321 
322 StringRef CodeGenTarget::getRegNamespace() const {
323   auto &RegClasses = RegBank->getRegClasses();
324   return RegClasses.size() > 0 ? RegClasses.front().Namespace : "";
325 }
326 
327 Record *CodeGenTarget::getInstructionSet() const {
328   return TargetRec->getValueAsDef("InstructionSet");
329 }
330 
331 bool CodeGenTarget::getAllowRegisterRenaming() const {
332   return TargetRec->getValueAsInt("AllowRegisterRenaming");
333 }
334 
335 /// getAsmParser - Return the AssemblyParser definition for this target.
336 ///
337 Record *CodeGenTarget::getAsmParser() const {
338   std::vector<Record *> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
339   if (AsmParserNum >= LI.size())
340     PrintFatalError("Target does not have an AsmParser #" +
341                     Twine(AsmParserNum) + "!");
342   return LI[AsmParserNum];
343 }
344 
345 /// getAsmParserVariant - Return the AssemblyParserVariant definition for
346 /// this target.
347 ///
348 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
349   std::vector<Record *> LI =
350       TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
351   if (i >= LI.size())
352     PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
353                     "!");
354   return LI[i];
355 }
356 
357 /// getAsmParserVariantCount - Return the AssemblyParserVariant definition
358 /// available for this target.
359 ///
360 unsigned CodeGenTarget::getAsmParserVariantCount() const {
361   std::vector<Record *> LI =
362       TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
363   return LI.size();
364 }
365 
366 /// getAsmWriter - Return the AssemblyWriter definition for this target.
367 ///
368 Record *CodeGenTarget::getAsmWriter() const {
369   std::vector<Record *> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
370   if (AsmWriterNum >= LI.size())
371     PrintFatalError("Target does not have an AsmWriter #" +
372                     Twine(AsmWriterNum) + "!");
373   return LI[AsmWriterNum];
374 }
375 
376 CodeGenRegBank &CodeGenTarget::getRegBank() const {
377   if (!RegBank)
378     RegBank = std::make_unique<CodeGenRegBank>(Records, getHwModes());
379   return *RegBank;
380 }
381 
382 std::optional<CodeGenRegisterClass *> CodeGenTarget::getSuperRegForSubReg(
383     const ValueTypeByHwMode &ValueTy, CodeGenRegBank &RegBank,
384     const CodeGenSubRegIndex *SubIdx, bool MustBeAllocatable) const {
385   std::vector<CodeGenRegisterClass *> Candidates;
386   auto &RegClasses = RegBank.getRegClasses();
387 
388   // Try to find a register class which supports ValueTy, and also contains
389   // SubIdx.
390   for (CodeGenRegisterClass &RC : RegClasses) {
391     // Is there a subclass of this class which contains this subregister index?
392     CodeGenRegisterClass *SubClassWithSubReg = RC.getSubClassWithSubReg(SubIdx);
393     if (!SubClassWithSubReg)
394       continue;
395 
396     // We have a class. Check if it supports this value type.
397     if (!llvm::is_contained(SubClassWithSubReg->VTs, ValueTy))
398       continue;
399 
400     // If necessary, check that it is allocatable.
401     if (MustBeAllocatable && !SubClassWithSubReg->Allocatable)
402       continue;
403 
404     // We have a register class which supports both the value type and
405     // subregister index. Remember it.
406     Candidates.push_back(SubClassWithSubReg);
407   }
408 
409   // If we didn't find anything, we're done.
410   if (Candidates.empty())
411     return std::nullopt;
412 
413   // Find and return the largest of our candidate classes.
414   llvm::stable_sort(Candidates, [&](const CodeGenRegisterClass *A,
415                                     const CodeGenRegisterClass *B) {
416     if (A->getMembers().size() > B->getMembers().size())
417       return true;
418 
419     if (A->getMembers().size() < B->getMembers().size())
420       return false;
421 
422     // Order by name as a tie-breaker.
423     return StringRef(A->getName()) < B->getName();
424   });
425 
426   return Candidates[0];
427 }
428 
429 void CodeGenTarget::ReadRegAltNameIndices() const {
430   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
431   llvm::sort(RegAltNameIndices, LessRecord());
432 }
433 
434 /// getRegisterByName - If there is a register with the specific AsmName,
435 /// return it.
436 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
437   return getRegBank().getRegistersByName().lookup(Name);
438 }
439 
440 const CodeGenRegisterClass &CodeGenTarget::getRegisterClass(Record *R) const {
441   return *getRegBank().getRegClass(R);
442 }
443 
444 std::vector<ValueTypeByHwMode> CodeGenTarget::getRegisterVTs(Record *R) const {
445   const CodeGenRegister *Reg = getRegBank().getReg(R);
446   std::vector<ValueTypeByHwMode> Result;
447   for (const auto &RC : getRegBank().getRegClasses()) {
448     if (RC.contains(Reg)) {
449       ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
450       llvm::append_range(Result, InVTs);
451     }
452   }
453 
454   // Remove duplicates.
455   llvm::sort(Result);
456   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
457   return Result;
458 }
459 
460 void CodeGenTarget::ReadLegalValueTypes() const {
461   for (const auto &RC : getRegBank().getRegClasses())
462     llvm::append_range(LegalValueTypes, RC.VTs);
463 
464   // Remove duplicates.
465   llvm::sort(LegalValueTypes);
466   LegalValueTypes.erase(
467       std::unique(LegalValueTypes.begin(), LegalValueTypes.end()),
468       LegalValueTypes.end());
469 }
470 
471 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
472   if (!SchedModels)
473     SchedModels = std::make_unique<CodeGenSchedModels>(Records, *this);
474   return *SchedModels;
475 }
476 
477 void CodeGenTarget::ReadInstructions() const {
478   std::vector<Record *> Insts = Records.getAllDerivedDefinitions("Instruction");
479   if (Insts.size() <= 2)
480     PrintFatalError("No 'Instruction' subclasses defined!");
481 
482   // Parse the instructions defined in the .td file.
483   for (Record *R : Insts) {
484     Instructions[R] = std::make_unique<CodeGenInstruction>(R);
485     if (Instructions[R]->isVariableLengthEncoding())
486       HasVariableLengthEncodings = true;
487   }
488 }
489 
490 static const CodeGenInstruction *GetInstByName(
491     const char *Name,
492     const DenseMap<const Record *, std::unique_ptr<CodeGenInstruction>> &Insts,
493     RecordKeeper &Records) {
494   const Record *Rec = Records.getDef(Name);
495 
496   const auto I = Insts.find(Rec);
497   if (!Rec || I == Insts.end())
498     PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
499   return I->second.get();
500 }
501 
502 static const char *FixedInstrs[] = {
503 #define HANDLE_TARGET_OPCODE(OPC) #OPC,
504 #include "llvm/Support/TargetOpcodes.def"
505     nullptr};
506 
507 unsigned CodeGenTarget::getNumFixedInstructions() {
508   return std::size(FixedInstrs) - 1;
509 }
510 
511 /// Return all of the instructions defined by the target, ordered by
512 /// their enum value.
513 void CodeGenTarget::ComputeInstrsByEnum() const {
514   const auto &Insts = getInstructions();
515   for (const char *const *p = FixedInstrs; *p; ++p) {
516     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
517     assert(Instr && "Missing target independent instruction");
518     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
519     InstrsByEnum.push_back(Instr);
520   }
521   unsigned EndOfPredefines = InstrsByEnum.size();
522   assert(EndOfPredefines == getNumFixedInstructions() &&
523          "Missing generic opcode");
524 
525   for (const auto &I : Insts) {
526     const CodeGenInstruction *CGI = I.second.get();
527     if (CGI->Namespace != "TargetOpcode") {
528       InstrsByEnum.push_back(CGI);
529       if (CGI->TheDef->getValueAsBit("isPseudo"))
530         ++NumPseudoInstructions;
531     }
532   }
533 
534   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
535 
536   // All of the instructions are now in random order based on the map iteration.
537   llvm::sort(
538       InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
539       [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
540         const auto &D1 = *Rec1->TheDef;
541         const auto &D2 = *Rec2->TheDef;
542         return std::tuple(!D1.getValueAsBit("isPseudo"), D1.getName()) <
543                std::tuple(!D2.getValueAsBit("isPseudo"), D2.getName());
544       });
545 
546   // Assign an enum value to each instruction according to the sorted order.
547   unsigned Num = 0;
548   for (const CodeGenInstruction *Inst : InstrsByEnum)
549     Inst->EnumVal = Num++;
550 }
551 
552 /// isLittleEndianEncoding - Return whether this target encodes its instruction
553 /// in little-endian format, i.e. bits laid out in the order [0..n]
554 ///
555 bool CodeGenTarget::isLittleEndianEncoding() const {
556   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
557 }
558 
559 /// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
560 /// encodings, reverse the bit order of all instructions.
561 void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
562   if (!isLittleEndianEncoding())
563     return;
564 
565   std::vector<Record *> Insts =
566       Records.getAllDerivedDefinitions("InstructionEncoding");
567   for (Record *R : Insts) {
568     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
569         R->getValueAsBit("isPseudo"))
570       continue;
571 
572     BitsInit *BI = R->getValueAsBitsInit("Inst");
573 
574     unsigned numBits = BI->getNumBits();
575 
576     SmallVector<Init *, 16> NewBits(numBits);
577 
578     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
579       unsigned bitSwapIdx = numBits - bit - 1;
580       Init *OrigBit = BI->getBit(bit);
581       Init *BitSwap = BI->getBit(bitSwapIdx);
582       NewBits[bit] = BitSwap;
583       NewBits[bitSwapIdx] = OrigBit;
584     }
585     if (numBits % 2) {
586       unsigned middle = (numBits + 1) / 2;
587       NewBits[middle] = BI->getBit(middle);
588     }
589 
590     BitsInit *NewBI = BitsInit::get(Records, NewBits);
591 
592     // Update the bits in reversed order so that emitInstrOpBits will get the
593     // correct endianness.
594     R->getValue("Inst")->setValue(NewBI);
595   }
596 }
597 
598 /// guessInstructionProperties - Return true if it's OK to guess instruction
599 /// properties instead of raising an error.
600 ///
601 /// This is configurable as a temporary migration aid. It will eventually be
602 /// permanently false.
603 bool CodeGenTarget::guessInstructionProperties() const {
604   return getInstructionSet()->getValueAsBit("guessInstructionProperties");
605 }
606 
607 //===----------------------------------------------------------------------===//
608 // ComplexPattern implementation
609 //
610 ComplexPattern::ComplexPattern(Record *R) {
611   Ty = R->getValueAsDef("Ty");
612   NumOperands = R->getValueAsInt("NumOperands");
613   SelectFunc = std::string(R->getValueAsString("SelectFunc"));
614   RootNodes = R->getValueAsListOfDefs("RootNodes");
615 
616   // FIXME: This is a hack to statically increase the priority of patterns which
617   // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
618   // possible pattern match we'll need to dynamically calculate the complexity
619   // of all patterns a dag can potentially map to.
620   int64_t RawComplexity = R->getValueAsInt("Complexity");
621   if (RawComplexity == -1)
622     Complexity = NumOperands * 3;
623   else
624     Complexity = RawComplexity;
625 
626   // FIXME: Why is this different from parseSDPatternOperatorProperties?
627   // Parse the properties.
628   Properties = 0;
629   std::vector<Record *> PropList = R->getValueAsListOfDefs("Properties");
630   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
631     if (PropList[i]->getName() == "SDNPHasChain") {
632       Properties |= 1 << SDNPHasChain;
633     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
634       Properties |= 1 << SDNPOptInGlue;
635     } else if (PropList[i]->getName() == "SDNPMayStore") {
636       Properties |= 1 << SDNPMayStore;
637     } else if (PropList[i]->getName() == "SDNPMayLoad") {
638       Properties |= 1 << SDNPMayLoad;
639     } else if (PropList[i]->getName() == "SDNPSideEffect") {
640       Properties |= 1 << SDNPSideEffect;
641     } else if (PropList[i]->getName() == "SDNPMemOperand") {
642       Properties |= 1 << SDNPMemOperand;
643     } else if (PropList[i]->getName() == "SDNPVariadic") {
644       Properties |= 1 << SDNPVariadic;
645     } else if (PropList[i]->getName() == "SDNPWantRoot") {
646       Properties |= 1 << SDNPWantRoot;
647     } else if (PropList[i]->getName() == "SDNPWantParent") {
648       Properties |= 1 << SDNPWantParent;
649     } else {
650       PrintFatalError(R->getLoc(), "Unsupported SD Node property '" +
651                                        PropList[i]->getName() +
652                                        "' on ComplexPattern '" + R->getName() +
653                                        "'!");
654     }
655 }
656