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