1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class wraps target description classes used by the various code
11 // generation TableGen backends.  This makes it easier to access the data and
12 // provides a single place that needs to check it for validity.  All of these
13 // classes abort on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CodeGenTarget.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/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include <algorithm>
26 using namespace llvm;
27 
28 cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
29 cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
30 
31 static cl::opt<unsigned>
32     AsmParserNum("asmparsernum", cl::init(0),
33                  cl::desc("Make -gen-asm-parser emit assembly parser #N"),
34                  cl::cat(AsmParserCat));
35 
36 static cl::opt<unsigned>
37     AsmWriterNum("asmwriternum", cl::init(0),
38                  cl::desc("Make -gen-asm-writer emit assembly writer #N"),
39                  cl::cat(AsmWriterCat));
40 
41 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
42 /// record corresponds to.
43 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
44   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
45 }
46 
47 StringRef llvm::getName(MVT::SimpleValueType T) {
48   switch (T) {
49   case MVT::Other:   return "UNKNOWN";
50   case MVT::iPTR:    return "TLI.getPointerTy()";
51   case MVT::iPTRAny: return "TLI.getPointerTy()";
52   default: return getEnumName(T);
53   }
54 }
55 
56 StringRef llvm::getEnumName(MVT::SimpleValueType T) {
57   switch (T) {
58   case MVT::Other:    return "MVT::Other";
59   case MVT::i1:       return "MVT::i1";
60   case MVT::i8:       return "MVT::i8";
61   case MVT::i16:      return "MVT::i16";
62   case MVT::i32:      return "MVT::i32";
63   case MVT::i64:      return "MVT::i64";
64   case MVT::i128:     return "MVT::i128";
65   case MVT::Any:      return "MVT::Any";
66   case MVT::iAny:     return "MVT::iAny";
67   case MVT::fAny:     return "MVT::fAny";
68   case MVT::vAny:     return "MVT::vAny";
69   case MVT::f16:      return "MVT::f16";
70   case MVT::f32:      return "MVT::f32";
71   case MVT::f64:      return "MVT::f64";
72   case MVT::f80:      return "MVT::f80";
73   case MVT::f128:     return "MVT::f128";
74   case MVT::ppcf128:  return "MVT::ppcf128";
75   case MVT::x86mmx:   return "MVT::x86mmx";
76   case MVT::Glue:     return "MVT::Glue";
77   case MVT::isVoid:   return "MVT::isVoid";
78   case MVT::v2i1:     return "MVT::v2i1";
79   case MVT::v4i1:     return "MVT::v4i1";
80   case MVT::v8i1:     return "MVT::v8i1";
81   case MVT::v16i1:    return "MVT::v16i1";
82   case MVT::v32i1:    return "MVT::v32i1";
83   case MVT::v64i1:    return "MVT::v64i1";
84   case MVT::v512i1:   return "MVT::v512i1";
85   case MVT::v1024i1:  return "MVT::v1024i1";
86   case MVT::v1i8:     return "MVT::v1i8";
87   case MVT::v2i8:     return "MVT::v2i8";
88   case MVT::v4i8:     return "MVT::v4i8";
89   case MVT::v8i8:     return "MVT::v8i8";
90   case MVT::v16i8:    return "MVT::v16i8";
91   case MVT::v32i8:    return "MVT::v32i8";
92   case MVT::v64i8:    return "MVT::v64i8";
93   case MVT::v128i8:   return "MVT::v128i8";
94   case MVT::v256i8:   return "MVT::v256i8";
95   case MVT::v1i16:    return "MVT::v1i16";
96   case MVT::v2i16:    return "MVT::v2i16";
97   case MVT::v4i16:    return "MVT::v4i16";
98   case MVT::v8i16:    return "MVT::v8i16";
99   case MVT::v16i16:   return "MVT::v16i16";
100   case MVT::v32i16:   return "MVT::v32i16";
101   case MVT::v64i16:   return "MVT::v64i16";
102   case MVT::v128i16:  return "MVT::v128i16";
103   case MVT::v1i32:    return "MVT::v1i32";
104   case MVT::v2i32:    return "MVT::v2i32";
105   case MVT::v4i32:    return "MVT::v4i32";
106   case MVT::v8i32:    return "MVT::v8i32";
107   case MVT::v16i32:   return "MVT::v16i32";
108   case MVT::v32i32:   return "MVT::v32i32";
109   case MVT::v64i32:   return "MVT::v64i32";
110   case MVT::v1i64:    return "MVT::v1i64";
111   case MVT::v2i64:    return "MVT::v2i64";
112   case MVT::v4i64:    return "MVT::v4i64";
113   case MVT::v8i64:    return "MVT::v8i64";
114   case MVT::v16i64:   return "MVT::v16i64";
115   case MVT::v32i64:   return "MVT::v32i64";
116   case MVT::v1i128:   return "MVT::v1i128";
117   case MVT::v2f16:    return "MVT::v2f16";
118   case MVT::v4f16:    return "MVT::v4f16";
119   case MVT::v8f16:    return "MVT::v8f16";
120   case MVT::v1f32:    return "MVT::v1f32";
121   case MVT::v2f32:    return "MVT::v2f32";
122   case MVT::v4f32:    return "MVT::v4f32";
123   case MVT::v8f32:    return "MVT::v8f32";
124   case MVT::v16f32:   return "MVT::v16f32";
125   case MVT::v1f64:    return "MVT::v1f64";
126   case MVT::v2f64:    return "MVT::v2f64";
127   case MVT::v4f64:    return "MVT::v4f64";
128   case MVT::v8f64:    return "MVT::v8f64";
129   case MVT::token:    return "MVT::token";
130   case MVT::Metadata: return "MVT::Metadata";
131   case MVT::iPTR:     return "MVT::iPTR";
132   case MVT::iPTRAny:  return "MVT::iPTRAny";
133   case MVT::Untyped:  return "MVT::Untyped";
134   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
135   }
136 }
137 
138 /// getQualifiedName - Return the name of the specified record, with a
139 /// namespace qualifier if the record contains one.
140 ///
141 std::string llvm::getQualifiedName(const Record *R) {
142   std::string Namespace;
143   if (R->getValue("Namespace"))
144      Namespace = R->getValueAsString("Namespace");
145   if (Namespace.empty()) return R->getName();
146   return Namespace + "::" + R->getName().str();
147 }
148 
149 
150 /// getTarget - Return the current instance of the Target class.
151 ///
152 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
153   : Records(records) {
154   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
155   if (Targets.size() == 0)
156     PrintFatalError("ERROR: No 'Target' subclasses defined!");
157   if (Targets.size() != 1)
158     PrintFatalError("ERROR: Multiple subclasses of Target defined!");
159   TargetRec = Targets[0];
160 }
161 
162 CodeGenTarget::~CodeGenTarget() {
163 }
164 
165 const StringRef CodeGenTarget::getName() const {
166   return TargetRec->getName();
167 }
168 
169 std::string CodeGenTarget::getInstNamespace() const {
170   for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
171     // Make sure not to pick up "TargetOpcode" by accidentally getting
172     // the namespace off the PHI instruction or something.
173     if (Inst->Namespace != "TargetOpcode")
174       return Inst->Namespace;
175   }
176 
177   return "";
178 }
179 
180 Record *CodeGenTarget::getInstructionSet() const {
181   return TargetRec->getValueAsDef("InstructionSet");
182 }
183 
184 
185 /// getAsmParser - Return the AssemblyParser definition for this target.
186 ///
187 Record *CodeGenTarget::getAsmParser() const {
188   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
189   if (AsmParserNum >= LI.size())
190     PrintFatalError("Target does not have an AsmParser #" +
191                     Twine(AsmParserNum) + "!");
192   return LI[AsmParserNum];
193 }
194 
195 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
196 /// this target.
197 ///
198 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
199   std::vector<Record*> LI =
200     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
201   if (i >= LI.size())
202     PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
203                     "!");
204   return LI[i];
205 }
206 
207 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
208 /// available for this target.
209 ///
210 unsigned CodeGenTarget::getAsmParserVariantCount() const {
211   std::vector<Record*> LI =
212     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
213   return LI.size();
214 }
215 
216 /// getAsmWriter - Return the AssemblyWriter definition for this target.
217 ///
218 Record *CodeGenTarget::getAsmWriter() const {
219   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
220   if (AsmWriterNum >= LI.size())
221     PrintFatalError("Target does not have an AsmWriter #" +
222                     Twine(AsmWriterNum) + "!");
223   return LI[AsmWriterNum];
224 }
225 
226 CodeGenRegBank &CodeGenTarget::getRegBank() const {
227   if (!RegBank)
228     RegBank = llvm::make_unique<CodeGenRegBank>(Records);
229   return *RegBank;
230 }
231 
232 void CodeGenTarget::ReadRegAltNameIndices() const {
233   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
234   std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
235 }
236 
237 /// getRegisterByName - If there is a register with the specific AsmName,
238 /// return it.
239 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
240   const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
241   StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
242   if (I == Regs.end())
243     return nullptr;
244   return I->second;
245 }
246 
247 std::vector<MVT::SimpleValueType> CodeGenTarget::
248 getRegisterVTs(Record *R) const {
249   const CodeGenRegister *Reg = getRegBank().getReg(R);
250   std::vector<MVT::SimpleValueType> Result;
251   for (const auto &RC : getRegBank().getRegClasses()) {
252     if (RC.contains(Reg)) {
253       ArrayRef<MVT::SimpleValueType> InVTs = RC.getValueTypes();
254       Result.insert(Result.end(), InVTs.begin(), InVTs.end());
255     }
256   }
257 
258   // Remove duplicates.
259   array_pod_sort(Result.begin(), Result.end());
260   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
261   return Result;
262 }
263 
264 
265 void CodeGenTarget::ReadLegalValueTypes() const {
266   for (const auto &RC : getRegBank().getRegClasses())
267     LegalValueTypes.insert(LegalValueTypes.end(), RC.VTs.begin(), RC.VTs.end());
268 
269   // Remove duplicates.
270   array_pod_sort(LegalValueTypes.begin(), LegalValueTypes.end());
271   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
272                                     LegalValueTypes.end()),
273                         LegalValueTypes.end());
274 }
275 
276 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
277   if (!SchedModels)
278     SchedModels = llvm::make_unique<CodeGenSchedModels>(Records, *this);
279   return *SchedModels;
280 }
281 
282 void CodeGenTarget::ReadInstructions() const {
283   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
284   if (Insts.size() <= 2)
285     PrintFatalError("No 'Instruction' subclasses defined!");
286 
287   // Parse the instructions defined in the .td file.
288   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
289     Instructions[Insts[i]] = llvm::make_unique<CodeGenInstruction>(Insts[i]);
290 }
291 
292 static const CodeGenInstruction *
293 GetInstByName(const char *Name,
294               const DenseMap<const Record*,
295                              std::unique_ptr<CodeGenInstruction>> &Insts,
296               RecordKeeper &Records) {
297   const Record *Rec = Records.getDef(Name);
298 
299   const auto I = Insts.find(Rec);
300   if (!Rec || I == Insts.end())
301     PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
302   return I->second.get();
303 }
304 
305 /// \brief Return all of the instructions defined by the target, ordered by
306 /// their enum value.
307 void CodeGenTarget::ComputeInstrsByEnum() const {
308   static const char *const FixedInstrs[] = {
309 #define HANDLE_TARGET_OPCODE(OPC) #OPC,
310 #include "llvm/Target/TargetOpcodes.def"
311       nullptr};
312   const auto &Insts = getInstructions();
313   for (const char *const *p = FixedInstrs; *p; ++p) {
314     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
315     assert(Instr && "Missing target independent instruction");
316     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
317     InstrsByEnum.push_back(Instr);
318   }
319   unsigned EndOfPredefines = InstrsByEnum.size();
320 
321   for (const auto &I : Insts) {
322     const CodeGenInstruction *CGI = I.second.get();
323     if (CGI->Namespace != "TargetOpcode")
324       InstrsByEnum.push_back(CGI);
325   }
326 
327   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
328 
329   // All of the instructions are now in random order based on the map iteration.
330   // Sort them by name.
331   std::sort(InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
332             [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
333     return Rec1->TheDef->getName() < Rec2->TheDef->getName();
334   });
335 }
336 
337 
338 /// isLittleEndianEncoding - Return whether this target encodes its instruction
339 /// in little-endian format, i.e. bits laid out in the order [0..n]
340 ///
341 bool CodeGenTarget::isLittleEndianEncoding() const {
342   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
343 }
344 
345 /// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
346 /// encodings, reverse the bit order of all instructions.
347 void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
348   if (!isLittleEndianEncoding())
349     return;
350 
351   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
352   for (Record *R : Insts) {
353     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
354         R->getValueAsBit("isPseudo"))
355       continue;
356 
357     BitsInit *BI = R->getValueAsBitsInit("Inst");
358 
359     unsigned numBits = BI->getNumBits();
360 
361     SmallVector<Init *, 16> NewBits(numBits);
362 
363     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
364       unsigned bitSwapIdx = numBits - bit - 1;
365       Init *OrigBit = BI->getBit(bit);
366       Init *BitSwap = BI->getBit(bitSwapIdx);
367       NewBits[bit]        = BitSwap;
368       NewBits[bitSwapIdx] = OrigBit;
369     }
370     if (numBits % 2) {
371       unsigned middle = (numBits + 1) / 2;
372       NewBits[middle] = BI->getBit(middle);
373     }
374 
375     BitsInit *NewBI = BitsInit::get(NewBits);
376 
377     // Update the bits in reversed order so that emitInstrOpBits will get the
378     // correct endianness.
379     R->getValue("Inst")->setValue(NewBI);
380   }
381 }
382 
383 /// guessInstructionProperties - Return true if it's OK to guess instruction
384 /// properties instead of raising an error.
385 ///
386 /// This is configurable as a temporary migration aid. It will eventually be
387 /// permanently false.
388 bool CodeGenTarget::guessInstructionProperties() const {
389   return getInstructionSet()->getValueAsBit("guessInstructionProperties");
390 }
391 
392 //===----------------------------------------------------------------------===//
393 // ComplexPattern implementation
394 //
395 ComplexPattern::ComplexPattern(Record *R) {
396   Ty          = ::getValueType(R->getValueAsDef("Ty"));
397   NumOperands = R->getValueAsInt("NumOperands");
398   SelectFunc  = R->getValueAsString("SelectFunc");
399   RootNodes   = R->getValueAsListOfDefs("RootNodes");
400 
401   // FIXME: This is a hack to statically increase the priority of patterns which
402   // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
403   // possible pattern match we'll need to dynamically calculate the complexity
404   // of all patterns a dag can potentially map to.
405   int64_t RawComplexity = R->getValueAsInt("Complexity");
406   if (RawComplexity == -1)
407     Complexity = NumOperands * 3;
408   else
409     Complexity = RawComplexity;
410 
411   // Parse the properties.
412   Properties = 0;
413   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
414   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
415     if (PropList[i]->getName() == "SDNPHasChain") {
416       Properties |= 1 << SDNPHasChain;
417     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
418       Properties |= 1 << SDNPOptInGlue;
419     } else if (PropList[i]->getName() == "SDNPMayStore") {
420       Properties |= 1 << SDNPMayStore;
421     } else if (PropList[i]->getName() == "SDNPMayLoad") {
422       Properties |= 1 << SDNPMayLoad;
423     } else if (PropList[i]->getName() == "SDNPSideEffect") {
424       Properties |= 1 << SDNPSideEffect;
425     } else if (PropList[i]->getName() == "SDNPMemOperand") {
426       Properties |= 1 << SDNPMemOperand;
427     } else if (PropList[i]->getName() == "SDNPVariadic") {
428       Properties |= 1 << SDNPVariadic;
429     } else if (PropList[i]->getName() == "SDNPWantRoot") {
430       Properties |= 1 << SDNPWantRoot;
431     } else if (PropList[i]->getName() == "SDNPWantParent") {
432       Properties |= 1 << SDNPWantParent;
433     } else {
434       PrintFatalError("Unsupported SD Node property '" +
435                       PropList[i]->getName() + "' on ComplexPattern '" +
436                       R->getName() + "'!");
437     }
438 }
439 
440 //===----------------------------------------------------------------------===//
441 // CodeGenIntrinsic Implementation
442 //===----------------------------------------------------------------------===//
443 
444 CodeGenIntrinsicTable::CodeGenIntrinsicTable(const RecordKeeper &RC,
445                                              bool TargetOnly) {
446   std::vector<Record*> Defs = RC.getAllDerivedDefinitions("Intrinsic");
447 
448   Intrinsics.reserve(Defs.size());
449 
450   for (unsigned I = 0, e = Defs.size(); I != e; ++I) {
451     bool isTarget = Defs[I]->getValueAsBit("isTarget");
452     if (isTarget == TargetOnly)
453       Intrinsics.push_back(CodeGenIntrinsic(Defs[I]));
454   }
455   std::sort(Intrinsics.begin(), Intrinsics.end(),
456             [](const CodeGenIntrinsic &LHS, const CodeGenIntrinsic &RHS) {
457               return std::tie(LHS.TargetPrefix, LHS.Name) <
458                      std::tie(RHS.TargetPrefix, RHS.Name);
459             });
460   Targets.push_back({"", 0, 0});
461   for (size_t I = 0, E = Intrinsics.size(); I < E; ++I)
462     if (Intrinsics[I].TargetPrefix != Targets.back().Name) {
463       Targets.back().Count = I - Targets.back().Offset;
464       Targets.push_back({Intrinsics[I].TargetPrefix, I, 0});
465     }
466   Targets.back().Count = Intrinsics.size() - Targets.back().Offset;
467 }
468 
469 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
470   TheDef = R;
471   std::string DefName = R->getName();
472   ModRef = ReadWriteMem;
473   isOverloaded = false;
474   isCommutative = false;
475   canThrow = false;
476   isNoReturn = false;
477   isNoDuplicate = false;
478   isConvergent = false;
479 
480   if (DefName.size() <= 4 ||
481       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
482     PrintFatalError("Intrinsic '" + DefName + "' does not start with 'int_'!");
483 
484   EnumName = std::string(DefName.begin()+4, DefName.end());
485 
486   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
487     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
488   if (R->getValue("MSBuiltinName"))   // Ignore a missing MSBuiltinName field.
489     MSBuiltinName = R->getValueAsString("MSBuiltinName");
490 
491   TargetPrefix = R->getValueAsString("TargetPrefix");
492   Name = R->getValueAsString("LLVMName");
493 
494   if (Name == "") {
495     // If an explicit name isn't specified, derive one from the DefName.
496     Name = "llvm.";
497 
498     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
499       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
500   } else {
501     // Verify it starts with "llvm.".
502     if (Name.size() <= 5 ||
503         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
504       PrintFatalError("Intrinsic '" + DefName + "'s name does not start with 'llvm.'!");
505   }
506 
507   // If TargetPrefix is specified, make sure that Name starts with
508   // "llvm.<targetprefix>.".
509   if (!TargetPrefix.empty()) {
510     if (Name.size() < 6+TargetPrefix.size() ||
511         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
512         != (TargetPrefix + "."))
513       PrintFatalError("Intrinsic '" + DefName + "' does not start with 'llvm." +
514         TargetPrefix + ".'!");
515   }
516 
517   // Parse the list of return types.
518   std::vector<MVT::SimpleValueType> OverloadedVTs;
519   ListInit *TypeList = R->getValueAsListInit("RetTypes");
520   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
521     Record *TyEl = TypeList->getElementAsRecord(i);
522     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
523     MVT::SimpleValueType VT;
524     if (TyEl->isSubClassOf("LLVMMatchType")) {
525       unsigned MatchTy = TyEl->getValueAsInt("Number");
526       assert(MatchTy < OverloadedVTs.size() &&
527              "Invalid matching number!");
528       VT = OverloadedVTs[MatchTy];
529       // It only makes sense to use the extended and truncated vector element
530       // variants with iAny types; otherwise, if the intrinsic is not
531       // overloaded, all the types can be specified directly.
532       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
533                !TyEl->isSubClassOf("LLVMTruncatedType")) ||
534               VT == MVT::iAny || VT == MVT::vAny) &&
535              "Expected iAny or vAny type");
536     } else {
537       VT = getValueType(TyEl->getValueAsDef("VT"));
538     }
539     if (MVT(VT).isOverloaded()) {
540       OverloadedVTs.push_back(VT);
541       isOverloaded = true;
542     }
543 
544     // Reject invalid types.
545     if (VT == MVT::isVoid)
546       PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
547 
548     IS.RetVTs.push_back(VT);
549     IS.RetTypeDefs.push_back(TyEl);
550   }
551 
552   // Parse the list of parameter types.
553   TypeList = R->getValueAsListInit("ParamTypes");
554   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
555     Record *TyEl = TypeList->getElementAsRecord(i);
556     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
557     MVT::SimpleValueType VT;
558     if (TyEl->isSubClassOf("LLVMMatchType")) {
559       unsigned MatchTy = TyEl->getValueAsInt("Number");
560       assert(MatchTy < OverloadedVTs.size() &&
561              "Invalid matching number!");
562       VT = OverloadedVTs[MatchTy];
563       // It only makes sense to use the extended and truncated vector element
564       // variants with iAny types; otherwise, if the intrinsic is not
565       // overloaded, all the types can be specified directly.
566       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
567                !TyEl->isSubClassOf("LLVMTruncatedType") &&
568                !TyEl->isSubClassOf("LLVMVectorSameWidth")) ||
569               VT == MVT::iAny || VT == MVT::vAny) &&
570              "Expected iAny or vAny type");
571     } else
572       VT = getValueType(TyEl->getValueAsDef("VT"));
573 
574     if (MVT(VT).isOverloaded()) {
575       OverloadedVTs.push_back(VT);
576       isOverloaded = true;
577     }
578 
579     // Reject invalid types.
580     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
581       PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
582 
583     IS.ParamVTs.push_back(VT);
584     IS.ParamTypeDefs.push_back(TyEl);
585   }
586 
587   // Parse the intrinsic properties.
588   ListInit *PropList = R->getValueAsListInit("IntrProperties");
589   for (unsigned i = 0, e = PropList->size(); i != e; ++i) {
590     Record *Property = PropList->getElementAsRecord(i);
591     assert(Property->isSubClassOf("IntrinsicProperty") &&
592            "Expected a property!");
593 
594     if (Property->getName() == "IntrNoMem")
595       ModRef = NoMem;
596     else if (Property->getName() == "IntrReadMem")
597       ModRef = ModRefBehavior(ModRef & ~MR_Mod);
598     else if (Property->getName() == "IntrWriteMem")
599       ModRef = ModRefBehavior(ModRef & ~MR_Ref);
600     else if (Property->getName() == "IntrArgMemOnly")
601       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem);
602     else if (Property->getName() == "IntrInaccessibleMemOnly")
603       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_InaccessibleMem);
604     else if (Property->getName() == "IntrInaccessibleMemOrArgMemOnly")
605       ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem |
606                               MR_InaccessibleMem);
607     else if (Property->getName() == "Commutative")
608       isCommutative = true;
609     else if (Property->getName() == "Throws")
610       canThrow = true;
611     else if (Property->getName() == "IntrNoDuplicate")
612       isNoDuplicate = true;
613     else if (Property->getName() == "IntrConvergent")
614       isConvergent = true;
615     else if (Property->getName() == "IntrNoReturn")
616       isNoReturn = true;
617     else if (Property->isSubClassOf("NoCapture")) {
618       unsigned ArgNo = Property->getValueAsInt("ArgNo");
619       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
620     } else if (Property->isSubClassOf("Returned")) {
621       unsigned ArgNo = Property->getValueAsInt("ArgNo");
622       ArgumentAttributes.push_back(std::make_pair(ArgNo, Returned));
623     } else if (Property->isSubClassOf("ReadOnly")) {
624       unsigned ArgNo = Property->getValueAsInt("ArgNo");
625       ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadOnly));
626     } else if (Property->isSubClassOf("WriteOnly")) {
627       unsigned ArgNo = Property->getValueAsInt("ArgNo");
628       ArgumentAttributes.push_back(std::make_pair(ArgNo, WriteOnly));
629     } else if (Property->isSubClassOf("ReadNone")) {
630       unsigned ArgNo = Property->getValueAsInt("ArgNo");
631       ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadNone));
632     } else
633       llvm_unreachable("Unknown property!");
634   }
635 
636   // Sort the argument attributes for later benefit.
637   std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
638 }
639