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