Home | History | Annotate | Download | only in TableGen
      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 throw exceptions on error conditions.
     14 //
     15 //===----------------------------------------------------------------------===//
     16 
     17 #include "CodeGenTarget.h"
     18 #include "CodeGenIntrinsics.h"
     19 #include "llvm/TableGen/Record.h"
     20 #include "llvm/ADT/StringExtras.h"
     21 #include "llvm/ADT/STLExtras.h"
     22 #include "llvm/Support/CommandLine.h"
     23 #include <algorithm>
     24 using namespace llvm;
     25 
     26 static cl::opt<unsigned>
     27 AsmParserNum("asmparsernum", cl::init(0),
     28              cl::desc("Make -gen-asm-parser emit assembly parser #N"));
     29 
     30 static cl::opt<unsigned>
     31 AsmWriterNum("asmwriternum", cl::init(0),
     32              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
     33 
     34 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
     35 /// record corresponds to.
     36 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
     37   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
     38 }
     39 
     40 std::string llvm::getName(MVT::SimpleValueType T) {
     41   switch (T) {
     42   case MVT::Other:   return "UNKNOWN";
     43   case MVT::iPTR:    return "TLI.getPointerTy()";
     44   case MVT::iPTRAny: return "TLI.getPointerTy()";
     45   default: return getEnumName(T);
     46   }
     47 }
     48 
     49 std::string llvm::getEnumName(MVT::SimpleValueType T) {
     50   switch (T) {
     51   case MVT::Other:    return "MVT::Other";
     52   case MVT::i1:       return "MVT::i1";
     53   case MVT::i8:       return "MVT::i8";
     54   case MVT::i16:      return "MVT::i16";
     55   case MVT::i32:      return "MVT::i32";
     56   case MVT::i64:      return "MVT::i64";
     57   case MVT::i128:     return "MVT::i128";
     58   case MVT::iAny:     return "MVT::iAny";
     59   case MVT::fAny:     return "MVT::fAny";
     60   case MVT::vAny:     return "MVT::vAny";
     61   case MVT::f16:      return "MVT::f16";
     62   case MVT::f32:      return "MVT::f32";
     63   case MVT::f64:      return "MVT::f64";
     64   case MVT::f80:      return "MVT::f80";
     65   case MVT::f128:     return "MVT::f128";
     66   case MVT::ppcf128:  return "MVT::ppcf128";
     67   case MVT::x86mmx:   return "MVT::x86mmx";
     68   case MVT::Glue:     return "MVT::Glue";
     69   case MVT::isVoid:   return "MVT::isVoid";
     70   case MVT::v2i8:     return "MVT::v2i8";
     71   case MVT::v4i8:     return "MVT::v4i8";
     72   case MVT::v8i8:     return "MVT::v8i8";
     73   case MVT::v16i8:    return "MVT::v16i8";
     74   case MVT::v32i8:    return "MVT::v32i8";
     75   case MVT::v2i16:    return "MVT::v2i16";
     76   case MVT::v4i16:    return "MVT::v4i16";
     77   case MVT::v8i16:    return "MVT::v8i16";
     78   case MVT::v16i16:   return "MVT::v16i16";
     79   case MVT::v2i32:    return "MVT::v2i32";
     80   case MVT::v4i32:    return "MVT::v4i32";
     81   case MVT::v8i32:    return "MVT::v8i32";
     82   case MVT::v1i64:    return "MVT::v1i64";
     83   case MVT::v2i64:    return "MVT::v2i64";
     84   case MVT::v4i64:    return "MVT::v4i64";
     85   case MVT::v8i64:    return "MVT::v8i64";
     86   case MVT::v2f16:    return "MVT::v2f16";
     87   case MVT::v2f32:    return "MVT::v2f32";
     88   case MVT::v4f32:    return "MVT::v4f32";
     89   case MVT::v8f32:    return "MVT::v8f32";
     90   case MVT::v2f64:    return "MVT::v2f64";
     91   case MVT::v4f64:    return "MVT::v4f64";
     92   case MVT::Metadata: return "MVT::Metadata";
     93   case MVT::iPTR:     return "MVT::iPTR";
     94   case MVT::iPTRAny:  return "MVT::iPTRAny";
     95   case MVT::Untyped:  return "MVT::Untyped";
     96   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
     97   }
     98 }
     99 
    100 /// getQualifiedName - Return the name of the specified record, with a
    101 /// namespace qualifier if the record contains one.
    102 ///
    103 std::string llvm::getQualifiedName(const Record *R) {
    104   std::string Namespace;
    105   if (R->getValue("Namespace"))
    106      Namespace = R->getValueAsString("Namespace");
    107   if (Namespace.empty()) return R->getName();
    108   return Namespace + "::" + R->getName();
    109 }
    110 
    111 
    112 /// getTarget - Return the current instance of the Target class.
    113 ///
    114 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
    115   : Records(records), RegBank(0) {
    116   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
    117   if (Targets.size() == 0)
    118     throw std::string("ERROR: No 'Target' subclasses defined!");
    119   if (Targets.size() != 1)
    120     throw std::string("ERROR: Multiple subclasses of Target defined!");
    121   TargetRec = Targets[0];
    122 }
    123 
    124 
    125 const std::string &CodeGenTarget::getName() const {
    126   return TargetRec->getName();
    127 }
    128 
    129 std::string CodeGenTarget::getInstNamespace() const {
    130   for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
    131     // Make sure not to pick up "TargetOpcode" by accidentally getting
    132     // the namespace off the PHI instruction or something.
    133     if ((*i)->Namespace != "TargetOpcode")
    134       return (*i)->Namespace;
    135   }
    136 
    137   return "";
    138 }
    139 
    140 Record *CodeGenTarget::getInstructionSet() const {
    141   return TargetRec->getValueAsDef("InstructionSet");
    142 }
    143 
    144 
    145 /// getAsmParser - Return the AssemblyParser definition for this target.
    146 ///
    147 Record *CodeGenTarget::getAsmParser() const {
    148   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
    149   if (AsmParserNum >= LI.size())
    150     throw "Target does not have an AsmParser #" + utostr(AsmParserNum) + "!";
    151   return LI[AsmParserNum];
    152 }
    153 
    154 /// getAsmParserVariant - Return the AssmblyParserVariant definition for
    155 /// this target.
    156 ///
    157 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
    158   std::vector<Record*> LI =
    159     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
    160   if (i >= LI.size())
    161     throw "Target does not have an AsmParserVariant #" + utostr(i) + "!";
    162   return LI[i];
    163 }
    164 
    165 /// getAsmParserVariantCount - Return the AssmblyParserVariant definition
    166 /// available for this target.
    167 ///
    168 unsigned CodeGenTarget::getAsmParserVariantCount() const {
    169   std::vector<Record*> LI =
    170     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
    171   return LI.size();
    172 }
    173 
    174 /// getAsmWriter - Return the AssemblyWriter definition for this target.
    175 ///
    176 Record *CodeGenTarget::getAsmWriter() const {
    177   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
    178   if (AsmWriterNum >= LI.size())
    179     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
    180   return LI[AsmWriterNum];
    181 }
    182 
    183 CodeGenRegBank &CodeGenTarget::getRegBank() const {
    184   if (!RegBank)
    185     RegBank = new CodeGenRegBank(Records);
    186   return *RegBank;
    187 }
    188 
    189 void CodeGenTarget::ReadRegAltNameIndices() const {
    190   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
    191   std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
    192 }
    193 
    194 /// getRegisterByName - If there is a register with the specific AsmName,
    195 /// return it.
    196 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
    197   const std::vector<CodeGenRegister*> &Regs = getRegBank().getRegisters();
    198   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
    199     if (Regs[i]->TheDef->getValueAsString("AsmName") == Name)
    200       return Regs[i];
    201 
    202   return 0;
    203 }
    204 
    205 std::vector<MVT::SimpleValueType> CodeGenTarget::
    206 getRegisterVTs(Record *R) const {
    207   const CodeGenRegister *Reg = getRegBank().getReg(R);
    208   std::vector<MVT::SimpleValueType> Result;
    209   ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
    210   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
    211     const CodeGenRegisterClass &RC = *RCs[i];
    212     if (RC.contains(Reg)) {
    213       const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
    214       Result.insert(Result.end(), InVTs.begin(), InVTs.end());
    215     }
    216   }
    217 
    218   // Remove duplicates.
    219   array_pod_sort(Result.begin(), Result.end());
    220   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
    221   return Result;
    222 }
    223 
    224 
    225 void CodeGenTarget::ReadLegalValueTypes() const {
    226   ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
    227   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
    228     for (unsigned ri = 0, re = RCs[i]->VTs.size(); ri != re; ++ri)
    229       LegalValueTypes.push_back(RCs[i]->VTs[ri]);
    230 
    231   // Remove duplicates.
    232   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
    233   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
    234                                     LegalValueTypes.end()),
    235                         LegalValueTypes.end());
    236 }
    237 
    238 
    239 void CodeGenTarget::ReadInstructions() const {
    240   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
    241   if (Insts.size() <= 2)
    242     throw std::string("No 'Instruction' subclasses defined!");
    243 
    244   // Parse the instructions defined in the .td file.
    245   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
    246     Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
    247 }
    248 
    249 static const CodeGenInstruction *
    250 GetInstByName(const char *Name,
    251               const DenseMap<const Record*, CodeGenInstruction*> &Insts,
    252               RecordKeeper &Records) {
    253   const Record *Rec = Records.getDef(Name);
    254 
    255   DenseMap<const Record*, CodeGenInstruction*>::const_iterator
    256     I = Insts.find(Rec);
    257   if (Rec == 0 || I == Insts.end())
    258     throw std::string("Could not find '") + Name + "' instruction!";
    259   return I->second;
    260 }
    261 
    262 namespace {
    263 /// SortInstByName - Sorting predicate to sort instructions by name.
    264 ///
    265 struct SortInstByName {
    266   bool operator()(const CodeGenInstruction *Rec1,
    267                   const CodeGenInstruction *Rec2) const {
    268     return Rec1->TheDef->getName() < Rec2->TheDef->getName();
    269   }
    270 };
    271 }
    272 
    273 /// getInstructionsByEnumValue - Return all of the instructions defined by the
    274 /// target, ordered by their enum value.
    275 void CodeGenTarget::ComputeInstrsByEnum() const {
    276   // The ordering here must match the ordering in TargetOpcodes.h.
    277   const char *const FixedInstrs[] = {
    278     "PHI",
    279     "INLINEASM",
    280     "PROLOG_LABEL",
    281     "EH_LABEL",
    282     "GC_LABEL",
    283     "KILL",
    284     "EXTRACT_SUBREG",
    285     "INSERT_SUBREG",
    286     "IMPLICIT_DEF",
    287     "SUBREG_TO_REG",
    288     "COPY_TO_REGCLASS",
    289     "DBG_VALUE",
    290     "REG_SEQUENCE",
    291     "COPY",
    292     "BUNDLE",
    293     0
    294   };
    295   const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
    296   for (const char *const *p = FixedInstrs; *p; ++p) {
    297     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
    298     assert(Instr && "Missing target independent instruction");
    299     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
    300     InstrsByEnum.push_back(Instr);
    301   }
    302   unsigned EndOfPredefines = InstrsByEnum.size();
    303 
    304   for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
    305        I = Insts.begin(), E = Insts.end(); I != E; ++I) {
    306     const CodeGenInstruction *CGI = I->second;
    307     if (CGI->Namespace != "TargetOpcode")
    308       InstrsByEnum.push_back(CGI);
    309   }
    310 
    311   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
    312 
    313   // All of the instructions are now in random order based on the map iteration.
    314   // Sort them by name.
    315   std::sort(InstrsByEnum.begin()+EndOfPredefines, InstrsByEnum.end(),
    316             SortInstByName());
    317 }
    318 
    319 
    320 /// isLittleEndianEncoding - Return whether this target encodes its instruction
    321 /// in little-endian format, i.e. bits laid out in the order [0..n]
    322 ///
    323 bool CodeGenTarget::isLittleEndianEncoding() const {
    324   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
    325 }
    326 
    327 //===----------------------------------------------------------------------===//
    328 // ComplexPattern implementation
    329 //
    330 ComplexPattern::ComplexPattern(Record *R) {
    331   Ty          = ::getValueType(R->getValueAsDef("Ty"));
    332   NumOperands = R->getValueAsInt("NumOperands");
    333   SelectFunc  = R->getValueAsString("SelectFunc");
    334   RootNodes   = R->getValueAsListOfDefs("RootNodes");
    335 
    336   // Parse the properties.
    337   Properties = 0;
    338   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
    339   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
    340     if (PropList[i]->getName() == "SDNPHasChain") {
    341       Properties |= 1 << SDNPHasChain;
    342     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
    343       Properties |= 1 << SDNPOptInGlue;
    344     } else if (PropList[i]->getName() == "SDNPMayStore") {
    345       Properties |= 1 << SDNPMayStore;
    346     } else if (PropList[i]->getName() == "SDNPMayLoad") {
    347       Properties |= 1 << SDNPMayLoad;
    348     } else if (PropList[i]->getName() == "SDNPSideEffect") {
    349       Properties |= 1 << SDNPSideEffect;
    350     } else if (PropList[i]->getName() == "SDNPMemOperand") {
    351       Properties |= 1 << SDNPMemOperand;
    352     } else if (PropList[i]->getName() == "SDNPVariadic") {
    353       Properties |= 1 << SDNPVariadic;
    354     } else if (PropList[i]->getName() == "SDNPWantRoot") {
    355       Properties |= 1 << SDNPWantRoot;
    356     } else if (PropList[i]->getName() == "SDNPWantParent") {
    357       Properties |= 1 << SDNPWantParent;
    358     } else {
    359       errs() << "Unsupported SD Node property '" << PropList[i]->getName()
    360              << "' on ComplexPattern '" << R->getName() << "'!\n";
    361       exit(1);
    362     }
    363 }
    364 
    365 //===----------------------------------------------------------------------===//
    366 // CodeGenIntrinsic Implementation
    367 //===----------------------------------------------------------------------===//
    368 
    369 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
    370                                                    bool TargetOnly) {
    371   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
    372 
    373   std::vector<CodeGenIntrinsic> Result;
    374 
    375   for (unsigned i = 0, e = I.size(); i != e; ++i) {
    376     bool isTarget = I[i]->getValueAsBit("isTarget");
    377     if (isTarget == TargetOnly)
    378       Result.push_back(CodeGenIntrinsic(I[i]));
    379   }
    380   return Result;
    381 }
    382 
    383 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
    384   TheDef = R;
    385   std::string DefName = R->getName();
    386   ModRef = ReadWriteMem;
    387   isOverloaded = false;
    388   isCommutative = false;
    389   canThrow = false;
    390 
    391   if (DefName.size() <= 4 ||
    392       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
    393     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
    394 
    395   EnumName = std::string(DefName.begin()+4, DefName.end());
    396 
    397   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
    398     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
    399 
    400   TargetPrefix = R->getValueAsString("TargetPrefix");
    401   Name = R->getValueAsString("LLVMName");
    402 
    403   if (Name == "") {
    404     // If an explicit name isn't specified, derive one from the DefName.
    405     Name = "llvm.";
    406 
    407     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
    408       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
    409   } else {
    410     // Verify it starts with "llvm.".
    411     if (Name.size() <= 5 ||
    412         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
    413       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
    414   }
    415 
    416   // If TargetPrefix is specified, make sure that Name starts with
    417   // "llvm.<targetprefix>.".
    418   if (!TargetPrefix.empty()) {
    419     if (Name.size() < 6+TargetPrefix.size() ||
    420         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
    421         != (TargetPrefix + "."))
    422       throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
    423         TargetPrefix + ".'!";
    424   }
    425 
    426   // Parse the list of return types.
    427   std::vector<MVT::SimpleValueType> OverloadedVTs;
    428   ListInit *TypeList = R->getValueAsListInit("RetTypes");
    429   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
    430     Record *TyEl = TypeList->getElementAsRecord(i);
    431     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
    432     MVT::SimpleValueType VT;
    433     if (TyEl->isSubClassOf("LLVMMatchType")) {
    434       unsigned MatchTy = TyEl->getValueAsInt("Number");
    435       assert(MatchTy < OverloadedVTs.size() &&
    436              "Invalid matching number!");
    437       VT = OverloadedVTs[MatchTy];
    438       // It only makes sense to use the extended and truncated vector element
    439       // variants with iAny types; otherwise, if the intrinsic is not
    440       // overloaded, all the types can be specified directly.
    441       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
    442                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
    443               VT == MVT::iAny || VT == MVT::vAny) &&
    444              "Expected iAny or vAny type");
    445     } else {
    446       VT = getValueType(TyEl->getValueAsDef("VT"));
    447     }
    448     if (EVT(VT).isOverloaded()) {
    449       OverloadedVTs.push_back(VT);
    450       isOverloaded = true;
    451     }
    452 
    453     // Reject invalid types.
    454     if (VT == MVT::isVoid)
    455       throw "Intrinsic '" + DefName + " has void in result type list!";
    456 
    457     IS.RetVTs.push_back(VT);
    458     IS.RetTypeDefs.push_back(TyEl);
    459   }
    460 
    461   // Parse the list of parameter types.
    462   TypeList = R->getValueAsListInit("ParamTypes");
    463   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
    464     Record *TyEl = TypeList->getElementAsRecord(i);
    465     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
    466     MVT::SimpleValueType VT;
    467     if (TyEl->isSubClassOf("LLVMMatchType")) {
    468       unsigned MatchTy = TyEl->getValueAsInt("Number");
    469       assert(MatchTy < OverloadedVTs.size() &&
    470              "Invalid matching number!");
    471       VT = OverloadedVTs[MatchTy];
    472       // It only makes sense to use the extended and truncated vector element
    473       // variants with iAny types; otherwise, if the intrinsic is not
    474       // overloaded, all the types can be specified directly.
    475       assert(((!TyEl->isSubClassOf("LLVMExtendedElementVectorType") &&
    476                !TyEl->isSubClassOf("LLVMTruncatedElementVectorType")) ||
    477               VT == MVT::iAny || VT == MVT::vAny) &&
    478              "Expected iAny or vAny type");
    479     } else
    480       VT = getValueType(TyEl->getValueAsDef("VT"));
    481 
    482     if (EVT(VT).isOverloaded()) {
    483       OverloadedVTs.push_back(VT);
    484       isOverloaded = true;
    485     }
    486 
    487     // Reject invalid types.
    488     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
    489       throw "Intrinsic '" + DefName + " has void in result type list!";
    490 
    491     IS.ParamVTs.push_back(VT);
    492     IS.ParamTypeDefs.push_back(TyEl);
    493   }
    494 
    495   // Parse the intrinsic properties.
    496   ListInit *PropList = R->getValueAsListInit("Properties");
    497   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
    498     Record *Property = PropList->getElementAsRecord(i);
    499     assert(Property->isSubClassOf("IntrinsicProperty") &&
    500            "Expected a property!");
    501 
    502     if (Property->getName() == "IntrNoMem")
    503       ModRef = NoMem;
    504     else if (Property->getName() == "IntrReadArgMem")
    505       ModRef = ReadArgMem;
    506     else if (Property->getName() == "IntrReadMem")
    507       ModRef = ReadMem;
    508     else if (Property->getName() == "IntrReadWriteArgMem")
    509       ModRef = ReadWriteArgMem;
    510     else if (Property->getName() == "Commutative")
    511       isCommutative = true;
    512     else if (Property->getName() == "Throws")
    513       canThrow = true;
    514     else if (Property->isSubClassOf("NoCapture")) {
    515       unsigned ArgNo = Property->getValueAsInt("ArgNo");
    516       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
    517     } else
    518       llvm_unreachable("Unknown property!");
    519   }
    520 
    521   // Sort the argument attributes for later benefit.
    522   std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
    523 }
    524