Beispiel #1
0
void EDEmitter::run(raw_ostream &o) {
  unsigned int i = 0;
  
  CompoundConstantEmitter infoArray;
  CodeGenTarget target;
  
  populateInstInfo(infoArray, target);
  
  emitCommonEnums(o, i);
  
  o << "namespace {\n";
  
  o << "llvm::EDInstInfo instInfo" << target.getName().c_str() << "[] = ";
  infoArray.emit(o, i);
  o << ";" << "\n";
  
  o << "}\n";
}
void
RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
                                     CodeGenRegBank &RegBank) {
  emitSourceFileHeader("Register Information Header Fragment", OS);

  OS << "\n#ifdef GET_REGINFO_HEADER\n";
  OS << "#undef GET_REGINFO_HEADER\n";

  const std::string &TargetName = Target.getName();
  std::string ClassName = TargetName + "GenRegisterInfo";

  OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n\n";

  OS << "namespace llvm {\n\n";

  OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
     << "  explicit " << ClassName
     << "(unsigned RA, unsigned D = 0, unsigned E = 0, unsigned PC = 0);\n"
     << "  bool needsStackRealignment(const MachineFunction &) const override\n"
     << "     { return false; }\n";
  if (!RegBank.getSubRegIndices().empty()) {
    OS << "  unsigned composeSubRegIndicesImpl"
       << "(unsigned, unsigned) const override;\n"
       << "  const TargetRegisterClass *getSubClassWithSubReg"
       << "(const TargetRegisterClass*, unsigned) const override;\n";
  }
  OS << "  const RegClassWeight &getRegClassWeight("
     << "const TargetRegisterClass *RC) const override;\n"
     << "  unsigned getRegUnitWeight(unsigned RegUnit) const override;\n"
     << "  unsigned getNumRegPressureSets() const override;\n"
     << "  const char *getRegPressureSetName(unsigned Idx) const override;\n"
     << "  unsigned getRegPressureSetLimit(unsigned Idx) const override;\n"
     << "  const int *getRegClassPressureSets("
     << "const TargetRegisterClass *RC) const override;\n"
     << "  const int *getRegUnitPressureSets("
     << "unsigned RegUnit) const override;\n"
     << "};\n\n";

  ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

  if (!RegisterClasses.empty()) {
    OS << "namespace " << RegisterClasses[0]->Namespace
       << " { // Register classes\n";

    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
      const CodeGenRegisterClass &RC = *RegisterClasses[i];
      const std::string &Name = RC.getName();

      // Output the extern for the instance.
      OS << "  extern const TargetRegisterClass " << Name << "RegClass;\n";
    }
    OS << "} // end of namespace " << TargetName << "\n\n";
  }
  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_HEADER\n\n";
}
Beispiel #3
0
/// getRegisterValueType - Look up and return the ValueType of the specified
/// register. If the register is a member of multiple register classes which
/// have different associated types, return MVT::Other.
static MVT::SimpleValueType getRegisterValueType(Record *R,
                                                 const CodeGenTarget &T) {
  bool FoundRC = false;
  MVT::SimpleValueType VT = MVT::Other;
  const CodeGenRegister *Reg = T.getRegBank().getReg(R);

  for (const auto &RC : T.getRegBank().getRegClasses()) {
    if (!RC.contains(Reg))
      continue;

    if (!FoundRC) {
      FoundRC = true;
      VT = RC.getValueTypeNum(0);
      continue;
    }

    // If this occurs in multiple register classes, they all have to agree.
    assert(VT == RC.getValueTypeNum(0));
  }
  return VT;
}
Beispiel #4
0
/// HasOneImplicitDefWithKnownVT - If the instruction has at least one
/// implicit def and it has a known VT, return the VT, otherwise return
/// MVT::Other.
MVT::SimpleValueType CodeGenInstruction::
HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
    if (ImplicitDefs.empty()) return MVT::Other;

    // Check to see if the first implicit def has a resolvable type.
    Record *FirstImplicitDef = ImplicitDefs[0];
    assert(FirstImplicitDef->isSubClassOf("Register"));
    const std::vector<MVT::SimpleValueType> &RegVTs =
        TargetInfo.getRegisterVTs(FirstImplicitDef);
    if (RegVTs.size() == 1)
        return RegVTs[0];
    return MVT::Other;
}
/// getRegisterValueType - Look up and return the ValueType of the specified
/// register. If the register is a member of multiple register classes which
/// have different associated types, return MVT::Other.
static MVT::SimpleValueType getRegisterValueType(Record *R,
                                                 const CodeGenTarget &T) {
  bool FoundRC = false;
  MVT::SimpleValueType VT = MVT::Other;
  const CodeGenRegister *Reg = T.getRegBank().getReg(R);
  ArrayRef<CodeGenRegisterClass*> RCs = T.getRegBank().getRegClasses();

  for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RCs[rc];
    if (!RC.contains(Reg))
      continue;

    if (!FoundRC) {
      FoundRC = true;
      VT = RC.getValueTypeNum(0);
      continue;
    }

    // If this occurs in multiple register classes, they all have to agree.
    assert(VT == RC.getValueTypeNum(0));
  }
  return VT;
}
Beispiel #6
0
/// EmitComputeAvailableFeatures - Emit the function to compute the list of
/// available features given a subtarget.
static void EmitComputeAvailableFeatures(AsmWriterInfo &Info,
                                         Record *AsmWriter,
                                         CodeGenTarget &Target,
                                         raw_ostream &O) {
  std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");

  O << "unsigned " << Target.getName() << ClassName << "::\n"
    << "ComputeAvailableFeatures(const " << Target.getName()
    << "Subtarget *Subtarget) const {\n";
  O << "  unsigned Features = 0;\n";

  for (std::map<const Record*, SubtargetFeatureInfo*>::const_iterator
         I = Info.SubtargetFeatures.begin(),
         E = Info.SubtargetFeatures.end(); I != E; ++I) {
    SubtargetFeatureInfo &SFI = *I->second;
    O << "  if (" << SFI.TheDef->getValueAsString("CondString")
      << ")\n";
    O << "    Features |= " << SFI.getEnumName() << ";\n";
  }

  O << "  return Features;\n";
  O << "}\n\n";
}
Beispiel #7
0
void
RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
                                     CodeGenRegBank &RegBank) {
    EmitSourceFileHeader("Register Information Header Fragment", OS);

    OS << "\n#ifdef GET_REGINFO_HEADER\n";
    OS << "#undef GET_REGINFO_HEADER\n";

    const std::string &TargetName = Target.getName();
    std::string ClassName = TargetName + "GenRegisterInfo";

    OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n";
    OS << "#include <string>\n\n";

    OS << "namespace llvm {\n\n";

    OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
       << "  explicit " << ClassName
       << "(unsigned RA, unsigned D = 0, unsigned E = 0);\n"
       << "  virtual bool needsStackRealignment(const MachineFunction &) const\n"
       << "     { return false; }\n"
       << "  unsigned composeSubRegIndices(unsigned, unsigned) const;\n"
       << "  const TargetRegisterClass *"
       "getSubClassWithSubReg(const TargetRegisterClass*, unsigned) const;\n"
       << "  const TargetRegisterClass *getMatchingSuperRegClass("
       "const TargetRegisterClass*, const TargetRegisterClass*, "
       "unsigned) const;\n"
       << "};\n\n";

    ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

    if (!RegisterClasses.empty()) {
        OS << "namespace " << RegisterClasses[0]->Namespace
           << " { // Register classes\n";

        for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
            const CodeGenRegisterClass &RC = *RegisterClasses[i];
            const std::string &Name = RC.getName();

            // Output the extern for the instance.
            OS << "  extern const TargetRegisterClass " << Name << "RegClass;\n";
            // Output the extern for the pointer to the instance (should remove).
            OS << "  static const TargetRegisterClass * const " << Name
               << "RegisterClass = &" << Name << "RegClass;\n";
        }
        OS << "} // end of namespace " << TargetName << "\n\n";
    }
    OS << "} // End llvm namespace \n";
    OS << "#endif // GET_REGINFO_HEADER\n\n";
}
// runEnums - Print out enum values for all of the registers.
void RegisterInfoEmitter::runEnums(raw_ostream &OS) {
  CodeGenTarget Target;
  const std::vector<CodeGenRegister> &Registers = Target.getRegisters();

  std::string Namespace = Registers[0].TheDef->getValueAsString("Namespace");

  EmitSourceFileHeader("Target Register Enum Values", OS);
  OS << "namespace llvm {\n\n";

  if (!Namespace.empty())
    OS << "namespace " << Namespace << " {\n";
  OS << "enum {\n  NoRegister,\n";

  for (unsigned i = 0, e = Registers.size(); i != e; ++i)
    OS << "  " << Registers[i].getName() << ", \t// " << i+1 << "\n";
  OS << "  NUM_TARGET_REGS \t// " << Registers.size()+1 << "\n";
  OS << "};\n";
  if (!Namespace.empty())
    OS << "}\n";

  const std::vector<Record*> SubRegIndices = Target.getSubRegIndices();
  if (!SubRegIndices.empty()) {
    OS << "\n// Subregister indices\n";
    Namespace = SubRegIndices[0]->getValueAsString("Namespace");
    if (!Namespace.empty())
      OS << "namespace " << Namespace << " {\n";
    OS << "enum {\n  NoSubRegister,\n";
    for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
      OS << "  " << SubRegIndices[i]->getName() << ",\t// " << i+1 << "\n";
    OS << "  NUM_TARGET_SUBREGS = " << SubRegIndices.size()+1 << "\n";
    OS << "};\n";
    if (!Namespace.empty())
      OS << "}\n";
  }
  OS << "} // End llvm namespace \n";
}
Beispiel #9
0
static std::string PhyRegForNode(TreePatternNode *Op,
                                 const CodeGenTarget &Target) {
  std::string PhysReg;

  if (!Op->isLeaf())
    return PhysReg;

  Record *OpLeafRec = cast<DefInit>(Op->getLeafValue())->getDef();
  if (!OpLeafRec->isSubClassOf("Register"))
    return PhysReg;

  PhysReg += cast<StringInit>(OpLeafRec->getValue("Namespace")->getValue())
               ->getValue();
  PhysReg += "::";
  PhysReg += Target.getRegBank().getReg(OpLeafRec)->getName();
  return PhysReg;
}
/// getRegisterValueType - Look up and return the ValueType of the specified
/// register. If the register is a member of multiple register classes which
/// have different associated types, return MVT::Other.
static MVT::SimpleValueType getRegisterValueType(Record *R,
                                                 const CodeGenTarget &T) {
  bool FoundRC = false;
  MVT::SimpleValueType VT = MVT::Other;
  const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
  std::vector<Record*>::const_iterator Element;

  for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = RCs[rc];
    if (!std::count(RC.Elements.begin(), RC.Elements.end(), R))
      continue;

    if (!FoundRC) {
      FoundRC = true;
      VT = RC.getValueTypeNum(0);
      continue;
    }

    // If this occurs in multiple register classes, they all have to agree.
    assert(VT == RC.getValueTypeNum(0));
  }
  return VT;
}
Beispiel #11
0
/// Generate an enum for all the operand types for this target, under the
/// llvm::TargetNamespace::OpTypes namespace.
/// Operand types are all definitions derived of the Operand Target.td class.
void InstrInfoEmitter::emitOperandTypesEnum(raw_ostream &OS,
                                            const CodeGenTarget &Target) {

  const std::string &Namespace = Target.getInstNamespace();
  std::vector<Record *> Operands = Records.getAllDerivedDefinitions("Operand");

  OS << "\n#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
  OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
  OS << "namespace llvm {";
  OS << "namespace " << Namespace << " {\n";
  OS << "namespace OpTypes { \n";
  OS << "enum OperandType {\n";

  for (unsigned oi = 0, oe = Operands.size(); oi != oe; ++oi) {
    if (!Operands[oi]->isAnonymous())
      OS << "  " << Operands[oi]->getName() << " = " << oi << ",\n";
  }

  OS << "  OPERAND_TYPE_LIST_END" << "\n};\n";
  OS << "} // End namespace OpTypes\n";
  OS << "} // End namespace " << Namespace << "\n";
  OS << "} // End namespace llvm\n";
  OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
}
Beispiel #12
0
/// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
/// constructor.  It checks if an argument in an InstAlias pattern matches
/// the corresponding operand of the instruction.  It returns true on a
/// successful match, with ResOp set to the result operand to be used.
bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
                                       Record *InstOpRec, bool hasSubOps,
                                       SMLoc Loc, CodeGenTarget &T,
                                       ResultOperand &ResOp) {
  Init *Arg = Result->getArg(AliasOpNo);
  DefInit *ADI = dynamic_cast<DefInit*>(Arg);

  if (ADI && ADI->getDef() == InstOpRec) {
    // If the operand is a record, it must have a name, and the record type
    // must match up with the instruction's argument type.
    if (Result->getArgName(AliasOpNo).empty())
      throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
                    " must have a name!");
    ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
    return true;
  }

  // Handle explicit registers.
  if (ADI && ADI->getDef()->isSubClassOf("Register")) {
    if (!InstOpRec->isSubClassOf("RegisterClass"))
      return false;

    if (!T.getRegisterClass(InstOpRec)
        .contains(T.getRegBank().getReg(ADI->getDef())))
      throw TGError(Loc, "fixed register " +ADI->getDef()->getName()
                    + " is not a member of the " + InstOpRec->getName() +
                    " register class!");

    if (!Result->getArgName(AliasOpNo).empty())
      throw TGError(Loc, "result fixed register argument must "
                    "not have a name!");

    ResOp = ResultOperand(ADI->getDef());
    return true;
  }

  // Handle "zero_reg" for optional def operands.
  if (ADI && ADI->getDef()->getName() == "zero_reg") {

    // Check if this is an optional def.
    if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
      throw TGError(Loc, "reg0 used for result that is not an "
                    "OptionalDefOperand!");

    ResOp = ResultOperand(static_cast<Record*>(0));
    return true;
  }

  if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
    if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
      return false;
    // Integer arguments can't have names.
    if (!Result->getArgName(AliasOpNo).empty())
      throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
                    " must not have a name!");
    ResOp = ResultOperand(II->getValue());
    return true;
  }

  return false;
}
Beispiel #13
0
/// populateInstInfo - Fills an array of InstInfos with information about each 
///   instruction in a target
///
/// @arg infoArray  - The array of InstInfo objects to populate
/// @arg target     - The CodeGenTarget to use as a source of instructions
static void populateInstInfo(CompoundConstantEmitter &infoArray,
                             CodeGenTarget &target) {
  const std::vector<const CodeGenInstruction*> &numberedInstructions =
    target.getInstructionsByEnumValue();
  
  unsigned int index;
  unsigned int numInstructions = numberedInstructions.size();
  
  for (index = 0; index < numInstructions; ++index) {
    const CodeGenInstruction& inst = *numberedInstructions[index];
    
    CompoundConstantEmitter *infoStruct = new CompoundConstantEmitter;
    infoArray.addEntry(infoStruct);
    
    LiteralConstantEmitter *instType = new LiteralConstantEmitter;
    infoStruct->addEntry(instType);
    
    LiteralConstantEmitter *numOperandsEmitter = 
      new LiteralConstantEmitter(inst.OperandList.size());
    infoStruct->addEntry(numOperandsEmitter);
    
    CompoundConstantEmitter *operandTypeArray = new CompoundConstantEmitter;
    infoStruct->addEntry(operandTypeArray);
    
    LiteralConstantEmitter *operandTypes[EDIS_MAX_OPERANDS];
                         
    CompoundConstantEmitter *operandFlagArray = new CompoundConstantEmitter;
    infoStruct->addEntry(operandFlagArray);
        
    FlagsConstantEmitter *operandFlags[EDIS_MAX_OPERANDS];
    
    for (unsigned operandIndex = 0; 
         operandIndex < EDIS_MAX_OPERANDS; 
         ++operandIndex) {
      operandTypes[operandIndex] = new LiteralConstantEmitter;
      operandTypeArray->addEntry(operandTypes[operandIndex]);
      
      operandFlags[operandIndex] = new FlagsConstantEmitter;
      operandFlagArray->addEntry(operandFlags[operandIndex]);
    }
 
    unsigned numSyntaxes = 0;
    
    if (target.getName() == "X86") {
      X86PopulateOperands(operandTypes, inst);
      X86ExtractSemantics(*instType, operandFlags, inst);
      numSyntaxes = 2;
    }
    else if (target.getName() == "ARM") {
      ARMPopulateOperands(operandTypes, inst);
      ARMExtractSemantics(*instType, operandTypes, operandFlags, inst);
      numSyntaxes = 1;
    }
    
    CompoundConstantEmitter *operandOrderArray = new CompoundConstantEmitter;    
    
    infoStruct->addEntry(operandOrderArray);
    
    for (unsigned syntaxIndex = 0; 
         syntaxIndex < EDIS_MAX_SYNTAXES; 
         ++syntaxIndex) {
      CompoundConstantEmitter *operandOrder = 
        new CompoundConstantEmitter(EDIS_MAX_OPERANDS);
      
      operandOrderArray->addEntry(operandOrder);
      
      if (syntaxIndex < numSyntaxes) {
        populateOperandOrder(operandOrder, inst, syntaxIndex);
      }
    }
    
    infoStruct = NULL;
  }
}
Beispiel #14
0
//
// runTargetDesc - Output the target register and register file descriptions.
//
void
RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target,
                                   CodeGenRegBank &RegBank){
  EmitSourceFileHeader("Target Register and Register Classes Information", OS);

  OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
  OS << "#undef GET_REGINFO_TARGET_DESC\n";

  OS << "namespace llvm {\n\n";

  // Get access to MCRegisterClass data.
  OS << "extern const MCRegisterClass " << Target.getName()
     << "MCRegisterClasses[];\n";

  // Start out by emitting each of the register classes.
  ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

  // Collect all registers belonging to any allocatable class.
  std::set<Record*> AllocatableRegs;

  // Collect allocatable registers.
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];
    ArrayRef<Record*> Order = RC.getOrder();

    if (RC.Allocatable)
      AllocatableRegs.insert(Order.begin(), Order.end());
  }

  OS << "namespace {     // Register classes...\n";

  // Emit the ValueType arrays for each RegisterClass
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];

    // Give the register class a legal C name if it's anonymous.
    std::string Name = RC.getName() + "VTs";

    // Emit the register list now.
    OS << "  // " << Name
       << " Register Class Value Types...\n"
       << "  static const EVT " << Name
       << "[] = {\n    ";
    for (unsigned i = 0, e = RC.VTs.size(); i != e; ++i)
      OS << getEnumName(RC.VTs[i]) << ", ";
    OS << "MVT::Other\n  };\n\n";
  }
  OS << "}  // end anonymous namespace\n\n";

  // Now that all of the structs have been emitted, emit the instances.
  if (!RegisterClasses.empty()) {
    OS << "namespace " << RegisterClasses[0]->Namespace
       << " {   // Register class instances\n";
    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i)
      OS << "  " << RegisterClasses[i]->getName()  << "Class\t"
         << RegisterClasses[i]->getName() << "RegClass;\n";

    std::map<unsigned, std::set<unsigned> > SuperRegClassMap;

    OS << "\n  static const TargetRegisterClass* const "
      << "NullRegClasses[] = { NULL };\n\n";

    unsigned NumSubRegIndices = RegBank.getSubRegIndices().size();

    if (NumSubRegIndices) {
      // Compute the super-register classes for each RegisterClass
      for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
        const CodeGenRegisterClass &RC = *RegisterClasses[rc];
        for (DenseMap<Record*,Record*>::const_iterator
             i = RC.SubRegClasses.begin(),
             e = RC.SubRegClasses.end(); i != e; ++i) {
          // Find the register class number of i->second for SuperRegClassMap.
          const CodeGenRegisterClass *RC2 = RegBank.getRegClass(i->second);
          assert(RC2 && "Invalid register class in SubRegClasses");
          SuperRegClassMap[RC2->EnumValue].insert(rc);
        }
      }

      // Emit the super-register classes for each RegisterClass
      for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
        const CodeGenRegisterClass &RC = *RegisterClasses[rc];

        // Give the register class a legal C name if it's anonymous.
        std::string Name = RC.getName();

        OS << "  // " << Name
           << " Super-register Classes...\n"
           << "  static const TargetRegisterClass* const "
           << Name << "SuperRegClasses[] = {\n    ";

        bool Empty = true;
        std::map<unsigned, std::set<unsigned> >::iterator I =
          SuperRegClassMap.find(rc);
        if (I != SuperRegClassMap.end()) {
          for (std::set<unsigned>::iterator II = I->second.begin(),
                 EE = I->second.end(); II != EE; ++II) {
            const CodeGenRegisterClass &RC2 = *RegisterClasses[*II];
            if (!Empty)
              OS << ", ";
            OS << "&" << RC2.getQualifiedName() << "RegClass";
            Empty = false;
          }
        }

        OS << (!Empty ? ", " : "") << "NULL";
        OS << "\n  };\n\n";
      }
    }

    // Emit the sub-classes array for each RegisterClass
    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
      const CodeGenRegisterClass &RC = *RegisterClasses[rc];

      // Give the register class a legal C name if it's anonymous.
      std::string Name = RC.getName();

      OS << "  static const unsigned " << Name << "SubclassMask[] = { ";
      printBitVectorAsHex(OS, RC.getSubClasses(), 32);
      OS << "};\n\n";
    }

    // Emit NULL terminated super-class lists.
    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
      const CodeGenRegisterClass &RC = *RegisterClasses[rc];
      ArrayRef<CodeGenRegisterClass*> Supers = RC.getSuperClasses();

      // Skip classes without supers.  We can reuse NullRegClasses.
      if (Supers.empty())
        continue;

      OS << "  static const TargetRegisterClass* const "
         << RC.getName() << "Superclasses[] = {\n";
      for (unsigned i = 0; i != Supers.size(); ++i)
        OS << "    &" << Supers[i]->getQualifiedName() << "RegClass,\n";
      OS << "    NULL\n  };\n\n";
    }

    // Emit methods.
    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
      const CodeGenRegisterClass &RC = *RegisterClasses[i];
      OS << RC.getName() << "Class::" << RC.getName()
         << "Class()  : TargetRegisterClass(&"
         << Target.getName() << "MCRegisterClasses["
         << RC.getName() + "RegClassID" << "], "
         << RC.getName() + "VTs" << ", "
         << RC.getName() + "SubclassMask" << ", ";
      if (RC.getSuperClasses().empty())
        OS << "NullRegClasses, ";
      else
        OS << RC.getName() + "Superclasses, ";
      OS << (NumSubRegIndices ? RC.getName() + "Super" : std::string("Null"))
         << "RegClasses"
         << ") {}\n";
      if (!RC.AltOrderSelect.empty()) {
        OS << "\nstatic inline unsigned " << RC.getName()
           << "AltOrderSelect(const MachineFunction &MF) {"
           << RC.AltOrderSelect << "}\n\nArrayRef<unsigned> "
           << RC.getName() << "Class::"
           << "getRawAllocationOrder(const MachineFunction &MF) const {\n";
        for (unsigned oi = 1 , oe = RC.getNumOrders(); oi != oe; ++oi) {
          ArrayRef<Record*> Elems = RC.getOrder(oi);
          OS << "  static const unsigned AltOrder" << oi << "[] = {";
          for (unsigned elem = 0; elem != Elems.size(); ++elem)
            OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
          OS << " };\n";
        }
        OS << "  const MCRegisterClass &MCR = " << Target.getName()
           << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];"
           << "  static const ArrayRef<unsigned> Order[] = {\n"
           << "    makeArrayRef(MCR.begin(), MCR.getNumRegs()";
        for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
          OS << "),\n    makeArrayRef(AltOrder" << oi;
        OS << ")\n  };\n  const unsigned Select = " << RC.getName()
           << "AltOrderSelect(MF);\n  assert(Select < " << RC.getNumOrders()
           << ");\n  return Order[Select];\n}\n";
        }
    }

    OS << "}\n";
  }

  OS << "\nnamespace {\n";
  OS << "  const TargetRegisterClass* const RegisterClasses[] = {\n";
  for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i)
    OS << "    &" << RegisterClasses[i]->getQualifiedName()
       << "RegClass,\n";
  OS << "  };\n";
  OS << "}\n";       // End of anonymous namespace...

  // Emit extra information about registers.
  const std::string &TargetName = Target.getName();
  OS << "\n  static const TargetRegisterInfoDesc "
     << TargetName << "RegInfoDesc[] = "
     << "{ // Extra Descriptors\n";
  OS << "    { 0, 0 },\n";

  const std::vector<CodeGenRegister*> &Regs = RegBank.getRegisters();
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister &Reg = *Regs[i];
    OS << "    { ";
    OS << Reg.CostPerUse << ", "
       << int(AllocatableRegs.count(Reg.TheDef)) << " },\n";
  }
  OS << "  };\n";      // End of register descriptors...


  // Calculate the mapping of subregister+index pairs to physical registers.
  // This will also create further anonymous indexes.
  unsigned NamedIndices = RegBank.getNumNamedIndices();

  // Emit SubRegIndex names, skipping 0
  const std::vector<Record*> &SubRegIndices = RegBank.getSubRegIndices();
  OS << "\n  static const char *const " << TargetName
     << "SubRegIndexTable[] = { \"";
  for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
    OS << SubRegIndices[i]->getName();
    if (i+1 != e)
      OS << "\", \"";
  }
  OS << "\" };\n\n";

  // Emit names of the anonymus subreg indexes.
  if (SubRegIndices.size() > NamedIndices) {
    OS << "  enum {";
    for (unsigned i = NamedIndices, e = SubRegIndices.size(); i != e; ++i) {
      OS << "\n    " << SubRegIndices[i]->getName() << " = " << i+1;
      if (i+1 != e)
        OS << ',';
    }
    OS << "\n  };\n\n";
  }
  OS << "\n";

  std::string ClassName = Target.getName() + "GenRegisterInfo";

  // Emit the subregister + index mapping function based on the information
  // calculated above.
  OS << "unsigned " << ClassName
     << "::getSubReg(unsigned RegNo, unsigned Index) const {\n"
     << "  switch (RegNo) {\n"
     << "  default:\n    return 0;\n";
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister::SubRegMap &SRM = Regs[i]->getSubRegs();
    if (SRM.empty())
      continue;
    OS << "  case " << getQualifiedName(Regs[i]->TheDef) << ":\n";
    OS << "    switch (Index) {\n";
    OS << "    default: return 0;\n";
    for (CodeGenRegister::SubRegMap::const_iterator ii = SRM.begin(),
         ie = SRM.end(); ii != ie; ++ii)
      OS << "    case " << getQualifiedName(ii->first)
         << ": return " << getQualifiedName(ii->second->TheDef) << ";\n";
    OS << "    };\n" << "    break;\n";
  }
  OS << "  };\n";
  OS << "  return 0;\n";
  OS << "}\n\n";

  OS << "unsigned " << ClassName
     << "::getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const {\n"
     << "  switch (RegNo) {\n"
     << "  default:\n    return 0;\n";
   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
     const CodeGenRegister::SubRegMap &SRM = Regs[i]->getSubRegs();
     if (SRM.empty())
       continue;
    OS << "  case " << getQualifiedName(Regs[i]->TheDef) << ":\n";
    for (CodeGenRegister::SubRegMap::const_iterator ii = SRM.begin(),
         ie = SRM.end(); ii != ie; ++ii)
      OS << "    if (SubRegNo == " << getQualifiedName(ii->second->TheDef)
         << ")  return " << getQualifiedName(ii->first) << ";\n";
    OS << "    return 0;\n";
  }
  OS << "  };\n";
  OS << "  return 0;\n";
  OS << "}\n\n";

  // Emit composeSubRegIndices
  OS << "unsigned " << ClassName
     << "::composeSubRegIndices(unsigned IdxA, unsigned IdxB) const {\n"
     << "  switch (IdxA) {\n"
     << "  default:\n    return IdxB;\n";
  for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
    bool Open = false;
    for (unsigned j = 0; j != e; ++j) {
      if (Record *Comp = RegBank.getCompositeSubRegIndex(SubRegIndices[i],
                                                         SubRegIndices[j])) {
        if (!Open) {
          OS << "  case " << getQualifiedName(SubRegIndices[i])
             << ": switch(IdxB) {\n    default: return IdxB;\n";
          Open = true;
        }
        OS << "    case " << getQualifiedName(SubRegIndices[j])
           << ": return " << getQualifiedName(Comp) << ";\n";
      }
    }
    if (Open)
      OS << "    }\n";
  }
  OS << "  }\n}\n\n";

  // Emit getSubClassWithSubReg.
  OS << "const TargetRegisterClass *" << ClassName
     << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
        " const {\n";
  if (SubRegIndices.empty()) {
    OS << "  assert(Idx == 0 && \"Target has no sub-registers\");\n"
       << "  return RC;\n";
  } else {
    // Use the smallest type that can hold a regclass ID with room for a
    // sentinel.
    if (RegisterClasses.size() < UINT8_MAX)
      OS << "  static const uint8_t Table[";
    else if (RegisterClasses.size() < UINT16_MAX)
      OS << "  static const uint16_t Table[";
    else
      throw "Too many register classes.";
    OS << RegisterClasses.size() << "][" << SubRegIndices.size() << "] = {\n";
    for (unsigned rci = 0, rce = RegisterClasses.size(); rci != rce; ++rci) {
      const CodeGenRegisterClass &RC = *RegisterClasses[rci];
      OS << "    {\t// " << RC.getName() << "\n";
      for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
        Record *Idx = SubRegIndices[sri];
        if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(Idx))
          OS << "      " << SRC->EnumValue + 1 << ",\t// " << Idx->getName()
             << " -> " << SRC->getName() << "\n";
        else
          OS << "      0,\t// " << Idx->getName() << "\n";
      }
      OS << "    },\n";
    }
    OS << "  };\n  assert(RC && \"Missing regclass\");\n"
       << "  if (!Idx) return RC;\n  --Idx;\n"
       << "  assert(Idx < " << SubRegIndices.size() << " && \"Bad subreg\");\n"
       << "  unsigned TV = Table[RC->getID()][Idx];\n"
       << "  return TV ? getRegClass(TV - 1) : 0;\n";
  }
  OS << "}\n\n";

  // Emit getMatchingSuperRegClass.
  OS << "const TargetRegisterClass *" << ClassName
     << "::getMatchingSuperRegClass(const TargetRegisterClass *A,"
        " const TargetRegisterClass *B, unsigned Idx) const {\n";
  if (SubRegIndices.empty()) {
    OS << "  llvm_unreachable(\"Target has no sub-registers\");\n";
  } else {
    // We need to find the largest sub-class of A such that every register has
    // an Idx sub-register in B.  Map (B, Idx) to a bit-vector of
    // super-register classes that map into B. Then compute the largest common
    // sub-class with A by taking advantage of the register class ordering,
    // like getCommonSubClass().

    // Bitvector table is NumRCs x NumSubIndexes x BVWords, where BVWords is
    // the number of 32-bit words required to represent all register classes.
    const unsigned BVWords = (RegisterClasses.size()+31)/32;
    BitVector BV(RegisterClasses.size());

    OS << "  static const unsigned Table[" << RegisterClasses.size()
       << "][" << SubRegIndices.size() << "][" << BVWords << "] = {\n";
    for (unsigned rci = 0, rce = RegisterClasses.size(); rci != rce; ++rci) {
      const CodeGenRegisterClass &RC = *RegisterClasses[rci];
      OS << "    {\t// " << RC.getName() << "\n";
      for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
        Record *Idx = SubRegIndices[sri];
        BV.reset();
        RC.getSuperRegClasses(Idx, BV);
        OS << "      { ";
        printBitVectorAsHex(OS, BV, 32);
        OS << "},\t// " << Idx->getName() << '\n';
      }
      OS << "    },\n";
    }
    OS << "  };\n  assert(A && B && \"Missing regclass\");\n"
       << "  --Idx;\n"
       << "  assert(Idx < " << SubRegIndices.size() << " && \"Bad subreg\");\n"
       << "  const unsigned *TV = Table[B->getID()][Idx];\n"
       << "  const unsigned *SC = A->getSubClassMask();\n"
       << "  for (unsigned i = 0; i != " << BVWords << "; ++i)\n"
       << "    if (unsigned Common = TV[i] & SC[i])\n"
       << "      return getRegClass(32*i + CountTrailingZeros_32(Common));\n"
       << "  return 0;\n";
  }
  OS << "}\n\n";

  // Emit the constructor of the class...
  OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";

  OS << ClassName << "::" << ClassName
     << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour)\n"
     << "  : TargetRegisterInfo(" << TargetName << "RegInfoDesc"
     << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n"
     << "                 " << TargetName << "SubRegIndexTable) {\n"
     << "  InitMCRegisterInfo(" << TargetName << "RegDesc, "
     << Regs.size()+1 << ", RA, " << TargetName << "MCRegisterClasses, "
     << RegisterClasses.size() << ");\n\n";

  EmitRegMapping(OS, Regs, true);

  OS << "}\n\n";


  // Emit CalleeSavedRegs information.
  std::vector<Record*> CSRSets =
    Records.getAllDerivedDefinitions("CalleeSavedRegs");
  for (unsigned i = 0, e = CSRSets.size(); i != e; ++i) {
    Record *CSRSet = CSRSets[i];
    const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
    assert(Regs && "Cannot expand CalleeSavedRegs instance");

    // Emit the *_SaveList list of callee-saved registers.
    OS << "static const unsigned " << CSRSet->getName()
       << "_SaveList[] = { ";
    for (unsigned r = 0, re = Regs->size(); r != re; ++r)
      OS << getQualifiedName((*Regs)[r]) << ", ";
    OS << "0 };\n";

    // Emit the *_RegMask bit mask of call-preserved registers.
    OS << "static const uint32_t " << CSRSet->getName()
       << "_RegMask[] = { ";
    printBitVectorAsHex(OS, RegBank.computeCoveredRegisters(*Regs), 32);
    OS << "};\n";
  }
  OS << "\n\n";

  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
}
Beispiel #15
0
void
RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
                                     CodeGenRegBank &RegBank) {
  EmitSourceFileHeader("Register Information Header Fragment", OS);

  OS << "\n#ifdef GET_REGINFO_HEADER\n";
  OS << "#undef GET_REGINFO_HEADER\n";

  const std::string &TargetName = Target.getName();
  std::string ClassName = TargetName + "GenRegisterInfo";

  OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n";
  OS << "#include <string>\n\n";

  OS << "namespace llvm {\n\n";

  OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
     << "  explicit " << ClassName
     << "(unsigned RA, unsigned D = 0, unsigned E = 0);\n"
     << "  virtual bool needsStackRealignment(const MachineFunction &) const\n"
     << "     { return false; }\n"
     << "  unsigned getSubReg(unsigned RegNo, unsigned Index) const;\n"
     << "  unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const;\n"
     << "  unsigned composeSubRegIndices(unsigned, unsigned) const;\n"
     << "  const TargetRegisterClass *"
        "getSubClassWithSubReg(const TargetRegisterClass*, unsigned) const;\n"
     << "  const TargetRegisterClass *getMatchingSuperRegClass("
        "const TargetRegisterClass*, const TargetRegisterClass*, "
        "unsigned) const;\n"
     << "};\n\n";

  const std::vector<Record*> &SubRegIndices = RegBank.getSubRegIndices();
  if (!SubRegIndices.empty()) {
    OS << "\n// Subregister indices\n";
    std::string Namespace = SubRegIndices[0]->getValueAsString("Namespace");
    if (!Namespace.empty())
      OS << "namespace " << Namespace << " {\n";
    OS << "enum {\n  NoSubRegister,\n";
    for (unsigned i = 0, e = RegBank.getNumNamedIndices(); i != e; ++i)
      OS << "  " << SubRegIndices[i]->getName() << ",\t// " << i+1 << "\n";
    OS << "  NUM_TARGET_NAMED_SUBREGS = " << SubRegIndices.size()+1 << "\n";
    OS << "};\n";
    if (!Namespace.empty())
      OS << "}\n";
  }

  ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

  if (!RegisterClasses.empty()) {
    OS << "namespace " << RegisterClasses[0]->Namespace
       << " { // Register classes\n";

    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
      const CodeGenRegisterClass &RC = *RegisterClasses[i];
      const std::string &Name = RC.getName();

      // Output the register class definition.
      OS << "  struct " << Name << "Class : public TargetRegisterClass {\n"
         << "    " << Name << "Class();\n";
      if (!RC.AltOrderSelect.empty())
        OS << "    ArrayRef<unsigned> "
              "getRawAllocationOrder(const MachineFunction&) const;\n";
      OS << "  };\n";

      // Output the extern for the instance.
      OS << "  extern " << Name << "Class\t" << Name << "RegClass;\n";
      // Output the extern for the pointer to the instance (should remove).
      OS << "  static TargetRegisterClass * const "<< Name <<"RegisterClass = &"
         << Name << "RegClass;\n";
    }
    OS << "} // end of namespace " << TargetName << "\n\n";
  }
  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_HEADER\n\n";
}
Beispiel #16
0
//
// runMCDesc - Print out MC register descriptions.
//
void
RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
                               CodeGenRegBank &RegBank) {
  EmitSourceFileHeader("MC Register Information", OS);

  OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
  OS << "#undef GET_REGINFO_MC_DESC\n";

  std::map<const CodeGenRegister*, CodeGenRegister::Set> Overlaps;
  RegBank.computeOverlaps(Overlaps);

  OS << "namespace llvm {\n\n";

  const std::string &TargetName = Target.getName();

  OS << "\nnamespace {\n";

  const std::vector<CodeGenRegister*> &Regs = RegBank.getRegisters();

  // Emit an overlap list for all registers.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister *Reg = Regs[i];
    const CodeGenRegister::Set &O = Overlaps[Reg];
    // Move Reg to the front so TRI::getAliasSet can share the list.
    OS << "  const unsigned " << Reg->getName() << "_Overlaps[] = { "
       << getQualifiedName(Reg->TheDef) << ", ";
    for (CodeGenRegister::Set::const_iterator I = O.begin(), E = O.end();
         I != E; ++I)
      if (*I != Reg)
        OS << getQualifiedName((*I)->TheDef) << ", ";
    OS << "0 };\n";
  }

  // Emit the empty sub-registers list
  OS << "  const unsigned Empty_SubRegsSet[] = { 0 };\n";
  // Loop over all of the registers which have sub-registers, emitting the
  // sub-registers list to memory.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister &Reg = *Regs[i];
    if (Reg.getSubRegs().empty())
     continue;
    // getSubRegs() orders by SubRegIndex. We want a topological order.
    SetVector<CodeGenRegister*> SR;
    Reg.addSubRegsPreOrder(SR);
    OS << "  const unsigned " << Reg.getName() << "_SubRegsSet[] = { ";
    for (unsigned j = 0, je = SR.size(); j != je; ++j)
      OS << getQualifiedName(SR[j]->TheDef) << ", ";
    OS << "0 };\n";
  }

  // Emit the empty super-registers list
  OS << "  const unsigned Empty_SuperRegsSet[] = { 0 };\n";
  // Loop over all of the registers which have super-registers, emitting the
  // super-registers list to memory.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister &Reg = *Regs[i];
    const CodeGenRegister::SuperRegList &SR = Reg.getSuperRegs();
    if (SR.empty())
      continue;
    OS << "  const unsigned " << Reg.getName() << "_SuperRegsSet[] = { ";
    for (unsigned j = 0, je = SR.size(); j != je; ++j)
      OS << getQualifiedName(SR[j]->TheDef) << ", ";
    OS << "0 };\n";
  }
  OS << "}\n";       // End of anonymous namespace...

  OS << "\nextern const MCRegisterDesc " << TargetName
     << "RegDesc[] = { // Descriptors\n";
  OS << "  { \"NOREG\",\t0,\t0,\t0 },\n";

  // Now that register alias and sub-registers sets have been emitted, emit the
  // register descriptors now.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister &Reg = *Regs[i];
    OS << "  { \"";
    OS << Reg.getName() << "\",\t" << Reg.getName() << "_Overlaps,\t";
    if (!Reg.getSubRegs().empty())
      OS << Reg.getName() << "_SubRegsSet,\t";
    else
      OS << "Empty_SubRegsSet,\t";
    if (!Reg.getSuperRegs().empty())
      OS << Reg.getName() << "_SuperRegsSet";
    else
      OS << "Empty_SuperRegsSet";
    OS << " },\n";
  }
  OS << "};\n\n";      // End of register descriptors...

  ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

  // Loop over all of the register classes... emitting each one.
  OS << "namespace {     // Register classes...\n";

  // Emit the register enum value arrays for each RegisterClass
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];
    ArrayRef<Record*> Order = RC.getOrder();

    // Give the register class a legal C name if it's anonymous.
    std::string Name = RC.getName();

    // Emit the register list now.
    OS << "  // " << Name << " Register Class...\n"
       << "  static const unsigned " << Name
       << "[] = {\n    ";
    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
      Record *Reg = Order[i];
      OS << getQualifiedName(Reg) << ", ";
    }
    OS << "\n  };\n\n";

    OS << "  // " << Name << " Bit set.\n"
       << "  static const unsigned char " << Name
       << "Bits[] = {\n    ";
    BitVectorEmitter BVE;
    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
      Record *Reg = Order[i];
      BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
    }
    BVE.print(OS);
    OS << "\n  };\n\n";

  }
  OS << "}\n\n";

  OS << "extern const MCRegisterClass " << TargetName
     << "MCRegisterClasses[] = {\n";

  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];
    OS << "  MCRegisterClass(" << RC.getQualifiedName() + "RegClassID" << ", "
       << '\"' << RC.getName() << "\", "
       << RC.SpillSize/8 << ", "
       << RC.SpillAlignment/8 << ", "
       << RC.CopyCost << ", "
       << RC.Allocatable << ", "
       << RC.getName() << ", " << RC.getName() << " + "
       << RC.getOrder().size() << ", "
       << RC.getName() << "Bits, sizeof(" << RC.getName() << "Bits)"
       << "),\n";
  }

  OS << "};\n\n";

  // MCRegisterInfo initialization routine.
  OS << "static inline void Init" << TargetName
     << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
     << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0) {\n";
  OS << "  RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
     << Regs.size()+1 << ", RA, " << TargetName << "MCRegisterClasses, "
     << RegisterClasses.size() << ");\n\n";

  EmitRegMapping(OS, Regs, false);

  OS << "}\n\n";


  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_MC_DESC\n\n";
}
Beispiel #17
0
//
// runMCDesc - Print out MC register descriptions.
//
void
RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
                               CodeGenRegBank &RegBank) {
    EmitSourceFileHeader("MC Register Information", OS);

    OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
    OS << "#undef GET_REGINFO_MC_DESC\n";

    std::map<const CodeGenRegister*, CodeGenRegister::Set> Overlaps;
    RegBank.computeOverlaps(Overlaps);

    OS << "namespace llvm {\n\n";

    const std::string &TargetName = Target.getName();

    const std::vector<CodeGenRegister*> &Regs = RegBank.getRegisters();

    OS << "extern const uint16_t " << TargetName << "RegOverlaps[] = {\n";

    // Emit an overlap list for all registers.
    for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
        const CodeGenRegister *Reg = Regs[i];
        const CodeGenRegister::Set &O = Overlaps[Reg];
        // Move Reg to the front so TRI::getAliasSet can share the list.
        OS << "  /* " << Reg->getName() << "_Overlaps */ "
           << getQualifiedName(Reg->TheDef) << ", ";
        for (CodeGenRegister::Set::const_iterator I = O.begin(), E = O.end();
                I != E; ++I)
            if (*I != Reg)
                OS << getQualifiedName((*I)->TheDef) << ", ";
        OS << "0,\n";
    }
    OS << "};\n\n";

    OS << "extern const uint16_t " << TargetName << "SubRegsSet[] = {\n";
    // Emit the empty sub-registers list
    OS << "  /* Empty_SubRegsSet */ 0,\n";
    // Loop over all of the registers which have sub-registers, emitting the
    // sub-registers list to memory.
    for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
        const CodeGenRegister &Reg = *Regs[i];
        if (Reg.getSubRegs().empty())
            continue;
        // getSubRegs() orders by SubRegIndex. We want a topological order.
        SetVector<CodeGenRegister*> SR;
        Reg.addSubRegsPreOrder(SR, RegBank);
        OS << "  /* " << Reg.getName() << "_SubRegsSet */ ";
        for (unsigned j = 0, je = SR.size(); j != je; ++j)
            OS << getQualifiedName(SR[j]->TheDef) << ", ";
        OS << "0,\n";
    }
    OS << "};\n\n";

    OS << "extern const uint16_t " << TargetName << "SuperRegsSet[] = {\n";
    // Emit the empty super-registers list
    OS << "  /* Empty_SuperRegsSet */ 0,\n";
    // Loop over all of the registers which have super-registers, emitting the
    // super-registers list to memory.
    for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
        const CodeGenRegister &Reg = *Regs[i];
        const CodeGenRegister::SuperRegList &SR = Reg.getSuperRegs();
        if (SR.empty())
            continue;
        OS << "  /* " << Reg.getName() << "_SuperRegsSet */ ";
        for (unsigned j = 0, je = SR.size(); j != je; ++j)
            OS << getQualifiedName(SR[j]->TheDef) << ", ";
        OS << "0,\n";
    }
    OS << "};\n\n";

    OS << "extern const MCRegisterDesc " << TargetName
       << "RegDesc[] = { // Descriptors\n";
    OS << "  { \"NOREG\", 0, 0, 0 },\n";

    // Now that register alias and sub-registers sets have been emitted, emit the
    // register descriptors now.
    unsigned OverlapsIndex = 0;
    unsigned SubRegIndex = 1; // skip 1 for empty set
    unsigned SuperRegIndex = 1; // skip 1 for empty set
    for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
        const CodeGenRegister *Reg = Regs[i];
        OS << "  { \"";
        OS << Reg->getName() << "\", /* " << Reg->getName() << "_Overlaps */ "
           << OverlapsIndex << ", ";
        OverlapsIndex += Overlaps[Reg].size() + 1;
        if (!Reg->getSubRegs().empty()) {
            OS << "/* " << Reg->getName() << "_SubRegsSet */ " << SubRegIndex
               << ", ";
            // FIXME not very nice to recalculate this
            SetVector<CodeGenRegister*> SR;
            Reg->addSubRegsPreOrder(SR, RegBank);
            SubRegIndex += SR.size() + 1;
        } else
            OS << "/* Empty_SubRegsSet */ 0, ";
        if (!Reg->getSuperRegs().empty()) {
            OS << "/* " << Reg->getName() << "_SuperRegsSet */ " << SuperRegIndex;
            SuperRegIndex += Reg->getSuperRegs().size() + 1;
        } else
            OS << "/* Empty_SuperRegsSet */ 0";
        OS << " },\n";
    }
    OS << "};\n\n";      // End of register descriptors...

    ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

    // Loop over all of the register classes... emitting each one.
    OS << "namespace {     // Register classes...\n";

    // Emit the register enum value arrays for each RegisterClass
    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
        const CodeGenRegisterClass &RC = *RegisterClasses[rc];
        ArrayRef<Record*> Order = RC.getOrder();

        // Give the register class a legal C name if it's anonymous.
        std::string Name = RC.getName();

        // Emit the register list now.
        OS << "  // " << Name << " Register Class...\n"
           << "  const uint16_t " << Name
           << "[] = {\n    ";
        for (unsigned i = 0, e = Order.size(); i != e; ++i) {
            Record *Reg = Order[i];
            OS << getQualifiedName(Reg) << ", ";
        }
        OS << "\n  };\n\n";

        OS << "  // " << Name << " Bit set.\n"
           << "  const uint8_t " << Name
           << "Bits[] = {\n    ";
        BitVectorEmitter BVE;
        for (unsigned i = 0, e = Order.size(); i != e; ++i) {
            Record *Reg = Order[i];
            BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
        }
        BVE.print(OS);
        OS << "\n  };\n\n";

    }
    OS << "}\n\n";

    OS << "extern const MCRegisterClass " << TargetName
       << "MCRegisterClasses[] = {\n";

    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
        const CodeGenRegisterClass &RC = *RegisterClasses[rc];

        // Asserts to make sure values will fit in table assuming types from
        // MCRegisterInfo.h
        assert((RC.SpillSize/8) <= 0xffff && "SpillSize too large.");
        assert((RC.SpillAlignment/8) <= 0xffff && "SpillAlignment too large.");
        assert(RC.CopyCost >= -128 && RC.CopyCost <= 127 && "Copy cost too large.");

        OS << "  { " << '\"' << RC.getName() << "\", "
           << RC.getName() << ", " << RC.getName() << "Bits, "
           << RC.getOrder().size() << ", sizeof(" << RC.getName() << "Bits), "
           << RC.getQualifiedName() + "RegClassID" << ", "
           << RC.SpillSize/8 << ", "
           << RC.SpillAlignment/8 << ", "
           << RC.CopyCost << ", "
           << RC.Allocatable << " },\n";
    }

    OS << "};\n\n";

    // Emit the data table for getSubReg().
    ArrayRef<CodeGenSubRegIndex*> SubRegIndices = RegBank.getSubRegIndices();
    if (SubRegIndices.size()) {
        OS << "const uint16_t " << TargetName << "SubRegTable[]["
           << SubRegIndices.size() << "] = {\n";
        for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
            const CodeGenRegister::SubRegMap &SRM = Regs[i]->getSubRegs();
            OS << "  /* " << Regs[i]->TheDef->getName() << " */\n";
            if (SRM.empty()) {
                OS << "  {0},\n";
                continue;
            }
            OS << "  {";
            for (unsigned j = 0, je = SubRegIndices.size(); j != je; ++j) {
                // FIXME: We really should keep this to 80 columns...
                CodeGenRegister::SubRegMap::const_iterator SubReg =
                    SRM.find(SubRegIndices[j]);
                if (SubReg != SRM.end())
                    OS << getQualifiedName(SubReg->second->TheDef);
                else
                    OS << "0";
                if (j != je - 1)
                    OS << ", ";
            }
            OS << "}" << (i != e ? "," : "") << "\n";
        }
        OS << "};\n\n";
        OS << "const uint16_t *get" << TargetName
           << "SubRegTable() {\n  return (const uint16_t *)" << TargetName
           << "SubRegTable;\n}\n\n";
    }

    // MCRegisterInfo initialization routine.
    OS << "static inline void Init" << TargetName
       << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
       << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0) {\n";
    OS << "  RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
       << Regs.size()+1 << ", RA, " << TargetName << "MCRegisterClasses, "
       << RegisterClasses.size() << ", " << TargetName << "RegOverlaps, "
       << TargetName << "SubRegsSet, " << TargetName << "SuperRegsSet, ";
    if (SubRegIndices.size() != 0)
        OS << "(uint16_t*)" << TargetName << "SubRegTable, "
           << SubRegIndices.size() << ");\n\n";
    else
        OS << "NULL, 0);\n\n";

    EmitRegMapping(OS, Regs, false);

    OS << "}\n\n";

    OS << "} // End llvm namespace \n";
    OS << "#endif // GET_REGINFO_MC_DESC\n\n";
}
Beispiel #18
0
//
// runMCDesc - Print out MC register descriptions.
//
void
RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
                               CodeGenRegBank &RegBank) {
  EmitSourceFileHeader("MC Register Information", OS);

  OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
  OS << "#undef GET_REGINFO_MC_DESC\n";

  const std::vector<CodeGenRegister*> &Regs = RegBank.getRegisters();

  // The lists of sub-registers, super-registers, and overlaps all go in the
  // same array. That allows us to share suffixes.
  typedef std::vector<const CodeGenRegister*> RegVec;
  SmallVector<RegVec, 4> SubRegLists(Regs.size());
  SmallVector<RegVec, 4> OverlapLists(Regs.size());
  SequenceToOffsetTable<RegVec, CodeGenRegister::Less> RegSeqs;

  // Precompute register lists for the SequenceToOffsetTable.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister *Reg = Regs[i];

    // Compute the ordered sub-register list.
    SetVector<const CodeGenRegister*> SR;
    Reg->addSubRegsPreOrder(SR, RegBank);
    RegVec &SubRegList = SubRegLists[i];
    SubRegList.assign(SR.begin(), SR.end());
    RegSeqs.add(SubRegList);

    // Super-registers are already computed.
    const RegVec &SuperRegList = Reg->getSuperRegs();
    RegSeqs.add(SuperRegList);

    // The list of overlaps doesn't need to have any particular order, except
    // Reg itself must be the first element. Pick an ordering that has one of
    // the other lists as a suffix.
    RegVec &OverlapList = OverlapLists[i];
    const RegVec &Suffix = SubRegList.size() > SuperRegList.size() ?
                           SubRegList : SuperRegList;
    CodeGenRegister::Set Omit(Suffix.begin(), Suffix.end());

    // First element is Reg itself.
    OverlapList.push_back(Reg);
    Omit.insert(Reg);

    // Any elements not in Suffix.
    CodeGenRegister::Set OSet;
    Reg->computeOverlaps(OSet, RegBank);
    std::set_difference(OSet.begin(), OSet.end(),
                        Omit.begin(), Omit.end(),
                        std::back_inserter(OverlapList),
                        CodeGenRegister::Less());

    // Finally, Suffix itself.
    OverlapList.insert(OverlapList.end(), Suffix.begin(), Suffix.end());
    RegSeqs.add(OverlapList);
  }

  // Compute the final layout of the sequence table.
  RegSeqs.layout();

  OS << "namespace llvm {\n\n";

  const std::string &TargetName = Target.getName();

  // Emit the shared table of register lists.
  OS << "extern const uint16_t " << TargetName << "RegLists[] = {\n";
  RegSeqs.emit(OS, printRegister);
  OS << "};\n\n";

  OS << "extern const MCRegisterDesc " << TargetName
     << "RegDesc[] = { // Descriptors\n";
  OS << "  { \"NOREG\", 0, 0, 0 },\n";

  // Emit the register descriptors now.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister *Reg = Regs[i];
    OS << "  { \"" << Reg->getName() << "\", "
       << RegSeqs.get(OverlapLists[i]) << ", "
       << RegSeqs.get(SubRegLists[i]) << ", "
       << RegSeqs.get(Reg->getSuperRegs()) << " },\n";
  }
  OS << "};\n\n";      // End of register descriptors...

  ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

  // Loop over all of the register classes... emitting each one.
  OS << "namespace {     // Register classes...\n";

  // Emit the register enum value arrays for each RegisterClass
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];
    ArrayRef<Record*> Order = RC.getOrder();

    // Give the register class a legal C name if it's anonymous.
    std::string Name = RC.getName();

    // Emit the register list now.
    OS << "  // " << Name << " Register Class...\n"
       << "  const uint16_t " << Name
       << "[] = {\n    ";
    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
      Record *Reg = Order[i];
      OS << getQualifiedName(Reg) << ", ";
    }
    OS << "\n  };\n\n";

    OS << "  // " << Name << " Bit set.\n"
       << "  const uint8_t " << Name
       << "Bits[] = {\n    ";
    BitVectorEmitter BVE;
    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
      Record *Reg = Order[i];
      BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
    }
    BVE.print(OS);
    OS << "\n  };\n\n";

  }
  OS << "}\n\n";

  OS << "extern const MCRegisterClass " << TargetName
     << "MCRegisterClasses[] = {\n";

  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];

    // Asserts to make sure values will fit in table assuming types from
    // MCRegisterInfo.h
    assert((RC.SpillSize/8) <= 0xffff && "SpillSize too large.");
    assert((RC.SpillAlignment/8) <= 0xffff && "SpillAlignment too large.");
    assert(RC.CopyCost >= -128 && RC.CopyCost <= 127 && "Copy cost too large.");

    OS << "  { " << '\"' << RC.getName() << "\", "
       << RC.getName() << ", " << RC.getName() << "Bits, "
       << RC.getOrder().size() << ", sizeof(" << RC.getName() << "Bits), "
       << RC.getQualifiedName() + "RegClassID" << ", "
       << RC.SpillSize/8 << ", "
       << RC.SpillAlignment/8 << ", "
       << RC.CopyCost << ", "
       << RC.Allocatable << " },\n";
  }

  OS << "};\n\n";

  // Emit the data table for getSubReg().
  ArrayRef<CodeGenSubRegIndex*> SubRegIndices = RegBank.getSubRegIndices();
  if (SubRegIndices.size()) {
    OS << "const uint16_t " << TargetName << "SubRegTable[]["
       << SubRegIndices.size() << "] = {\n";
    for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
      const CodeGenRegister::SubRegMap &SRM = Regs[i]->getSubRegs();
      OS << "  /* " << Regs[i]->TheDef->getName() << " */\n";
      if (SRM.empty()) {
        OS << "  {0},\n";
        continue;
      }
      OS << "  {";
      for (unsigned j = 0, je = SubRegIndices.size(); j != je; ++j) {
        // FIXME: We really should keep this to 80 columns...
        CodeGenRegister::SubRegMap::const_iterator SubReg =
          SRM.find(SubRegIndices[j]);
        if (SubReg != SRM.end())
          OS << getQualifiedName(SubReg->second->TheDef);
        else
          OS << "0";
        if (j != je - 1)
          OS << ", ";
      }
      OS << "}" << (i != e ? "," : "") << "\n";
    }
    OS << "};\n\n";
    OS << "const uint16_t *get" << TargetName
       << "SubRegTable() {\n  return (const uint16_t *)" << TargetName
       << "SubRegTable;\n}\n\n";
  }

  EmitRegMappingTables(OS, Regs, false);

  // Emit Reg encoding table
  OS << "extern const uint16_t " << TargetName;
  OS << "RegEncodingTable[] = {\n";
  // Add entry for NoRegister
  OS << "  0,\n";
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    Record *Reg = Regs[i]->TheDef;
    BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
    uint64_t Value = 0;
    for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
      if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(b)))
      Value |= (uint64_t)B->getValue() << b;
    }
    OS << "  " << Value << ",\n";
  }
  OS << "};\n";       // End of HW encoding table

  // MCRegisterInfo initialization routine.
  OS << "static inline void Init" << TargetName
     << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
     << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0) {\n";
  OS << "  RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
     << Regs.size()+1 << ", RA, " << TargetName << "MCRegisterClasses, "
     << RegisterClasses.size() << ", " << TargetName << "RegLists, ";
  if (SubRegIndices.size() != 0)
    OS << "(uint16_t*)" << TargetName << "SubRegTable, "
       << SubRegIndices.size() << ",\n";
  else
    OS << "NULL, 0,\n";

  OS << "  " << TargetName << "RegEncodingTable);\n\n";

  EmitRegMapping(OS, Regs, false);

  OS << "}\n\n";

  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_MC_DESC\n\n";
}
/// Generate a table and function for looking up the indices of operands by
/// name.
///
/// This code generates:
/// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
///   for each operand name.
/// - A 2-dimensional table called OperandMap for mapping OpName enum values to
///   operand indices.
/// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
///   for looking up the operand index for an instruction, given a value from
///   OpName enum
void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
           const CodeGenTarget &Target,
           const std::vector<const CodeGenInstruction*> &NumberedInstructions) {

  const std::string &Namespace = Target.getInstNamespace();
  std::string OpNameNS = "OpName";
  // Map of operand names to their enumeration value.  This will be used to
  // generate the OpName enum.
  std::map<std::string, unsigned> Operands;
  OpNameMapTy OperandMap;

  initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);

  OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
  OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
  OS << "namespace llvm {\n";
  OS << "namespace " << Namespace << " {\n";
  OS << "namespace " << OpNameNS << " { \n";
  OS << "enum {\n";
  for (const auto &Op : Operands)
    OS << "  " << Op.first << " = " << Op.second << ",\n";

  OS << "OPERAND_LAST";
  OS << "\n};\n";
  OS << "} // end namespace OpName\n";
  OS << "} // end namespace " << Namespace << "\n";
  OS << "} // end namespace llvm\n";
  OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n";

  OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
  OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
  OS << "namespace llvm {\n";
  OS << "namespace " << Namespace << " {\n";
  OS << "LLVM_READONLY\n";
  OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
  if (!Operands.empty()) {
    OS << "  static const int16_t OperandMap [][" << Operands.size()
       << "] = {\n";
    for (const auto &Entry : OperandMap) {
      const std::map<unsigned, unsigned> &OpList = Entry.first;
      OS << "{";

      // Emit a row of the OperandMap table
      for (unsigned i = 0, e = Operands.size(); i != e; ++i)
        OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";

      OS << "},\n";
    }
    OS << "};\n";

    OS << "  switch(Opcode) {\n";
    unsigned TableIndex = 0;
    for (const auto &Entry : OperandMap) {
      for (const std::string &Name : Entry.second)
        OS << "  case " << Name << ":\n";

      OS << "    return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
    }
    OS << "    default: return -1;\n";
    OS << "  }\n";
  } else {
    // There are no operands, so no need to emit anything
    OS << "  return -1;\n";
  }
  OS << "}\n";
  OS << "} // end namespace " << Namespace << "\n";
  OS << "} // end namespace llvm\n";
  OS << "#endif //GET_INSTRINFO_NAMED_OPS\n";

}
Beispiel #20
0
CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
  AsmString = R->getValueAsString("AsmString");
  Result = R->getValueAsDag("ResultInst");

  // Verify that the root of the result is an instruction.
  DefInit *DI = dynamic_cast<DefInit*>(Result->getOperator());
  if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
    throw TGError(R->getLoc(), "result of inst alias should be an instruction");

  ResultInst = &T.getInstruction(DI->getDef());

  // NameClass - If argument names are repeated, we need to verify they have
  // the same class.
  StringMap<Record*> NameClass;
  for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
    DefInit *ADI = dynamic_cast<DefInit*>(Result->getArg(i));
    if (!ADI || Result->getArgName(i).empty())
      continue;
    // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
    // $foo can exist multiple times in the result list, but it must have the
    // same type.
    Record *&Entry = NameClass[Result->getArgName(i)];
    if (Entry && Entry != ADI->getDef())
      throw TGError(R->getLoc(), "result value $" + Result->getArgName(i) +
                    " is both " + Entry->getName() + " and " +
                    ADI->getDef()->getName() + "!");
    Entry = ADI->getDef();
  }

  // Decode and validate the arguments of the result.
  unsigned AliasOpNo = 0;
  for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {

    // Tied registers don't have an entry in the result dag.
    if (ResultInst->Operands[i].getTiedRegister() != -1)
      continue;

    if (AliasOpNo >= Result->getNumArgs())
      throw TGError(R->getLoc(), "not enough arguments for instruction!");

    Record *InstOpRec = ResultInst->Operands[i].Rec;
    unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
    ResultOperand ResOp(static_cast<int64_t>(0));
    if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
                        R->getLoc(), T, ResOp)) {
      ResultOperands.push_back(ResOp);
      ResultInstOperandIndex.push_back(std::make_pair(i, -1));
      ++AliasOpNo;
      continue;
    }

    // If the argument did not match the instruction operand, and the operand
    // is composed of multiple suboperands, try matching the suboperands.
    if (NumSubOps > 1) {
      DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
      for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
        if (AliasOpNo >= Result->getNumArgs())
          throw TGError(R->getLoc(), "not enough arguments for instruction!");
        Record *SubRec = dynamic_cast<DefInit*>(MIOI->getArg(SubOp))->getDef();
        if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
                            R->getLoc(), T, ResOp)) {
          ResultOperands.push_back(ResOp);
          ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
          ++AliasOpNo;
        } else {
          throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
                        " does not match instruction operand class " +
                        (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
        }
      }
      continue;
    }
    throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
                  " does not match instruction operand class " +
                  InstOpRec->getName());
  }

  if (AliasOpNo != Result->getNumArgs())
    throw TGError(R->getLoc(), "too many operands for instruction!");
}
// RegisterInfoEmitter::run - Main register file description emitter.
//
void RegisterInfoEmitter::run(raw_ostream &OS) {
  CodeGenTarget Target;
  EmitSourceFileHeader("Register Information Source Fragment", OS);

  OS << "namespace llvm {\n\n";

  // Start out by emitting each of the register classes... to do this, we build
  // a set of registers which belong to a register class, this is to ensure that
  // each register is only in a single register class.
  //
  const std::vector<CodeGenRegisterClass> &RegisterClasses =
    Target.getRegisterClasses();

  // Loop over all of the register classes... emitting each one.
  OS << "namespace {     // Register classes...\n";

  // RegClassesBelongedTo - Keep track of which register classes each reg
  // belongs to.
  std::multimap<Record*, const CodeGenRegisterClass*> RegClassesBelongedTo;

  // Emit the register enum value arrays for each RegisterClass
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = RegisterClasses[rc];

    // Give the register class a legal C name if it's anonymous.
    std::string Name = RC.TheDef->getName();
  
    // Emit the register list now.
    OS << "  // " << Name << " Register Class...\n"
       << "  static const unsigned " << Name
       << "[] = {\n    ";
    for (unsigned i = 0, e = RC.Elements.size(); i != e; ++i) {
      Record *Reg = RC.Elements[i];
      OS << getQualifiedName(Reg) << ", ";

      // Keep track of which regclasses this register is in.
      RegClassesBelongedTo.insert(std::make_pair(Reg, &RC));
    }
    OS << "\n  };\n\n";
  }

  // Emit the ValueType arrays for each RegisterClass
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = RegisterClasses[rc];
    
    // Give the register class a legal C name if it's anonymous.
    std::string Name = RC.TheDef->getName() + "VTs";
    
    // Emit the register list now.
    OS << "  // " << Name 
       << " Register Class Value Types...\n"
       << "  static const EVT " << Name
       << "[] = {\n    ";
    for (unsigned i = 0, e = RC.VTs.size(); i != e; ++i)
      OS << getEnumName(RC.VTs[i]) << ", ";
    OS << "MVT::Other\n  };\n\n";
  }
  OS << "}  // end anonymous namespace\n\n";
  
  // Now that all of the structs have been emitted, emit the instances.
  if (!RegisterClasses.empty()) {
    OS << "namespace " << RegisterClasses[0].Namespace
       << " {   // Register class instances\n";
    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i)
      OS << "  " << RegisterClasses[i].getName()  << "Class\t"
         << RegisterClasses[i].getName() << "RegClass;\n";
         
    std::map<unsigned, std::set<unsigned> > SuperClassMap;
    std::map<unsigned, std::set<unsigned> > SuperRegClassMap;
    OS << "\n";

    unsigned NumSubRegIndices = Target.getSubRegIndices().size();

    if (NumSubRegIndices) {
      // Emit the sub-register classes for each RegisterClass
      for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
        const CodeGenRegisterClass &RC = RegisterClasses[rc];
        std::vector<Record*> SRC(NumSubRegIndices);
        for (DenseMap<Record*,Record*>::const_iterator
             i = RC.SubRegClasses.begin(),
             e = RC.SubRegClasses.end(); i != e; ++i) {
          // Build SRC array.
          unsigned idx = Target.getSubRegIndexNo(i->first);
          SRC.at(idx-1) = i->second;

          // Find the register class number of i->second for SuperRegClassMap.
          for (unsigned rc2 = 0, e2 = RegisterClasses.size(); rc2 != e2; ++rc2) {
            const CodeGenRegisterClass &RC2 =  RegisterClasses[rc2];
            if (RC2.TheDef == i->second) {
              SuperRegClassMap[rc2].insert(rc);
              break;
            }
          }
        }

        // Give the register class a legal C name if it's anonymous.
        std::string Name = RC.TheDef->getName();

        OS << "  // " << Name
           << " Sub-register Classes...\n"
           << "  static const TargetRegisterClass* const "
           << Name << "SubRegClasses[] = {\n    ";

        for (unsigned idx = 0; idx != NumSubRegIndices; ++idx) {
          if (idx)
            OS << ", ";
          if (SRC[idx])
            OS << "&" << getQualifiedName(SRC[idx]) << "RegClass";
          else
            OS << "0";
        }
        OS << "\n  };\n\n";
      }

      // Emit the super-register classes for each RegisterClass
      for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
        const CodeGenRegisterClass &RC = RegisterClasses[rc];

        // Give the register class a legal C name if it's anonymous.
        std::string Name = RC.TheDef->getName();

        OS << "  // " << Name
           << " Super-register Classes...\n"
           << "  static const TargetRegisterClass* const "
           << Name << "SuperRegClasses[] = {\n    ";

        bool Empty = true;
        std::map<unsigned, std::set<unsigned> >::iterator I =
          SuperRegClassMap.find(rc);
        if (I != SuperRegClassMap.end()) {
          for (std::set<unsigned>::iterator II = I->second.begin(),
                 EE = I->second.end(); II != EE; ++II) {
            const CodeGenRegisterClass &RC2 = RegisterClasses[*II];
            if (!Empty)
              OS << ", ";
            OS << "&" << getQualifiedName(RC2.TheDef) << "RegClass";
            Empty = false;
          }
        }

        OS << (!Empty ? ", " : "") << "NULL";
        OS << "\n  };\n\n";
      }
    } else {
      // No subregindices in this target
      OS << "  static const TargetRegisterClass* const "
         << "NullRegClasses[] = { NULL };\n\n";
    }

    // Emit the sub-classes array for each RegisterClass
    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
      const CodeGenRegisterClass &RC = RegisterClasses[rc];

      // Give the register class a legal C name if it's anonymous.
      std::string Name = RC.TheDef->getName();

      std::set<Record*> RegSet;
      for (unsigned i = 0, e = RC.Elements.size(); i != e; ++i) {
        Record *Reg = RC.Elements[i];
        RegSet.insert(Reg);
      }

      OS << "  // " << Name 
         << " Register Class sub-classes...\n"
         << "  static const TargetRegisterClass* const "
         << Name << "Subclasses[] = {\n    ";

      bool Empty = true;
      for (unsigned rc2 = 0, e2 = RegisterClasses.size(); rc2 != e2; ++rc2) {
        const CodeGenRegisterClass &RC2 = RegisterClasses[rc2];

        // RC2 is a sub-class of RC if it is a valid replacement for any
        // instruction operand where an RC register is required. It must satisfy
        // these conditions:
        //
        // 1. All RC2 registers are also in RC.
        // 2. The RC2 spill size must not be smaller that the RC spill size.
        // 3. RC2 spill alignment must be compatible with RC.
        //
        // Sub-classes are used to determine if a virtual register can be used
        // as an instruction operand, or if it must be copied first.

        if (rc == rc2 || RC2.Elements.size() > RC.Elements.size() ||
            (RC.SpillAlignment && RC2.SpillAlignment % RC.SpillAlignment) ||
            RC.SpillSize > RC2.SpillSize || !isSubRegisterClass(RC2, RegSet))
          continue;
      
        if (!Empty) OS << ", ";
        OS << "&" << getQualifiedName(RC2.TheDef) << "RegClass";
        Empty = false;

        std::map<unsigned, std::set<unsigned> >::iterator SCMI =
          SuperClassMap.find(rc2);
        if (SCMI == SuperClassMap.end()) {
          SuperClassMap.insert(std::make_pair(rc2, std::set<unsigned>()));
          SCMI = SuperClassMap.find(rc2);
        }
        SCMI->second.insert(rc);
      }

      OS << (!Empty ? ", " : "") << "NULL";
      OS << "\n  };\n\n";
    }

    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
      const CodeGenRegisterClass &RC = RegisterClasses[rc];

      // Give the register class a legal C name if it's anonymous.
      std::string Name = RC.TheDef->getName();

      OS << "  // " << Name 
         << " Register Class super-classes...\n"
         << "  static const TargetRegisterClass* const "
         << Name << "Superclasses[] = {\n    ";

      bool Empty = true;
      std::map<unsigned, std::set<unsigned> >::iterator I =
        SuperClassMap.find(rc);
      if (I != SuperClassMap.end()) {
        for (std::set<unsigned>::iterator II = I->second.begin(),
               EE = I->second.end(); II != EE; ++II) {
          const CodeGenRegisterClass &RC2 = RegisterClasses[*II];
          if (!Empty) OS << ", ";
          OS << "&" << getQualifiedName(RC2.TheDef) << "RegClass";
          Empty = false;        
        }
      }

      OS << (!Empty ? ", " : "") << "NULL";
      OS << "\n  };\n\n";
    }


    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
      const CodeGenRegisterClass &RC = RegisterClasses[i];
      OS << RC.MethodBodies << "\n";
      OS << RC.getName() << "Class::" << RC.getName() 
         << "Class()  : TargetRegisterClass("
         << RC.getName() + "RegClassID" << ", "
         << '\"' << RC.getName() << "\", "
         << RC.getName() + "VTs" << ", "
         << RC.getName() + "Subclasses" << ", "
         << RC.getName() + "Superclasses" << ", "
         << (NumSubRegIndices ? RC.getName() + "Sub" : std::string("Null"))
         << "RegClasses, "
         << (NumSubRegIndices ? RC.getName() + "Super" : std::string("Null"))
         << "RegClasses, "
         << RC.SpillSize/8 << ", "
         << RC.SpillAlignment/8 << ", "
         << RC.CopyCost << ", "
         << RC.getName() << ", " << RC.getName() << " + " << RC.Elements.size()
         << ") {}\n";
    }
  
    OS << "}\n";
  }

  OS << "\nnamespace {\n";
  OS << "  const TargetRegisterClass* const RegisterClasses[] = {\n";
  for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i)
    OS << "    &" << getQualifiedName(RegisterClasses[i].TheDef)
       << "RegClass,\n";
  OS << "  };\n";

  // Emit register sub-registers / super-registers, aliases...
  std::map<Record*, std::set<Record*>, LessRecord> RegisterSubRegs;
  std::map<Record*, std::set<Record*>, LessRecord> RegisterSuperRegs;
  std::map<Record*, std::set<Record*>, LessRecord> RegisterAliases;
  typedef std::map<Record*, std::vector<int64_t>, LessRecord> DwarfRegNumsMapTy;
  DwarfRegNumsMapTy DwarfRegNums;
  
  const std::vector<CodeGenRegister> &Regs = Target.getRegisters();

  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    Record *R = Regs[i].TheDef;
    std::vector<Record*> LI = Regs[i].TheDef->getValueAsListOfDefs("Aliases");
    // Add information that R aliases all of the elements in the list... and
    // that everything in the list aliases R.
    for (unsigned j = 0, e = LI.size(); j != e; ++j) {
      Record *Reg = LI[j];
      if (RegisterAliases[R].count(Reg))
        errs() << "Warning: register alias between " << getQualifiedName(R)
               << " and " << getQualifiedName(Reg)
               << " specified multiple times!\n";
      RegisterAliases[R].insert(Reg);

      if (RegisterAliases[Reg].count(R))
        errs() << "Warning: register alias between " << getQualifiedName(R)
               << " and " << getQualifiedName(Reg)
               << " specified multiple times!\n";
      RegisterAliases[Reg].insert(R);
    }
  }

  // Process sub-register sets.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    Record *R = Regs[i].TheDef;
    std::vector<Record*> LI = Regs[i].TheDef->getValueAsListOfDefs("SubRegs");
    // Process sub-register set and add aliases information.
    for (unsigned j = 0, e = LI.size(); j != e; ++j) {
      Record *SubReg = LI[j];
      if (RegisterSubRegs[R].count(SubReg))
        errs() << "Warning: register " << getQualifiedName(SubReg)
               << " specified as a sub-register of " << getQualifiedName(R)
               << " multiple times!\n";
      addSubSuperReg(R, SubReg, RegisterSubRegs, RegisterSuperRegs,
                     RegisterAliases);
    }
  }
  
  // Print the SubregHashTable, a simple quadratically probed
  // hash table for determining if a register is a subregister
  // of another register.
  unsigned NumSubRegs = 0;
  std::map<Record*, unsigned> RegNo;
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    RegNo[Regs[i].TheDef] = i;
    NumSubRegs += RegisterSubRegs[Regs[i].TheDef].size();
  }
  
  unsigned SubregHashTableSize = 2 * NextPowerOf2(2 * NumSubRegs);
  unsigned* SubregHashTable = new unsigned[2 * SubregHashTableSize];
  std::fill(SubregHashTable, SubregHashTable + 2 * SubregHashTableSize, ~0U);
  
  unsigned hashMisses = 0;
  
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    Record* R = Regs[i].TheDef;
    for (std::set<Record*>::iterator I = RegisterSubRegs[R].begin(),
         E = RegisterSubRegs[R].end(); I != E; ++I) {
      Record* RJ = *I;
      // We have to increase the indices of both registers by one when
      // computing the hash because, in the generated code, there
      // will be an extra empty slot at register 0.
      size_t index = ((i+1) + (RegNo[RJ]+1) * 37) & (SubregHashTableSize-1);
      unsigned ProbeAmt = 2;
      while (SubregHashTable[index*2] != ~0U &&
             SubregHashTable[index*2+1] != ~0U) {
        index = (index + ProbeAmt) & (SubregHashTableSize-1);
        ProbeAmt += 2;
        
        hashMisses++;
      }
      
      SubregHashTable[index*2] = i;
      SubregHashTable[index*2+1] = RegNo[RJ];
    }
  }
  
  OS << "\n\n  // Number of hash collisions: " << hashMisses << "\n";
  
  if (SubregHashTableSize) {
    std::string Namespace = Regs[0].TheDef->getValueAsString("Namespace");
    
    OS << "  const unsigned SubregHashTable[] = { ";
    for (unsigned i = 0; i < SubregHashTableSize - 1; ++i) {
      if (i != 0)
        // Insert spaces for nice formatting.
        OS << "                                       ";
      
      if (SubregHashTable[2*i] != ~0U) {
        OS << getQualifiedName(Regs[SubregHashTable[2*i]].TheDef) << ", "
           << getQualifiedName(Regs[SubregHashTable[2*i+1]].TheDef) << ", \n";
      } else {
        OS << Namespace << "::NoRegister, " << Namespace << "::NoRegister, \n";
      }
    }
    
    unsigned Idx = SubregHashTableSize*2-2;
    if (SubregHashTable[Idx] != ~0U) {
      OS << "                                       "
         << getQualifiedName(Regs[SubregHashTable[Idx]].TheDef) << ", "
         << getQualifiedName(Regs[SubregHashTable[Idx+1]].TheDef) << " };\n";
    } else {
      OS << Namespace << "::NoRegister, " << Namespace << "::NoRegister };\n";
    }
    
    OS << "  const unsigned SubregHashTableSize = "
       << SubregHashTableSize << ";\n";
  } else {
    OS << "  const unsigned SubregHashTable[] = { ~0U, ~0U };\n"
       << "  const unsigned SubregHashTableSize = 1;\n";
  }
  
  delete [] SubregHashTable;


  // Print the AliasHashTable, a simple quadratically probed
  // hash table for determining if a register aliases another register.
  unsigned NumAliases = 0;
  RegNo.clear();
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    RegNo[Regs[i].TheDef] = i;
    NumAliases += RegisterAliases[Regs[i].TheDef].size();
  }
  
  unsigned AliasesHashTableSize = 2 * NextPowerOf2(2 * NumAliases);
  unsigned* AliasesHashTable = new unsigned[2 * AliasesHashTableSize];
  std::fill(AliasesHashTable, AliasesHashTable + 2 * AliasesHashTableSize, ~0U);
  
  hashMisses = 0;
  
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    Record* R = Regs[i].TheDef;
    for (std::set<Record*>::iterator I = RegisterAliases[R].begin(),
         E = RegisterAliases[R].end(); I != E; ++I) {
      Record* RJ = *I;
      // We have to increase the indices of both registers by one when
      // computing the hash because, in the generated code, there
      // will be an extra empty slot at register 0.
      size_t index = ((i+1) + (RegNo[RJ]+1) * 37) & (AliasesHashTableSize-1);
      unsigned ProbeAmt = 2;
      while (AliasesHashTable[index*2] != ~0U &&
             AliasesHashTable[index*2+1] != ~0U) {
        index = (index + ProbeAmt) & (AliasesHashTableSize-1);
        ProbeAmt += 2;
        
        hashMisses++;
      }
      
      AliasesHashTable[index*2] = i;
      AliasesHashTable[index*2+1] = RegNo[RJ];
    }
  }
  
  OS << "\n\n  // Number of hash collisions: " << hashMisses << "\n";
  
  if (AliasesHashTableSize) {
    std::string Namespace = Regs[0].TheDef->getValueAsString("Namespace");
    
    OS << "  const unsigned AliasesHashTable[] = { ";
    for (unsigned i = 0; i < AliasesHashTableSize - 1; ++i) {
      if (i != 0)
        // Insert spaces for nice formatting.
        OS << "                                       ";
      
      if (AliasesHashTable[2*i] != ~0U) {
        OS << getQualifiedName(Regs[AliasesHashTable[2*i]].TheDef) << ", "
           << getQualifiedName(Regs[AliasesHashTable[2*i+1]].TheDef) << ", \n";
      } else {
        OS << Namespace << "::NoRegister, " << Namespace << "::NoRegister, \n";
      }
    }
    
    unsigned Idx = AliasesHashTableSize*2-2;
    if (AliasesHashTable[Idx] != ~0U) {
      OS << "                                       "
         << getQualifiedName(Regs[AliasesHashTable[Idx]].TheDef) << ", "
         << getQualifiedName(Regs[AliasesHashTable[Idx+1]].TheDef) << " };\n";
    } else {
      OS << Namespace << "::NoRegister, " << Namespace << "::NoRegister };\n";
    }
    
    OS << "  const unsigned AliasesHashTableSize = "
       << AliasesHashTableSize << ";\n";
  } else {
    OS << "  const unsigned AliasesHashTable[] = { ~0U, ~0U };\n"
       << "  const unsigned AliasesHashTableSize = 1;\n";
  }
  
  delete [] AliasesHashTable;

  if (!RegisterAliases.empty())
    OS << "\n\n  // Register Alias Sets...\n";

  // Emit the empty alias list
  OS << "  const unsigned Empty_AliasSet[] = { 0 };\n";
  // Loop over all of the registers which have aliases, emitting the alias list
  // to memory.
  for (std::map<Record*, std::set<Record*>, LessRecord >::iterator
         I = RegisterAliases.begin(), E = RegisterAliases.end(); I != E; ++I) {
    if (I->second.empty())
      continue;
    OS << "  const unsigned " << I->first->getName() << "_AliasSet[] = { ";
    for (std::set<Record*>::iterator ASI = I->second.begin(),
           E = I->second.end(); ASI != E; ++ASI)
      OS << getQualifiedName(*ASI) << ", ";
    OS << "0 };\n";
  }

  if (!RegisterSubRegs.empty())
    OS << "\n\n  // Register Sub-registers Sets...\n";

  // Emit the empty sub-registers list
  OS << "  const unsigned Empty_SubRegsSet[] = { 0 };\n";
  // Loop over all of the registers which have sub-registers, emitting the
  // sub-registers list to memory.
  for (std::map<Record*, std::set<Record*>, LessRecord>::iterator
         I = RegisterSubRegs.begin(), E = RegisterSubRegs.end(); I != E; ++I) {
   if (I->second.empty())
     continue;
    OS << "  const unsigned " << I->first->getName() << "_SubRegsSet[] = { ";
    std::vector<Record*> SubRegsVector;
    for (std::set<Record*>::iterator ASI = I->second.begin(),
           E = I->second.end(); ASI != E; ++ASI)
      SubRegsVector.push_back(*ASI);
    RegisterSorter RS(RegisterSubRegs);
    std::stable_sort(SubRegsVector.begin(), SubRegsVector.end(), RS);
    for (unsigned i = 0, e = SubRegsVector.size(); i != e; ++i)
      OS << getQualifiedName(SubRegsVector[i]) << ", ";
    OS << "0 };\n";
  }

  if (!RegisterSuperRegs.empty())
    OS << "\n\n  // Register Super-registers Sets...\n";

  // Emit the empty super-registers list
  OS << "  const unsigned Empty_SuperRegsSet[] = { 0 };\n";
  // Loop over all of the registers which have super-registers, emitting the
  // super-registers list to memory.
  for (std::map<Record*, std::set<Record*>, LessRecord >::iterator
         I = RegisterSuperRegs.begin(), E = RegisterSuperRegs.end(); I != E; ++I) {
    if (I->second.empty())
      continue;
    OS << "  const unsigned " << I->first->getName() << "_SuperRegsSet[] = { ";

    std::vector<Record*> SuperRegsVector;
    for (std::set<Record*>::iterator ASI = I->second.begin(),
           E = I->second.end(); ASI != E; ++ASI)
      SuperRegsVector.push_back(*ASI);
    RegisterSorter RS(RegisterSubRegs);
    std::stable_sort(SuperRegsVector.begin(), SuperRegsVector.end(), RS);
    for (unsigned i = 0, e = SuperRegsVector.size(); i != e; ++i)
      OS << getQualifiedName(SuperRegsVector[i]) << ", ";
    OS << "0 };\n";
  }

  OS<<"\n  const TargetRegisterDesc RegisterDescriptors[] = { // Descriptors\n";
  OS << "    { \"NOREG\",\t0,\t0,\t0 },\n";

  // Now that register alias and sub-registers sets have been emitted, emit the
  // register descriptors now.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister &Reg = Regs[i];
    OS << "    { \"";
    OS << Reg.getName() << "\",\t";
    if (!RegisterAliases[Reg.TheDef].empty())
      OS << Reg.getName() << "_AliasSet,\t";
    else
      OS << "Empty_AliasSet,\t";
    if (!RegisterSubRegs[Reg.TheDef].empty())
      OS << Reg.getName() << "_SubRegsSet,\t";
    else
      OS << "Empty_SubRegsSet,\t";
    if (!RegisterSuperRegs[Reg.TheDef].empty())
      OS << Reg.getName() << "_SuperRegsSet },\n";
    else
      OS << "Empty_SuperRegsSet },\n";
  }
  OS << "  };\n";      // End of register descriptors...

  // Emit SubRegIndex names, skipping 0
  const std::vector<Record*> SubRegIndices = Target.getSubRegIndices();
  OS << "\n  const char *const SubRegIndexTable[] = { \"";
  for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
    OS << SubRegIndices[i]->getName();
    if (i+1 != e)
      OS << "\", \"";
  }
  OS << "\" };\n\n";
  OS << "}\n\n";       // End of anonymous namespace...

  std::string ClassName = Target.getName() + "GenRegisterInfo";

  // Calculate the mapping of subregister+index pairs to physical registers.
  RegisterMaps RegMaps;

  // Emit the subregister + index mapping function based on the information
  // calculated above.
  OS << "unsigned " << ClassName
     << "::getSubReg(unsigned RegNo, unsigned Index) const {\n"
     << "  switch (RegNo) {\n"
     << "  default:\n    return 0;\n";
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    RegisterMaps::SubRegMap &SRM = RegMaps.inferSubRegIndices(Regs[i].TheDef);
    if (SRM.empty())
      continue;
    OS << "  case " << getQualifiedName(Regs[i].TheDef) << ":\n";
    OS << "    switch (Index) {\n";
    OS << "    default: return 0;\n";
    for (RegisterMaps::SubRegMap::const_iterator ii = SRM.begin(),
         ie = SRM.end(); ii != ie; ++ii)
      OS << "    case " << getQualifiedName(ii->first)
         << ": return " << getQualifiedName(ii->second) << ";\n";
    OS << "    };\n" << "    break;\n";
  }
  OS << "  };\n";
  OS << "  return 0;\n";
  OS << "}\n\n";

  OS << "unsigned " << ClassName
     << "::getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const {\n"
     << "  switch (RegNo) {\n"
     << "  default:\n    return 0;\n";
   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
     RegisterMaps::SubRegMap &SRM = RegMaps.SubReg[Regs[i].TheDef];
     if (SRM.empty())
       continue;
    OS << "  case " << getQualifiedName(Regs[i].TheDef) << ":\n";
    for (RegisterMaps::SubRegMap::const_iterator ii = SRM.begin(),
         ie = SRM.end(); ii != ie; ++ii)
      OS << "    if (SubRegNo == " << getQualifiedName(ii->second)
         << ")  return " << getQualifiedName(ii->first) << ";\n";
    OS << "    return 0;\n";
  }
  OS << "  };\n";
  OS << "  return 0;\n";
  OS << "}\n\n";

  // Emit composeSubRegIndices
  RegMaps.computeComposites();
  OS << "unsigned " << ClassName
     << "::composeSubRegIndices(unsigned IdxA, unsigned IdxB) const {\n"
     << "  switch (IdxA) {\n"
     << "  default:\n    return IdxB;\n";
  for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
    bool Open = false;
    for (unsigned j = 0; j != e; ++j) {
      if (Record *Comp = RegMaps.Composite.lookup(
                          std::make_pair(SubRegIndices[i], SubRegIndices[j]))) {
        if (!Open) {
          OS << "  case " << getQualifiedName(SubRegIndices[i])
             << ": switch(IdxB) {\n    default: return IdxB;\n";
          Open = true;
        }
        OS << "    case " << getQualifiedName(SubRegIndices[j])
           << ": return " << getQualifiedName(Comp) << ";\n";
      }
    }
    if (Open)
      OS << "    }\n";
  }
  OS << "  }\n}\n\n";

  // Emit the constructor of the class...
  OS << ClassName << "::" << ClassName
     << "(int CallFrameSetupOpcode, int CallFrameDestroyOpcode)\n"
     << "  : TargetRegisterInfo(RegisterDescriptors, " << Regs.size()+1
     << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n"
     << "                 SubRegIndexTable,\n"
     << "                 CallFrameSetupOpcode, CallFrameDestroyOpcode,\n"
     << "                 SubregHashTable, SubregHashTableSize,\n"
     << "                 AliasesHashTable, AliasesHashTableSize) {\n"
     << "}\n\n";

  // Collect all information about dwarf register numbers

  // First, just pull all provided information to the map
  unsigned maxLength = 0;
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    Record *Reg = Regs[i].TheDef;
    std::vector<int64_t> RegNums = Reg->getValueAsListOfInts("DwarfNumbers");
    maxLength = std::max((size_t)maxLength, RegNums.size());
    if (DwarfRegNums.count(Reg))
      errs() << "Warning: DWARF numbers for register " << getQualifiedName(Reg)
             << "specified multiple times\n";
    DwarfRegNums[Reg] = RegNums;
  }

  // Now we know maximal length of number list. Append -1's, where needed
  for (DwarfRegNumsMapTy::iterator 
       I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I)
    for (unsigned i = I->second.size(), e = maxLength; i != e; ++i)
      I->second.push_back(-1);

  // Emit information about the dwarf register numbers.
  OS << "int " << ClassName << "::getDwarfRegNumFull(unsigned RegNum, "
     << "unsigned Flavour) const {\n"
     << "  switch (Flavour) {\n"
     << "  default:\n"
     << "    assert(0 && \"Unknown DWARF flavour\");\n"
     << "    return -1;\n";
  
  for (unsigned i = 0, e = maxLength; i != e; ++i) {
    OS << "  case " << i << ":\n"
       << "    switch (RegNum) {\n"
       << "    default:\n"
       << "      assert(0 && \"Invalid RegNum\");\n"
       << "      return -1;\n";
    
    // Sort by name to get a stable order.
    

    for (DwarfRegNumsMapTy::iterator 
           I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) {
      int RegNo = I->second[i];
      if (RegNo != -2)
        OS << "    case " << getQualifiedName(I->first) << ":\n"
           << "      return " << RegNo << ";\n";
      else
        OS << "    case " << getQualifiedName(I->first) << ":\n"
           << "      assert(0 && \"Invalid register for this mode\");\n"
           << "      return -1;\n";
    }
    OS << "    };\n";
  }
    
  OS << "  };\n}\n\n";

  OS << "} // End llvm namespace \n";
}
//
// runMCDesc - Print out MC register descriptions.
//
void
RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
                               CodeGenRegBank &RegBank) {
  emitSourceFileHeader("MC Register Information", OS);

  OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
  OS << "#undef GET_REGINFO_MC_DESC\n";

  const std::vector<CodeGenRegister*> &Regs = RegBank.getRegisters();

  // The lists of sub-registers, super-registers, and overlaps all go in the
  // same array. That allows us to share suffixes.
  typedef std::vector<const CodeGenRegister*> RegVec;

  // Differentially encoded lists.
  SequenceToOffsetTable<DiffVec> DiffSeqs;
  SmallVector<DiffVec, 4> SubRegLists(Regs.size());
  SmallVector<DiffVec, 4> SuperRegLists(Regs.size());
  SmallVector<DiffVec, 4> OverlapLists(Regs.size());
  SmallVector<DiffVec, 4> RegUnitLists(Regs.size());
  SmallVector<unsigned, 4> RegUnitInitScale(Regs.size());

  // Keep track of sub-register names as well. These are not differentially
  // encoded.
  typedef SmallVector<const CodeGenSubRegIndex*, 4> SubRegIdxVec;
  SequenceToOffsetTable<SubRegIdxVec> SubRegIdxSeqs;
  SmallVector<SubRegIdxVec, 4> SubRegIdxLists(Regs.size());

  SequenceToOffsetTable<std::string> RegStrings;

  // Precompute register lists for the SequenceToOffsetTable.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister *Reg = Regs[i];

    RegStrings.add(Reg->getName());

    // Compute the ordered sub-register list.
    SetVector<const CodeGenRegister*> SR;
    Reg->addSubRegsPreOrder(SR, RegBank);
    diffEncode(SubRegLists[i], Reg->EnumValue, SR.begin(), SR.end());
    DiffSeqs.add(SubRegLists[i]);

    // Compute the corresponding sub-register indexes.
    SubRegIdxVec &SRIs = SubRegIdxLists[i];
    for (unsigned j = 0, je = SR.size(); j != je; ++j)
      SRIs.push_back(Reg->getSubRegIndex(SR[j]));
    SubRegIdxSeqs.add(SRIs);

    // Super-registers are already computed.
    const RegVec &SuperRegList = Reg->getSuperRegs();
    diffEncode(SuperRegLists[i], Reg->EnumValue,
               SuperRegList.begin(), SuperRegList.end());
    DiffSeqs.add(SuperRegLists[i]);

    // The list of overlaps doesn't need to have any particular order, and Reg
    // itself must be omitted.
    DiffVec &OverlapList = OverlapLists[i];
    CodeGenRegister::Set OSet;
    Reg->computeOverlaps(OSet, RegBank);
    OSet.erase(Reg);
    diffEncode(OverlapList, Reg->EnumValue, OSet.begin(), OSet.end());
    DiffSeqs.add(OverlapList);

    // Differentially encode the register unit list, seeded by register number.
    // First compute a scale factor that allows more diff-lists to be reused:
    //
    //   D0 -> (S0, S1)
    //   D1 -> (S2, S3)
    //
    // A scale factor of 2 allows D0 and D1 to share a diff-list. The initial
    // value for the differential decoder is the register number multiplied by
    // the scale.
    //
    // Check the neighboring registers for arithmetic progressions.
    unsigned ScaleA = ~0u, ScaleB = ~0u;
    ArrayRef<unsigned> RUs = Reg->getNativeRegUnits();
    if (i > 0 && Regs[i-1]->getNativeRegUnits().size() == RUs.size())
      ScaleB = RUs.front() - Regs[i-1]->getNativeRegUnits().front();
    if (i+1 != Regs.size() &&
        Regs[i+1]->getNativeRegUnits().size() == RUs.size())
      ScaleA = Regs[i+1]->getNativeRegUnits().front() - RUs.front();
    unsigned Scale = std::min(ScaleB, ScaleA);
    // Default the scale to 0 if it can't be encoded in 4 bits.
    if (Scale >= 16)
      Scale = 0;
    RegUnitInitScale[i] = Scale;
    DiffSeqs.add(diffEncode(RegUnitLists[i], Scale * Reg->EnumValue, RUs));
  }

  // Compute the final layout of the sequence table.
  DiffSeqs.layout();
  SubRegIdxSeqs.layout();

  OS << "namespace llvm {\n\n";

  const std::string &TargetName = Target.getName();

  // Emit the shared table of differential lists.
  OS << "extern const uint16_t " << TargetName << "RegDiffLists[] = {\n";
  DiffSeqs.emit(OS, printDiff16);
  OS << "};\n\n";

  // Emit the table of sub-register indexes.
  OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
  SubRegIdxSeqs.emit(OS, printSubRegIndex);
  OS << "};\n\n";

  // Emit the string table.
  RegStrings.layout();
  OS << "extern const char " << TargetName << "RegStrings[] = {\n";
  RegStrings.emit(OS, printChar);
  OS << "};\n\n";

  OS << "extern const MCRegisterDesc " << TargetName
     << "RegDesc[] = { // Descriptors\n";
  OS << "  { " << RegStrings.get("") << ", 0, 0, 0, 0, 0 },\n";

  // Emit the register descriptors now.
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister *Reg = Regs[i];
    OS << "  { " << RegStrings.get(Reg->getName()) << ", "
       << DiffSeqs.get(OverlapLists[i]) << ", "
       << DiffSeqs.get(SubRegLists[i]) << ", "
       << DiffSeqs.get(SuperRegLists[i]) << ", "
       << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
       << (DiffSeqs.get(RegUnitLists[i])*16 + RegUnitInitScale[i]) << " },\n";
  }
  OS << "};\n\n";      // End of register descriptors...

  // Emit the table of register unit roots. Each regunit has one or two root
  // registers.
  OS << "extern const uint16_t " << TargetName << "RegUnitRoots[][2] = {\n";
  for (unsigned i = 0, e = RegBank.getNumNativeRegUnits(); i != e; ++i) {
    ArrayRef<const CodeGenRegister*> Roots = RegBank.getRegUnit(i).getRoots();
    assert(!Roots.empty() && "All regunits must have a root register.");
    assert(Roots.size() <= 2 && "More than two roots not supported yet.");
    OS << "  { " << getQualifiedName(Roots.front()->TheDef);
    for (unsigned r = 1; r != Roots.size(); ++r)
      OS << ", " << getQualifiedName(Roots[r]->TheDef);
    OS << " },\n";
  }
  OS << "};\n\n";

  ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();

  // Loop over all of the register classes... emitting each one.
  OS << "namespace {     // Register classes...\n";

  // Emit the register enum value arrays for each RegisterClass
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];
    ArrayRef<Record*> Order = RC.getOrder();

    // Give the register class a legal C name if it's anonymous.
    std::string Name = RC.getName();

    // Emit the register list now.
    OS << "  // " << Name << " Register Class...\n"
       << "  const uint16_t " << Name
       << "[] = {\n    ";
    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
      Record *Reg = Order[i];
      OS << getQualifiedName(Reg) << ", ";
    }
    OS << "\n  };\n\n";

    OS << "  // " << Name << " Bit set.\n"
       << "  const uint8_t " << Name
       << "Bits[] = {\n    ";
    BitVectorEmitter BVE;
    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
      Record *Reg = Order[i];
      BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
    }
    BVE.print(OS);
    OS << "\n  };\n\n";

  }
  OS << "}\n\n";

  OS << "extern const MCRegisterClass " << TargetName
     << "MCRegisterClasses[] = {\n";

  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];

    // Asserts to make sure values will fit in table assuming types from
    // MCRegisterInfo.h
    assert((RC.SpillSize/8) <= 0xffff && "SpillSize too large.");
    assert((RC.SpillAlignment/8) <= 0xffff && "SpillAlignment too large.");
    assert(RC.CopyCost >= -128 && RC.CopyCost <= 127 && "Copy cost too large.");

    OS << "  { " << '\"' << RC.getName() << "\", "
       << RC.getName() << ", " << RC.getName() << "Bits, "
       << RC.getOrder().size() << ", sizeof(" << RC.getName() << "Bits), "
       << RC.getQualifiedName() + "RegClassID" << ", "
       << RC.SpillSize/8 << ", "
       << RC.SpillAlignment/8 << ", "
       << RC.CopyCost << ", "
       << RC.Allocatable << " },\n";
  }

  OS << "};\n\n";

  ArrayRef<CodeGenSubRegIndex*> SubRegIndices = RegBank.getSubRegIndices();

  EmitRegMappingTables(OS, Regs, false);

  // Emit Reg encoding table
  OS << "extern const uint16_t " << TargetName;
  OS << "RegEncodingTable[] = {\n";
  // Add entry for NoRegister
  OS << "  0,\n";
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    Record *Reg = Regs[i]->TheDef;
    BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
    uint64_t Value = 0;
    for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
      if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(b)))
      Value |= (uint64_t)B->getValue() << b;
    }
    OS << "  " << Value << ",\n";
  }
  OS << "};\n";       // End of HW encoding table

  // MCRegisterInfo initialization routine.
  OS << "static inline void Init" << TargetName
     << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
     << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0) {\n"
     << "  RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
     << Regs.size()+1 << ", RA, " << TargetName << "MCRegisterClasses, "
     << RegisterClasses.size() << ", "
     << TargetName << "RegUnitRoots, "
     << RegBank.getNumNativeRegUnits() << ", "
     << TargetName << "RegDiffLists, "
     << TargetName << "RegStrings, "
     << TargetName << "SubRegIdxLists, "
     << SubRegIndices.size() << ",\n"
     << "  " << TargetName << "RegEncodingTable);\n\n";

  EmitRegMapping(OS, Regs, false);

  OS << "}\n\n";

  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_MC_DESC\n\n";
}
/// Generate a table and function for looking up the indices of operands by
/// name.
///
/// This code generates:
/// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
///   for each operand name.
/// - A 2-dimensional table called OperandMap for mapping OpName enum values to
///   operand indices.
/// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
///   for looking up the operand index for an instruction, given a value from
///   OpName enum
void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
           const CodeGenTarget &Target,
           const std::vector<const CodeGenInstruction*> &NumberedInstructions) {

  const std::string &Namespace = Target.getInstNamespace();
  std::string OpNameNS = "OpName";
  // Map of operand names to their enumeration value.  This will be used to
  // generate the OpName enum.
  std::map<std::string, unsigned> Operands;
  OpNameMapTy OperandMap;

  initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);

  OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
  OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
  OS << "namespace llvm {";
  OS << "namespace " << Namespace << " {\n";
  OS << "namespace " << OpNameNS << " { \n";
  OS << "enum {\n";
  for (StrUintMapIter i = Operands.begin(), e = Operands.end(); i != e; ++i)
    OS << "  " << i->first << " = " << i->second << ",\n";

  OS << "OPERAND_LAST";
  OS << "\n};\n";
  OS << "} // End namespace OpName\n";
  OS << "} // End namespace " << Namespace << "\n";
  OS << "} // End namespace llvm\n";
  OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n";

  OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
  OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
  OS << "namespace llvm {";
  OS << "namespace " << Namespace << " {\n";
  OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
  OS << "  static const int16_t OperandMap []["<< Operands.size() << "] = {\n";
  for (OpNameMapTy::iterator i = OperandMap.begin(), e = OperandMap.end();
                                                     i != e; ++i) {
    const std::map<unsigned, unsigned> &OpList = i->first;
    OS << "{";

    // Emit a row of the OperandMap table
    for (unsigned ii = 0, ie = Operands.size(); ii != ie; ++ii)
      OS << (OpList.count(ii) == 0 ? -1 : (int)OpList.find(ii)->second) << ", ";

    OS << "},\n";
  }
  OS << "};\n";

  OS << "  switch(Opcode) {\n";
  unsigned TableIndex = 0;
  for (OpNameMapTy::iterator i = OperandMap.begin(), e = OperandMap.end();
                                                     i != e; ++i) {
    std::vector<std::string> &OpcodeList = i->second;

    for (unsigned ii = 0, ie = OpcodeList.size(); ii != ie; ++ii)
      OS << "  case " << OpcodeList[ii] << ":\n";

    OS << "    return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
  }
  OS << "    default: return -1;\n";
  OS << "  }\n";
  OS << "}\n";
  OS << "} // End namespace " << Namespace << "\n";
  OS << "} // End namespace llvm\n";
  OS << "#endif //GET_INSTRINFO_NAMED_OPS\n";

}
Beispiel #24
0
void CodeEmitterGen::run(raw_ostream &o) {
  CodeGenTarget Target;
  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
  
  // For little-endian instruction bit encodings, reverse the bit order
  if (Target.isLittleEndianEncoding()) reverseBits(Insts);

  EmitSourceFileHeader("Machine Code Emitter", o);
  std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
  
  std::vector<const CodeGenInstruction*> NumberedInstructions;
  Target.getInstructionsByEnumValue(NumberedInstructions);

  // Emit function declaration
  o << "unsigned " << Target.getName() << "CodeEmitter::"
    << "getBinaryCodeForInstr(const MachineInstr &MI) {\n";

  // Emit instruction base values
  o << "  static const unsigned InstBits[] = {\n";
  for (std::vector<const CodeGenInstruction*>::iterator
          IN = NumberedInstructions.begin(),
          EN = NumberedInstructions.end();
       IN != EN; ++IN) {
    const CodeGenInstruction *CGI = *IN;
    Record *R = CGI->TheDef;
    
    if (R->getName() == "PHI" ||
        R->getName() == "INLINEASM" ||
        R->getName() == "DBG_LABEL" ||
        R->getName() == "EH_LABEL" ||
        R->getName() == "GC_LABEL" ||
        R->getName() == "KILL" ||
        R->getName() == "EXTRACT_SUBREG" ||
        R->getName() == "INSERT_SUBREG" ||
        R->getName() == "IMPLICIT_DEF" ||
        R->getName() == "SUBREG_TO_REG" ||
        R->getName() == "COPY_TO_REGCLASS") {
      o << "    0U,\n";
      continue;
    }
    
    BitsInit *BI = R->getValueAsBitsInit("Inst");

    // Start by filling in fixed values...
    unsigned Value = 0;
    for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
      if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
        Value |= B->getValue() << (e-i-1);
      }
    }
    o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
  }
  o << "    0U\n  };\n";
  
  // Map to accumulate all the cases.
  std::map<std::string, std::vector<std::string> > CaseMap;
  
  // Construct all cases statement for each opcode
  for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
        IC != EC; ++IC) {
    Record *R = *IC;
    const std::string &InstName = R->getName();
    std::string Case("");
    
    if (InstName == "PHI" ||
        InstName == "INLINEASM" ||
        InstName == "DBG_LABEL"||
        InstName == "EH_LABEL"||
        InstName == "GC_LABEL"||
        InstName == "KILL"||
        InstName == "EXTRACT_SUBREG" ||
        InstName == "INSERT_SUBREG" ||
        InstName == "IMPLICIT_DEF" ||
        InstName == "SUBREG_TO_REG" ||
        InstName == "COPY_TO_REGCLASS") continue;

    BitsInit *BI = R->getValueAsBitsInit("Inst");
    const std::vector<RecordVal> &Vals = R->getValues();
    CodeGenInstruction &CGI = Target.getInstruction(InstName);
    
    // Loop over all of the fields in the instruction, determining which are the
    // operands to the instruction.
    unsigned op = 0;
    for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
      if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
        // Is the operand continuous? If so, we can just mask and OR it in
        // instead of doing it bit-by-bit, saving a lot in runtime cost.
        const std::string &VarName = Vals[i].getName();
        bool gotOp = false;
        
        for (int bit = BI->getNumBits()-1; bit >= 0; ) {
          int varBit = getVariableBit(VarName, BI, bit);
          
          if (varBit == -1) {
            --bit;
          } else {
            int beginInstBit = bit;
            int beginVarBit = varBit;
            int N = 1;
            
            for (--bit; bit >= 0;) {
              varBit = getVariableBit(VarName, BI, bit);
              if (varBit == -1 || varBit != (beginVarBit - N)) break;
              ++N;
              --bit;
            }

            if (!gotOp) {
              /// If this operand is not supposed to be emitted by the generated
              /// emitter, skip it.
              while (CGI.isFlatOperandNotEmitted(op))
                ++op;
              
              Case += "      // op: " + VarName + "\n"
                   +  "      op = getMachineOpValue(MI, MI.getOperand("
                   +  utostr(op++) + "));\n";
              gotOp = true;
            }
            
            unsigned opMask = ~0U >> (32-N);
            int opShift = beginVarBit - N + 1;
            opMask <<= opShift;
            opShift = beginInstBit - beginVarBit;
            
            if (opShift > 0) {
              Case += "      Value |= (op & " + utostr(opMask) + "U) << "
                   +  itostr(opShift) + ";\n";
            } else if (opShift < 0) {
              Case += "      Value |= (op & " + utostr(opMask) + "U) >> "
                   +  itostr(-opShift) + ";\n";
            } else {
              Case += "      Value |= op & " + utostr(opMask) + "U;\n";
            }
          }
        }
      }
    }

    std::vector<std::string> &InstList = CaseMap[Case];
    InstList.push_back(InstName);
  }


  // Emit initial function code
  o << "  const unsigned opcode = MI.getOpcode();\n"
    << "  unsigned Value = InstBits[opcode];\n"
    << "  unsigned op = 0;\n"
    << "  op = op;  // suppress warning\n"
    << "  switch (opcode) {\n";

  // Emit each case statement
  std::map<std::string, std::vector<std::string> >::iterator IE, EE;
  for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
    const std::string &Case = IE->first;
    std::vector<std::string> &InstList = IE->second;

    for (int i = 0, N = InstList.size(); i < N; i++) {
      if (i) o << "\n";
      o << "    case " << Namespace << InstList[i]  << ":";
    }
    o << " {\n";
    o << Case;
    o << "      break;\n"
      << "    }\n";
  }

  // Default case: unhandled opcode
  o << "  default:\n"
    << "    std::string msg;\n"
    << "    raw_string_ostream Msg(msg);\n"
    << "    Msg << \"Not supported instr: \" << MI;\n"
    << "    llvm_report_error(Msg.str());\n"
    << "  }\n"
    << "  return Value;\n"
    << "}\n\n";
}
Beispiel #25
0
// runEnums - Print out enum values for all of the registers.
void RegisterInfoEmitter::runEnums(raw_ostream &OS,
                                   CodeGenTarget &Target, CodeGenRegBank &Bank) {
  const std::vector<CodeGenRegister*> &Registers = Bank.getRegisters();

  // Register enums are stored as uint16_t in the tables. Make sure we'll fit.
  assert(Registers.size() <= 0xffff && "Too many regs to fit in tables");

  std::string Namespace = Registers[0]->TheDef->getValueAsString("Namespace");

  EmitSourceFileHeader("Target Register Enum Values", OS);

  OS << "\n#ifdef GET_REGINFO_ENUM\n";
  OS << "#undef GET_REGINFO_ENUM\n";

  OS << "namespace llvm {\n\n";

  OS << "class MCRegisterClass;\n"
     << "extern const MCRegisterClass " << Namespace
     << "MCRegisterClasses[];\n\n";

  if (!Namespace.empty())
    OS << "namespace " << Namespace << " {\n";
  OS << "enum {\n  NoRegister,\n";

  for (unsigned i = 0, e = Registers.size(); i != e; ++i)
    OS << "  " << Registers[i]->getName() << " = " <<
      Registers[i]->EnumValue << ",\n";
  assert(Registers.size() == Registers[Registers.size()-1]->EnumValue &&
         "Register enum value mismatch!");
  OS << "  NUM_TARGET_REGS \t// " << Registers.size()+1 << "\n";
  OS << "};\n";
  if (!Namespace.empty())
    OS << "}\n";

  ArrayRef<CodeGenRegisterClass*> RegisterClasses = Bank.getRegClasses();
  if (!RegisterClasses.empty()) {

    // RegisterClass enums are stored as uint16_t in the tables.
    assert(RegisterClasses.size() <= 0xffff &&
           "Too many register classes to fit in tables");

    OS << "\n// Register classes\n";
    if (!Namespace.empty())
      OS << "namespace " << Namespace << " {\n";
    OS << "enum {\n";
    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
      if (i) OS << ",\n";
      OS << "  " << RegisterClasses[i]->getName() << "RegClassID";
      OS << " = " << i;
    }
    OS << "\n  };\n";
    if (!Namespace.empty())
      OS << "}\n";
  }

  const std::vector<Record*> RegAltNameIndices = Target.getRegAltNameIndices();
  // If the only definition is the default NoRegAltName, we don't need to
  // emit anything.
  if (RegAltNameIndices.size() > 1) {
    OS << "\n// Register alternate name indices\n";
    if (!Namespace.empty())
      OS << "namespace " << Namespace << " {\n";
    OS << "enum {\n";
    for (unsigned i = 0, e = RegAltNameIndices.size(); i != e; ++i)
      OS << "  " << RegAltNameIndices[i]->getName() << ",\t// " << i << "\n";
    OS << "  NUM_TARGET_REG_ALT_NAMES = " << RegAltNameIndices.size() << "\n";
    OS << "};\n";
    if (!Namespace.empty())
      OS << "}\n";
  }

  ArrayRef<CodeGenSubRegIndex*> SubRegIndices = Bank.getSubRegIndices();
  if (!SubRegIndices.empty()) {
    OS << "\n// Subregister indices\n";
    std::string Namespace =
      SubRegIndices[0]->getNamespace();
    if (!Namespace.empty())
      OS << "namespace " << Namespace << " {\n";
    OS << "enum {\n  NoSubRegister,\n";
    for (unsigned i = 0, e = Bank.getNumNamedIndices(); i != e; ++i)
      OS << "  " << SubRegIndices[i]->getName() << ",\t// " << i+1 << "\n";
    OS << "  NUM_TARGET_NAMED_SUBREGS\n};\n";
    if (!Namespace.empty())
      OS << "}\n";
  }

  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_ENUM\n\n";
}
Beispiel #26
0
/// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
/// constructor.  It checks if an argument in an InstAlias pattern matches
/// the corresponding operand of the instruction.  It returns true on a
/// successful match, with ResOp set to the result operand to be used.
bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
                                       Record *InstOpRec, bool hasSubOps,
                                       ArrayRef<SMLoc> Loc, CodeGenTarget &T,
                                       ResultOperand &ResOp) {
    Init *Arg = Result->getArg(AliasOpNo);
    DefInit *ADI = dyn_cast<DefInit>(Arg);
    Record *ResultRecord = ADI ? ADI->getDef() : nullptr;

    if (ADI && ADI->getDef() == InstOpRec) {
        // If the operand is a record, it must have a name, and the record type
        // must match up with the instruction's argument type.
        if (Result->getArgName(AliasOpNo).empty())
            PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
                            " must have a name!");
        ResOp = ResultOperand(Result->getArgName(AliasOpNo), ResultRecord);
        return true;
    }

    // For register operands, the source register class can be a subclass
    // of the instruction register class, not just an exact match.
    if (InstOpRec->isSubClassOf("RegisterOperand"))
        InstOpRec = InstOpRec->getValueAsDef("RegClass");

    if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
        ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();

    if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
        if (!InstOpRec->isSubClassOf("RegisterClass"))
            return false;
        if (!T.getRegisterClass(InstOpRec)
                .hasSubClass(&T.getRegisterClass(ADI->getDef())))
            return false;
        ResOp = ResultOperand(Result->getArgName(AliasOpNo), ResultRecord);
        return true;
    }

    // Handle explicit registers.
    if (ADI && ADI->getDef()->isSubClassOf("Register")) {
        if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
            DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
            // The operand info should only have a single (register) entry. We
            // want the register class of it.
            InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
        }

        if (!InstOpRec->isSubClassOf("RegisterClass"))
            return false;

        if (!T.getRegisterClass(InstOpRec)
                .contains(T.getRegBank().getReg(ADI->getDef())))
            PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
                            " is not a member of the " + InstOpRec->getName() +
                            " register class!");

        if (!Result->getArgName(AliasOpNo).empty())
            PrintFatalError(Loc, "result fixed register argument must "
                            "not have a name!");

        ResOp = ResultOperand(ResultRecord);
        return true;
    }

    // Handle "zero_reg" for optional def operands.
    if (ADI && ADI->getDef()->getName() == "zero_reg") {

        // Check if this is an optional def.
        // Tied operands where the source is a sub-operand of a complex operand
        // need to represent both operands in the alias destination instruction.
        // Allow zero_reg for the tied portion. This can and should go away once
        // the MC representation of things doesn't use tied operands at all.
        //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
        //  throw TGError(Loc, "reg0 used for result that is not an "
        //                "OptionalDefOperand!");

        ResOp = ResultOperand(static_cast<Record*>(nullptr));
        return true;
    }

    // Literal integers.
    if (IntInit *II = dyn_cast<IntInit>(Arg)) {
        if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
            return false;
        // Integer arguments can't have names.
        if (!Result->getArgName(AliasOpNo).empty())
            PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
                            " must not have a name!");
        ResOp = ResultOperand(II->getValue());
        return true;
    }

    // If both are Operands with the same MVT, allow the conversion. It's
    // up to the user to make sure the values are appropriate, just like
    // for isel Pat's.
    if (InstOpRec->isSubClassOf("Operand") &&
            ADI->getDef()->isSubClassOf("Operand")) {
        // FIXME: What other attributes should we check here? Identical
        // MIOperandInfo perhaps?
        if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
            return false;
        ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
        return true;
    }

    return false;
}
Beispiel #27
0
//
// runTargetDesc - Output the target register and register file descriptions.
//
void
RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target,
                                   CodeGenRegBank &RegBank){
  EmitSourceFileHeader("Target Register and Register Classes Information", OS);

  OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
  OS << "#undef GET_REGINFO_TARGET_DESC\n";

  OS << "namespace llvm {\n\n";

  // Get access to MCRegisterClass data.
  OS << "extern const MCRegisterClass " << Target.getName()
     << "MCRegisterClasses[];\n";

  // Start out by emitting each of the register classes.
  ArrayRef<CodeGenRegisterClass*> RegisterClasses = RegBank.getRegClasses();
  ArrayRef<CodeGenSubRegIndex*> SubRegIndices = RegBank.getSubRegIndices();

  // Collect all registers belonging to any allocatable class.
  std::set<Record*> AllocatableRegs;

  // Collect allocatable registers.
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
    const CodeGenRegisterClass &RC = *RegisterClasses[rc];
    ArrayRef<Record*> Order = RC.getOrder();

    if (RC.Allocatable)
      AllocatableRegs.insert(Order.begin(), Order.end());
  }

  // Build a shared array of value types.
  SequenceToOffsetTable<std::vector<MVT::SimpleValueType> > VTSeqs;
  for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc)
    VTSeqs.add(RegisterClasses[rc]->VTs);
  VTSeqs.layout();
  OS << "\nstatic const MVT::SimpleValueType VTLists[] = {\n";
  VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
  OS << "};\n";

  // Emit SubRegIndex names, skipping 0
  OS << "\nstatic const char *const SubRegIndexTable[] = { \"";
  for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
    OS << SubRegIndices[i]->getName();
    if (i+1 != e)
      OS << "\", \"";
  }
  OS << "\" };\n\n";

  // Emit names of the anonymous subreg indices.
  unsigned NamedIndices = RegBank.getNumNamedIndices();
  if (SubRegIndices.size() > NamedIndices) {
    OS << "  enum {";
    for (unsigned i = NamedIndices, e = SubRegIndices.size(); i != e; ++i) {
      OS << "\n    " << SubRegIndices[i]->getName() << " = " << i+1;
      if (i+1 != e)
        OS << ',';
    }
    OS << "\n  };\n\n";
  }
  OS << "\n";

  // Now that all of the structs have been emitted, emit the instances.
  if (!RegisterClasses.empty()) {
    OS << "\nstatic const TargetRegisterClass *const "
       << "NullRegClasses[] = { NULL };\n\n";

    // Emit register class bit mask tables. The first bit mask emitted for a
    // register class, RC, is the set of sub-classes, including RC itself.
    //
    // If RC has super-registers, also create a list of subreg indices and bit
    // masks, (Idx, Mask). The bit mask has a bit for every superreg regclass,
    // SuperRC, that satisfies:
    //
    //   For all SuperReg in SuperRC: SuperReg:Idx in RC
    //
    // The 0-terminated list of subreg indices starts at:
    //
    //   RC->getSuperRegIndices() = SuperRegIdxSeqs + ...
    //
    // The corresponding bitmasks follow the sub-class mask in memory. Each
    // mask has RCMaskWords uint32_t entries.
    //
    // Every bit mask present in the list has at least one bit set.

    // Compress the sub-reg index lists.
    typedef std::vector<const CodeGenSubRegIndex*> IdxList;
    SmallVector<IdxList, 8> SuperRegIdxLists(RegisterClasses.size());
    SequenceToOffsetTable<IdxList> SuperRegIdxSeqs;
    BitVector MaskBV(RegisterClasses.size());

    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
      const CodeGenRegisterClass &RC = *RegisterClasses[rc];
      OS << "static const uint32_t " << RC.getName() << "SubClassMask[] = {\n  ";
      printBitVectorAsHex(OS, RC.getSubClasses(), 32);

      // Emit super-reg class masks for any relevant SubRegIndices that can
      // project into RC.
      IdxList &SRIList = SuperRegIdxLists[rc];
      for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
        CodeGenSubRegIndex *Idx = SubRegIndices[sri];
        MaskBV.reset();
        RC.getSuperRegClasses(Idx, MaskBV);
        if (MaskBV.none())
          continue;
        SRIList.push_back(Idx);
        OS << "\n  ";
        printBitVectorAsHex(OS, MaskBV, 32);
        OS << "// " << Idx->getName();
      }
      SuperRegIdxSeqs.add(SRIList);
      OS << "\n};\n\n";
    }

    OS << "static const uint16_t SuperRegIdxSeqs[] = {\n";
    SuperRegIdxSeqs.layout();
    SuperRegIdxSeqs.emit(OS, printSubRegIndex);
    OS << "};\n\n";

    // Emit NULL terminated super-class lists.
    for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) {
      const CodeGenRegisterClass &RC = *RegisterClasses[rc];
      ArrayRef<CodeGenRegisterClass*> Supers = RC.getSuperClasses();

      // Skip classes without supers.  We can reuse NullRegClasses.
      if (Supers.empty())
        continue;

      OS << "static const TargetRegisterClass *const "
         << RC.getName() << "Superclasses[] = {\n";
      for (unsigned i = 0; i != Supers.size(); ++i)
        OS << "  &" << Supers[i]->getQualifiedName() << "RegClass,\n";
      OS << "  NULL\n};\n\n";
    }

    // Emit methods.
    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
      const CodeGenRegisterClass &RC = *RegisterClasses[i];
      if (!RC.AltOrderSelect.empty()) {
        OS << "\nstatic inline unsigned " << RC.getName()
           << "AltOrderSelect(const MachineFunction &MF) {"
           << RC.AltOrderSelect << "}\n\n"
           << "static ArrayRef<uint16_t> " << RC.getName()
           << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
        for (unsigned oi = 1 , oe = RC.getNumOrders(); oi != oe; ++oi) {
          ArrayRef<Record*> Elems = RC.getOrder(oi);
          if (!Elems.empty()) {
            OS << "  static const uint16_t AltOrder" << oi << "[] = {";
            for (unsigned elem = 0; elem != Elems.size(); ++elem)
              OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
            OS << " };\n";
          }
        }
        OS << "  const MCRegisterClass &MCR = " << Target.getName()
           << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];\n"
           << "  const ArrayRef<uint16_t> Order[] = {\n"
           << "    makeArrayRef(MCR.begin(), MCR.getNumRegs()";
        for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
          if (RC.getOrder(oi).empty())
            OS << "),\n    ArrayRef<uint16_t>(";
          else
            OS << "),\n    makeArrayRef(AltOrder" << oi;
        OS << ")\n  };\n  const unsigned Select = " << RC.getName()
           << "AltOrderSelect(MF);\n  assert(Select < " << RC.getNumOrders()
           << ");\n  return Order[Select];\n}\n";
        }
    }

    // Now emit the actual value-initialized register class instances.
    OS << "namespace " << RegisterClasses[0]->Namespace
       << " {   // Register class instances\n";

    for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
      const CodeGenRegisterClass &RC = *RegisterClasses[i];
      OS << "  extern const TargetRegisterClass "
         << RegisterClasses[i]->getName() << "RegClass = {\n    "
         << '&' << Target.getName() << "MCRegisterClasses[" << RC.getName()
         << "RegClassID],\n    "
         << "VTLists + " << VTSeqs.get(RC.VTs) << ",\n    "
         << RC.getName() << "SubClassMask,\n    SuperRegIdxSeqs + "
         << SuperRegIdxSeqs.get(SuperRegIdxLists[i]) << ",\n    ";
      if (RC.getSuperClasses().empty())
        OS << "NullRegClasses,\n    ";
      else
        OS << RC.getName() << "Superclasses,\n    ";
      if (RC.AltOrderSelect.empty())
        OS << "0\n";
      else
        OS << RC.getName() << "GetRawAllocationOrder\n";
      OS << "  };\n\n";
    }

    OS << "}\n";
  }

  OS << "\nnamespace {\n";
  OS << "  const TargetRegisterClass* const RegisterClasses[] = {\n";
  for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i)
    OS << "    &" << RegisterClasses[i]->getQualifiedName()
       << "RegClass,\n";
  OS << "  };\n";
  OS << "}\n";       // End of anonymous namespace...

  // Emit extra information about registers.
  const std::string &TargetName = Target.getName();
  OS << "\nstatic const TargetRegisterInfoDesc "
     << TargetName << "RegInfoDesc[] = { // Extra Descriptors\n";
  OS << "  { 0, 0 },\n";

  const std::vector<CodeGenRegister*> &Regs = RegBank.getRegisters();
  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
    const CodeGenRegister &Reg = *Regs[i];
    OS << "  { ";
    OS << Reg.CostPerUse << ", "
       << int(AllocatableRegs.count(Reg.TheDef)) << " },\n";
  }
  OS << "};\n";      // End of register descriptors...


  std::string ClassName = Target.getName() + "GenRegisterInfo";

  // Emit composeSubRegIndices
  if (!SubRegIndices.empty()) {
    OS << "unsigned " << ClassName
      << "::composeSubRegIndices(unsigned IdxA, unsigned IdxB) const {\n"
      << "  switch (IdxA) {\n"
      << "  default:\n    return IdxB;\n";
    for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
      bool Open = false;
      for (unsigned j = 0; j != e; ++j) {
        if (CodeGenSubRegIndex *Comp =
            SubRegIndices[i]->compose(SubRegIndices[j])) {
          if (!Open) {
            OS << "  case " << SubRegIndices[i]->getQualifiedName()
              << ": switch(IdxB) {\n    default: return IdxB;\n";
            Open = true;
          }
          OS << "    case " << SubRegIndices[j]->getQualifiedName()
            << ": return " << Comp->getQualifiedName() << ";\n";
        }
      }
      if (Open)
        OS << "    }\n";
    }
    OS << "  }\n}\n\n";
  }

  // Emit getSubClassWithSubReg.
  if (!SubRegIndices.empty()) {
    OS << "const TargetRegisterClass *" << ClassName
       << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
       << " const {\n";
    // Use the smallest type that can hold a regclass ID with room for a
    // sentinel.
    if (RegisterClasses.size() < UINT8_MAX)
      OS << "  static const uint8_t Table[";
    else if (RegisterClasses.size() < UINT16_MAX)
      OS << "  static const uint16_t Table[";
    else
      throw "Too many register classes.";
    OS << RegisterClasses.size() << "][" << SubRegIndices.size() << "] = {\n";
    for (unsigned rci = 0, rce = RegisterClasses.size(); rci != rce; ++rci) {
      const CodeGenRegisterClass &RC = *RegisterClasses[rci];
      OS << "    {\t// " << RC.getName() << "\n";
      for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
        CodeGenSubRegIndex *Idx = SubRegIndices[sri];
        if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(Idx))
          OS << "      " << SRC->EnumValue + 1 << ",\t// " << Idx->getName()
             << " -> " << SRC->getName() << "\n";
        else
          OS << "      0,\t// " << Idx->getName() << "\n";
      }
      OS << "    },\n";
    }
    OS << "  };\n  assert(RC && \"Missing regclass\");\n"
       << "  if (!Idx) return RC;\n  --Idx;\n"
       << "  assert(Idx < " << SubRegIndices.size() << " && \"Bad subreg\");\n"
       << "  unsigned TV = Table[RC->getID()][Idx];\n"
       << "  return TV ? getRegClass(TV - 1) : 0;\n}\n\n";
  }

  EmitRegUnitPressure(OS, RegBank, ClassName);

  // Emit the constructor of the class...
  OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
  OS << "extern const uint16_t " << TargetName << "RegLists[];\n";
  if (SubRegIndices.size() != 0)
    OS << "extern const uint16_t *get" << TargetName
       << "SubRegTable();\n";
  OS << "extern const uint16_t " << TargetName << "RegEncodingTable[];\n";

  EmitRegMappingTables(OS, Regs, true);

  OS << ClassName << "::\n" << ClassName
     << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour)\n"
     << "  : TargetRegisterInfo(" << TargetName << "RegInfoDesc"
     << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n"
     << "             SubRegIndexTable) {\n"
     << "  InitMCRegisterInfo(" << TargetName << "RegDesc, "
     << Regs.size()+1 << ", RA,\n                     " << TargetName
     << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
     << "                     " << TargetName << "RegLists,\n"
     << "                     ";
  if (SubRegIndices.size() != 0)
    OS << "get" << TargetName << "SubRegTable(), "
       << SubRegIndices.size() << ",\n";
  else
    OS << "NULL, 0,\n";

  OS << "                     " << TargetName << "RegEncodingTable);\n\n";

  EmitRegMapping(OS, Regs, true);

  OS << "}\n\n";


  // Emit CalleeSavedRegs information.
  std::vector<Record*> CSRSets =
    Records.getAllDerivedDefinitions("CalleeSavedRegs");
  for (unsigned i = 0, e = CSRSets.size(); i != e; ++i) {
    Record *CSRSet = CSRSets[i];
    const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
    assert(Regs && "Cannot expand CalleeSavedRegs instance");

    // Emit the *_SaveList list of callee-saved registers.
    OS << "static const uint16_t " << CSRSet->getName()
       << "_SaveList[] = { ";
    for (unsigned r = 0, re = Regs->size(); r != re; ++r)
      OS << getQualifiedName((*Regs)[r]) << ", ";
    OS << "0 };\n";

    // Emit the *_RegMask bit mask of call-preserved registers.
    OS << "static const uint32_t " << CSRSet->getName()
       << "_RegMask[] = { ";
    printBitVectorAsHex(OS, RegBank.computeCoveredRegisters(*Regs), 32);
    OS << "};\n";
  }
  OS << "\n\n";

  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
}
Beispiel #28
0
CodeGenInstAlias::CodeGenInstAlias(Record *R, unsigned Variant,
                                   CodeGenTarget &T)
    : TheDef(R) {
    Result = R->getValueAsDag("ResultInst");
    AsmString = R->getValueAsString("AsmString");
    AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, Variant);


    // Verify that the root of the result is an instruction.
    DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
    if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
        PrintFatalError(R->getLoc(),
                        "result of inst alias should be an instruction");

    ResultInst = &T.getInstruction(DI->getDef());

    // NameClass - If argument names are repeated, we need to verify they have
    // the same class.
    StringMap<Record*> NameClass;
    for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
        DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
        if (!ADI || Result->getArgName(i).empty())
            continue;
        // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
        // $foo can exist multiple times in the result list, but it must have the
        // same type.
        Record *&Entry = NameClass[Result->getArgName(i)];
        if (Entry && Entry != ADI->getDef())
            PrintFatalError(R->getLoc(), "result value $" + Result->getArgName(i) +
                            " is both " + Entry->getName() + " and " +
                            ADI->getDef()->getName() + "!");
        Entry = ADI->getDef();
    }

    // Decode and validate the arguments of the result.
    unsigned AliasOpNo = 0;
    for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {

        // Tied registers don't have an entry in the result dag unless they're part
        // of a complex operand, in which case we include them anyways, as we
        // don't have any other way to specify the whole operand.
        if (ResultInst->Operands[i].MINumOperands == 1 &&
                ResultInst->Operands[i].getTiedRegister() != -1)
            continue;

        if (AliasOpNo >= Result->getNumArgs())
            PrintFatalError(R->getLoc(), "not enough arguments for instruction!");

        Record *InstOpRec = ResultInst->Operands[i].Rec;
        unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
        ResultOperand ResOp(static_cast<int64_t>(0));
        if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
                            R->getLoc(), T, ResOp)) {
            // If this is a simple operand, or a complex operand with a custom match
            // class, then we can match is verbatim.
            if (NumSubOps == 1 ||
                    (InstOpRec->getValue("ParserMatchClass") &&
                     InstOpRec->getValueAsDef("ParserMatchClass")
                     ->getValueAsString("Name") != "Imm")) {
                ResultOperands.push_back(ResOp);
                ResultInstOperandIndex.push_back(std::make_pair(i, -1));
                ++AliasOpNo;

                // Otherwise, we need to match each of the suboperands individually.
            } else {
                DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
                for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
                    Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();

                    // Take care to instantiate each of the suboperands with the correct
                    // nomenclature: $foo.bar
                    ResultOperands.push_back(
                        ResultOperand(Result->getArgName(AliasOpNo) + "." +
                                      MIOI->getArgName(SubOp), SubRec));
                    ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
                }
                ++AliasOpNo;
            }
            continue;
        }

        // If the argument did not match the instruction operand, and the operand
        // is composed of multiple suboperands, try matching the suboperands.
        if (NumSubOps > 1) {
            DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
            for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
                if (AliasOpNo >= Result->getNumArgs())
                    PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
                Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
                if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
                                    R->getLoc(), T, ResOp)) {
                    ResultOperands.push_back(ResOp);
                    ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
                    ++AliasOpNo;
                } else {
                    PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
                                    " does not match instruction operand class " +
                                    (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
                }
            }
            continue;
        }
        PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
                        " does not match instruction operand class " +
                        InstOpRec->getName());
    }

    if (AliasOpNo != Result->getNumArgs())
        PrintFatalError(R->getLoc(), "too many operands for instruction!");
}
Beispiel #29
0
/// populateInstInfo - Fills an array of InstInfos with information about each
///   instruction in a target
///
/// \param infoArray The array of InstInfo objects to populate
/// \param target    The CodeGenTarget to use as a source of instructions
static void populateInstInfo(CompoundConstantEmitter &infoArray,
                             CodeGenTarget &target) {
  const std::vector<const CodeGenInstruction*> &numberedInstructions =
    target.getInstructionsByEnumValue();

  unsigned int index;
  unsigned int numInstructions = numberedInstructions.size();

  for (index = 0; index < numInstructions; ++index) {
    const CodeGenInstruction& inst = *numberedInstructions[index];

    CompoundConstantEmitter *infoStruct = new CompoundConstantEmitter;
    infoArray.addEntry(infoStruct);

    LiteralConstantEmitter *instType = new LiteralConstantEmitter;
    infoStruct->addEntry(instType);

    LiteralConstantEmitter *numOperandsEmitter =
      new LiteralConstantEmitter(inst.Operands.size());
    infoStruct->addEntry(numOperandsEmitter);

    CompoundConstantEmitter *operandTypeArray = new CompoundConstantEmitter;
    infoStruct->addEntry(operandTypeArray);

    LiteralConstantEmitter *operandTypes[EDIS_MAX_OPERANDS];

    CompoundConstantEmitter *operandFlagArray = new CompoundConstantEmitter;
    infoStruct->addEntry(operandFlagArray);

    FlagsConstantEmitter *operandFlags[EDIS_MAX_OPERANDS];

    for (unsigned operandIndex = 0;
         operandIndex < EDIS_MAX_OPERANDS;
         ++operandIndex) {
      operandTypes[operandIndex] = new LiteralConstantEmitter;
      operandTypeArray->addEntry(operandTypes[operandIndex]);

      operandFlags[operandIndex] = new FlagsConstantEmitter;
      operandFlagArray->addEntry(operandFlags[operandIndex]);
    }

    unsigned numSyntaxes = 0;

    // We don't need to do anything for pseudo-instructions, as we'll never
    // see them here. We'll only see real instructions.
    // We still need to emit null initializers for everything.
    if (!inst.isPseudo) {
      if (target.getName() == "X86") {
        X86PopulateOperands(operandTypes, inst);
        X86ExtractSemantics(*instType, operandFlags, inst);
        numSyntaxes = 2;
      }
      else if (target.getName() == "ARM") {
        ARMPopulateOperands(operandTypes, inst);
        ARMExtractSemantics(*instType, operandTypes, operandFlags, inst);
        numSyntaxes = 1;
      }
    }

    CompoundConstantEmitter *operandOrderArray = new CompoundConstantEmitter;

    infoStruct->addEntry(operandOrderArray);

    for (unsigned syntaxIndex = 0;
         syntaxIndex < EDIS_MAX_SYNTAXES;
         ++syntaxIndex) {
      CompoundConstantEmitter *operandOrder =
        new CompoundConstantEmitter(EDIS_MAX_OPERANDS);

      operandOrderArray->addEntry(operandOrder);

      if (syntaxIndex < numSyntaxes) {
        populateOperandOrder(operandOrder, inst, syntaxIndex);
      }
    }

    infoStruct = NULL;
  }
}
CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
  AsmString = R->getValueAsString("AsmString");
  Result = R->getValueAsDag("ResultInst");

  // Verify that the root of the result is an instruction.
  DefInit *DI = dynamic_cast<DefInit*>(Result->getOperator());
  if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
    throw TGError(R->getLoc(), "result of inst alias should be an instruction");

  ResultInst = &T.getInstruction(DI->getDef());
  
  // NameClass - If argument names are repeated, we need to verify they have
  // the same class.
  StringMap<Record*> NameClass;
    
  // Decode and validate the arguments of the result.
  unsigned AliasOpNo = 0;
  for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
    // Tied registers don't have an entry in the result dag.
    if (ResultInst->Operands[i].getTiedRegister() != -1)
      continue;

    if (AliasOpNo >= Result->getNumArgs())
      throw TGError(R->getLoc(), "result has " + utostr(Result->getNumArgs()) +
                    " arguments, but " + ResultInst->TheDef->getName() +
                    " instruction expects " +
                    utostr(ResultInst->Operands.size()) + " operands!");
    
    
    Init *Arg = Result->getArg(AliasOpNo);
    Record *ResultOpRec = ResultInst->Operands[i].Rec;

    // Handle explicit registers.
    if (DefInit *ADI = dynamic_cast<DefInit*>(Arg)) {
      if (ADI->getDef()->isSubClassOf("Register")) {
        if (!Result->getArgName(AliasOpNo).empty())
          throw TGError(R->getLoc(), "result fixed register argument must "
                        "not have a name!");
        
        if (!ResultOpRec->isSubClassOf("RegisterClass"))
          throw TGError(R->getLoc(), "result fixed register argument is not "
                        "passed to a RegisterClass operand!");
        
        if (!T.getRegisterClass(ResultOpRec).containsRegister(ADI->getDef()))
          throw TGError(R->getLoc(), "fixed register " +ADI->getDef()->getName()
                        + " is not a member of the " + ResultOpRec->getName() +
                        " register class!");
                                                                              
        // Now that it is validated, add it.
        ResultOperands.push_back(ResultOperand(ADI->getDef()));
        ++AliasOpNo;
        continue;
      }
    }
    
    // If the operand is a record, it must have a name, and the record type must
    // match up with the instruction's argument type.
    if (DefInit *ADI = dynamic_cast<DefInit*>(Arg)) {
      if (Result->getArgName(AliasOpNo).empty())
        throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
                      " must have a name!");

      if (ADI->getDef() != ResultOpRec)
        throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
                      " declared with class " + ADI->getDef()->getName() +
                      ", instruction operand is class " + 
                      ResultOpRec->getName());
      
      // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
      // $foo can exist multiple times in the result list, but it must have the
      // same type.
      Record *&Entry = NameClass[Result->getArgName(AliasOpNo)];
      if (Entry && Entry != ADI->getDef())
        throw TGError(R->getLoc(), "result value $" +
                      Result->getArgName(AliasOpNo) +
                      " is both " + Entry->getName() + " and " +
                      ADI->getDef()->getName() + "!");
      
      // Now that it is validated, add it.
      ResultOperands.push_back(ResultOperand(Result->getArgName(AliasOpNo),
                                             ADI->getDef()));
      ++AliasOpNo;
      continue;
    }
    
    if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
      // Integer arguments can't have names.
      if (!Result->getArgName(AliasOpNo).empty())
        throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
                      " must not have a name!");
      if (ResultInst->Operands[i].MINumOperands != 1 ||
          !ResultOpRec->isSubClassOf("Operand"))
        throw TGError(R->getLoc(), "invalid argument class " + 
                      ResultOpRec->getName() +
                      " for integer result operand!");
      ResultOperands.push_back(ResultOperand(II->getValue()));
      ++AliasOpNo;
      continue;
    }

    throw TGError(R->getLoc(), "result of inst alias has unknown operand type");
  }
  
  if (AliasOpNo != Result->getNumArgs())
    throw TGError(R->getLoc(), "result has " + utostr(Result->getNumArgs()) +
                  " arguments, but " + ResultInst->TheDef->getName() +
                  " instruction expects " + utostr(ResultInst->Operands.size())+
                  " operands!");
}