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