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