CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) { // Rename anonymous register classes. if (R->getName().size() > 9 && R->getName()[9] == '.') { static unsigned AnonCounter = 0; R->setName("AnonRegClass_"+utostr(AnonCounter++)); } std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes"); for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { Record *Type = TypeList[i]; if (!Type->isSubClassOf("ValueType")) throw "RegTypes list member '" + Type->getName() + "' does not derive from the ValueType class!"; VTs.push_back(getValueType(Type)); } assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!"); std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList"); for (unsigned i = 0, e = RegList.size(); i != e; ++i) { Record *Reg = RegList[i]; if (!Reg->isSubClassOf("Register")) throw "Register Class member '" + Reg->getName() + "' does not derive from the Register class!"; Elements.push_back(Reg); } // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags. ListInit *SRC = R->getValueAsListInit("SubRegClasses"); for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) { DagInit *DAG = dynamic_cast<DagInit*>(*i); if (!DAG) throw "SubRegClasses must contain DAGs"; DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator()); Record *RCRec; if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass")) throw "Operator '" + DAG->getOperator()->getAsString() + "' in SubRegClasses is not a RegisterClass"; // Iterate over args, all SubRegIndex instances. for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end(); ai != ae; ++ai) { DefInit *Idx = dynamic_cast<DefInit*>(*ai); Record *IdxRec; if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex")) throw "Argument '" + (*ai)->getAsString() + "' in SubRegClasses is not a SubRegIndex"; if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second) throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice"; } } // Allow targets to override the size in bits of the RegisterClass. unsigned Size = R->getValueAsInt("Size"); Namespace = R->getValueAsString("Namespace"); SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits(); SpillAlignment = R->getValueAsInt("Alignment"); CopyCost = R->getValueAsInt("CopyCost"); MethodBodies = R->getValueAsCode("MethodBodies"); MethodProtos = R->getValueAsCode("MethodProtos"); }
/// \brief Invert the 1-[0/1] mapping of diags to group into a one to many /// mapping of groups to diags in the group. static void groupDiagnostics(const std::vector<Record*> &Diags, const std::vector<Record*> &DiagGroups, std::map<std::string, GroupInfo> &DiagsInGroup) { for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record *R = Diags[i]; DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")); if (DI == 0) continue; assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" && "Note can't be in a DiagGroup"); std::string GroupName = DI->getDef()->getValueAsString("GroupName"); DiagsInGroup[GroupName].DiagsInGroup.push_back(R); } // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty // groups (these are warnings that GCC supports that clang never produces). for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { Record *Group = DiagGroups[i]; GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")]; std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName")); } // Assign unique ID numbers to the groups. unsigned IDNo = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo) I->second.IDNo = IDNo; }
void SetTheory::evaluate(Init *Expr, RecSet &Elts, ArrayRef<SMLoc> Loc) { // A def in a list can be a just an element, or it may expand. if (DefInit *Def = dyn_cast<DefInit>(Expr)) { if (const RecVec *Result = expand(Def->getDef())) return Elts.insert(Result->begin(), Result->end()); Elts.insert(Def->getDef()); return; } // Lists simply expand. if (ListInit *LI = dyn_cast<ListInit>(Expr)) return evaluate(LI->begin(), LI->end(), Elts, Loc); // Anything else must be a DAG. DagInit *DagExpr = dyn_cast<DagInit>(Expr); if (!DagExpr) PrintFatalError(Loc, "Invalid set element: " + Expr->getAsString()); DefInit *OpInit = dyn_cast<DefInit>(DagExpr->getOperator()); if (!OpInit) PrintFatalError(Loc, "Bad set expression: " + Expr->getAsString()); auto I = Operators.find(OpInit->getDef()->getName()); if (I == Operators.end()) PrintFatalError(Loc, "Unknown set operator: " + Expr->getAsString()); I->second->apply(*this, DagExpr, Elts, Loc); }
void SetTheory::evaluate(Init *Expr, RecSet &Elts) { // A def in a list can be a just an element, or it may expand. if (DefInit *Def = dynamic_cast<DefInit*>(Expr)) { if (const RecVec *Result = expand(Def->getDef())) return Elts.insert(Result->begin(), Result->end()); Elts.insert(Def->getDef()); return; } // Lists simply expand. if (ListInit *LI = dynamic_cast<ListInit*>(Expr)) return evaluate(LI->begin(), LI->end(), Elts); // Anything else must be a DAG. DagInit *DagExpr = dynamic_cast<DagInit*>(Expr); if (!DagExpr) throw "Invalid set element: " + Expr->getAsString(); DefInit *OpInit = dynamic_cast<DefInit*>(DagExpr->getOperator()); if (!OpInit) throw "Bad set expression: " + Expr->getAsString(); Operator *Op = Operators.lookup(OpInit->getDef()->getName()); if (!Op) throw "Unknown set operator: " + Expr->getAsString(); Op->apply(*this, DagExpr, Elts); }
static std::string PhyRegForNode(TreePatternNode *Op, const CodeGenTarget &Target) { std::string PhysReg; if (!Op->isLeaf()) return PhysReg; DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue()); Record *OpLeafRec = OpDI->getDef(); if (!OpLeafRec->isSubClassOf("Register")) return PhysReg; PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \ "Namespace")->getValue())->getValue(); PhysReg += "::"; PhysReg += Target.getRegBank().getReg(OpLeafRec)->getName(); return PhysReg; }
/// 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; }
CGIOperandList::CGIOperandList(Record *R) : TheDef(R) { isPredicable = false; hasOptionalDef = false; isVariadic = false; DagInit *OutDI = R->getValueAsDag("OutOperandList"); if (DefInit *Init = dyn_cast<DefInit>(OutDI->getOperator())) { if (Init->getDef()->getName() != "outs") PrintFatalError(R->getName() + ": invalid def name for output list: use 'outs'"); } else PrintFatalError(R->getName() + ": invalid output list: use 'outs'"); NumDefs = OutDI->getNumArgs(); DagInit *InDI = R->getValueAsDag("InOperandList"); if (DefInit *Init = dyn_cast<DefInit>(InDI->getOperator())) { if (Init->getDef()->getName() != "ins") PrintFatalError(R->getName() + ": invalid def name for input list: use 'ins'"); } else PrintFatalError(R->getName() + ": invalid input list: use 'ins'"); unsigned MIOperandNo = 0; std::set<std::string> OperandNames; for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i) { Init *ArgInit; std::string ArgName; if (i < NumDefs) { ArgInit = OutDI->getArg(i); ArgName = OutDI->getArgName(i); } else { ArgInit = InDI->getArg(i-NumDefs); ArgName = InDI->getArgName(i-NumDefs); } DefInit *Arg = dyn_cast<DefInit>(ArgInit); if (!Arg) PrintFatalError("Illegal operand for the '" + R->getName() + "' instruction!"); Record *Rec = Arg->getDef(); std::string PrintMethod = "printOperand"; std::string EncoderMethod; std::string OperandType = "OPERAND_UNKNOWN"; unsigned NumOps = 1; DagInit *MIOpInfo = nullptr; if (Rec->isSubClassOf("RegisterOperand")) { PrintMethod = Rec->getValueAsString("PrintMethod"); } else if (Rec->isSubClassOf("Operand")) { PrintMethod = Rec->getValueAsString("PrintMethod"); OperandType = Rec->getValueAsString("OperandType"); // If there is an explicit encoder method, use it. EncoderMethod = Rec->getValueAsString("EncoderMethod"); MIOpInfo = Rec->getValueAsDag("MIOperandInfo"); // Verify that MIOpInfo has an 'ops' root value. if (!isa<DefInit>(MIOpInfo->getOperator()) || cast<DefInit>(MIOpInfo->getOperator())->getDef()->getName() != "ops") PrintFatalError("Bad value for MIOperandInfo in operand '" + Rec->getName() + "'\n"); // If we have MIOpInfo, then we have #operands equal to number of entries // in MIOperandInfo. if (unsigned NumArgs = MIOpInfo->getNumArgs()) NumOps = NumArgs; if (Rec->isSubClassOf("PredicateOp")) isPredicable = true; else if (Rec->isSubClassOf("OptionalDefOperand")) hasOptionalDef = true; } else if (Rec->getName() == "variable_ops") { isVariadic = true; continue; } else if (Rec->isSubClassOf("RegisterClass")) { OperandType = "OPERAND_REGISTER"; } else if (!Rec->isSubClassOf("PointerLikeRegClass") && !Rec->isSubClassOf("unknown_class")) PrintFatalError("Unknown operand class '" + Rec->getName() + "' in '" + R->getName() + "' instruction!"); // Check that the operand has a name and that it's unique. if (ArgName.empty()) PrintFatalError("In instruction '" + R->getName() + "', operand #" + Twine(i) + " has no name!"); if (!OperandNames.insert(ArgName).second) PrintFatalError("In instruction '" + R->getName() + "', operand #" + Twine(i) + " has the same name as a previous operand!"); OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, EncoderMethod, OperandType, MIOperandNo, NumOps, MIOpInfo)); MIOperandNo += NumOps; } // Make sure the constraints list for each operand is large enough to hold // constraint info, even if none is present. for (unsigned i = 0, e = OperandList.size(); i != e; ++i) OperandList[i].Constraints.resize(OperandList[i].MINumOperands); }
/// getValueRecord - Returns the value of this tree node as a record. For now /// we only allow DefInit's as our leaf values, so this is used. Record *TreePatternNode::getValueRecord() const { DefInit *DI = dynamic_cast<DefInit*>(getValue()); assert(DI && "Instruction Selector does not yet support non-def leaves!"); return DI->getDef(); }
InvTreePatternNode *InvTreePattern::ParseTreePattern(Init *TheInit, StringRef OpName) { if (DefInit *DI = dyn_cast<DefInit>(TheInit)) { Record *R = DI->getDef(); // On direct reference to a leaf DagNode (SDNode) or a pattern fragment, create // a new InvTreePatternNode. if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) { return ParseTreePattern(DagInit::get(DI, "", std::vector<std::pair<Init*, std::string> >()), OpName); } // Treat as an input element InvTreePatternNode *Res = new InvTreePatternNode(DI); if (R->getName() == "node" && OpName.empty()) { error("'node' requires an opname to match operand lists!"); } Res->setName(OpName); return Res; } if (IntInit *II = dyn_cast<IntInit>(TheInit)) { if (!OpName.empty()) { error("Constant int args should not have a name!"); } return new InvTreePatternNode(II); } if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) { // Convert to IntInit Init *II = BI->convertInitializerTo(IntRecTy::get()); if (II == 0 || !isa<IntInit>(II)) { error("Bits values must be integer constants!"); } return ParseTreePattern(II, OpName); } DagInit *Dag = dyn_cast<DagInit>(TheInit); if (!Dag) { TheInit->dump(); error("The Pattern has an unexpected init type."); } DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator()); if (!OpDef) { error("Thye Pattern has an unexpected operator type."); } Record *OpRec = OpDef->getDef(); if (OpRec->isSubClassOf("ValueType")) { // ValueType is the type of a leaf node. if (Dag->getNumArgs() != 1) { error("Expected 1 argument for a ValueType operator."); } InvTreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0)); // assert(New->getNumTypes() == 1 && "Unable to handle multiple types!"); // New->UpdateNodeType(0, getValueType(OpRec), *this); if (!OpName.empty()) { error("ValueType should not have a name!"); } return New; } // Verify that this makes sense for an operator if (!OpRec->isSubClassOf("PatFrag") && !OpRec->isSubClassOf("SDNode") && !OpRec->isSubClassOf("Instruction") && !OpRec->isSubClassOf("SDNodeXForm") && !OpRec->isSubClassOf("Intrinsic") && OpRec->getName() != "set" && OpRec->getName() != "implicit" && OpRec->getName() != "outs" && OpRec->getName() != "ins" && OpRec->getName() != "null_frag") { error("Unrecognized node '" + OpRec->getName() + "'!"); } // Unlike Regular treepatterns, we assume all patterns are "input" patterns // in the TableGen context if (OpRec->isSubClassOf("Instruction") || OpRec->isSubClassOf("SDNodeXForm")) { error("Cannot use '" + OpRec->getName() + "' in the output pattern."); } std::vector<InvTreePatternNode*> Children; // Parse operands for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) { Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i))); } if (OpRec->isSubClassOf("Intrinsic")) { // Unhandled... DEBUG(error("Intrinsics unhandled at this time."););
/// EmitLeafMatchCode - Generate matching code for leaf nodes. void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) { assert(N->isLeaf() && "Not a leaf?"); // Direct match against an integer constant. if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) { // If this is the root of the dag we're matching, we emit a redundant opcode // check to ensure that this gets folded into the normal top-level // OpcodeSwitch. if (N == Pattern.getSrcPattern()) { const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm")); AddMatcher(new CheckOpcodeMatcher(NI)); } return AddMatcher(new CheckIntegerMatcher(II->getValue())); } // An UnsetInit represents a named node without any constraints. if (isa<UnsetInit>(N->getLeafValue())) { assert(N->hasName() && "Unnamed ? leaf"); return; } DefInit *DI = dyn_cast<DefInit>(N->getLeafValue()); if (!DI) { errs() << "Unknown leaf kind: " << *N << "\n"; abort(); } Record *LeafRec = DI->getDef(); // A ValueType leaf node can represent a register when named, or itself when // unnamed. if (LeafRec->isSubClassOf("ValueType")) { // A named ValueType leaf always matches: (add i32:$a, i32:$b). if (N->hasName()) return; // An unnamed ValueType as in (sext_inreg GPR:$foo, i8). return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName())); } if (// Handle register references. Nothing to do here, they always match. LeafRec->isSubClassOf("RegisterClass") || LeafRec->isSubClassOf("RegisterOperand") || LeafRec->isSubClassOf("PointerLikeRegClass") || LeafRec->isSubClassOf("SubRegIndex") || // Place holder for SRCVALUE nodes. Nothing to do here. LeafRec->getName() == "srcvalue") return; // If we have a physreg reference like (mul gpr:$src, EAX) then we need to // record the register if (LeafRec->isSubClassOf("Register")) { AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(), NextRecordedOperandNo)); PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++)); return; } if (LeafRec->isSubClassOf("CondCode")) return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName())); if (LeafRec->isSubClassOf("ComplexPattern")) { // We can't model ComplexPattern uses that don't have their name taken yet. // The OPC_CheckComplexPattern operation implicitly records the results. if (N->getName().empty()) { std::string S; raw_string_ostream OS(S); OS << "We expect complex pattern uses to have names: " << *N; PrintFatalError(OS.str()); } // Remember this ComplexPattern so that we can emit it after all the other // structural matches are done. unsigned InputOperand = VariableMap[N->getName()] - 1; MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand)); return; } errs() << "Unknown leaf kind: " << *N << "\n"; abort(); }
void RegisterInfoEmitter::EmitRegMapping(raw_ostream &OS, const std::vector<CodeGenRegister*> &Regs, bool isCtor) { // Collect all information about dwarf register numbers typedef std::map<Record*, std::vector<int64_t>, LessRecord> DwarfRegNumsMapTy; DwarfRegNumsMapTy DwarfRegNums; // 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; } if (!maxLength) return; // 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 reverse information about the dwarf register numbers. for (unsigned j = 0; j < 2; ++j) { OS << " switch ("; if (j == 0) OS << "DwarfFlavour"; else OS << "EHFlavour"; OS << ") {\n" << " default:\n" << " assert(0 && \"Unknown DWARF flavour\");\n" << " break;\n"; for (unsigned i = 0, e = maxLength; i != e; ++i) { OS << " case " << i << ":\n"; for (DwarfRegNumsMapTy::iterator I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) { int DwarfRegNo = I->second[i]; if (DwarfRegNo < 0) continue; OS << " "; if (!isCtor) OS << "RI->"; OS << "mapDwarfRegToLLVMReg(" << DwarfRegNo << ", " << getQualifiedName(I->first) << ", "; if (j == 0) OS << "false"; else OS << "true"; OS << " );\n"; } OS << " break;\n"; } OS << " }\n"; } for (unsigned i = 0, e = Regs.size(); i != e; ++i) { Record *Reg = Regs[i]->TheDef; const RecordVal *V = Reg->getValue("DwarfAlias"); if (!V || !V->getValue()) continue; DefInit *DI = dynamic_cast<DefInit*>(V->getValue()); Record *Alias = DI->getDef(); DwarfRegNums[Reg] = DwarfRegNums[Alias]; } // Emit information about the dwarf register numbers. for (unsigned j = 0; j < 2; ++j) { OS << " switch ("; if (j == 0) OS << "DwarfFlavour"; else OS << "EHFlavour"; OS << ") {\n" << " default:\n" << " assert(0 && \"Unknown DWARF flavour\");\n" << " break;\n"; for (unsigned i = 0, e = maxLength; i != e; ++i) { OS << " case " << i << ":\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]; OS << " "; if (!isCtor) OS << "RI->"; OS << "mapLLVMRegToDwarfReg(" << getQualifiedName(I->first) << ", " << RegNo << ", "; if (j == 0) OS << "false"; else OS << "true"; OS << " );\n"; } OS << " break;\n"; } OS << " }\n"; } }
void FastISelMap::collectPatterns(CodeGenDAGPatterns &CGP) { const CodeGenTarget &Target = CGP.getTargetInfo(); // Determine the target's namespace name. InstNS = Target.getInstNamespace() + "::"; assert(InstNS.size() > 2 && "Can't determine target-specific namespace!"); // Scan through all the patterns and record the simple ones. for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end(); I != E; ++I) { const PatternToMatch &Pattern = *I; // For now, just look at Instructions, so that we don't have to worry // about emitting multiple instructions for a pattern. TreePatternNode *Dst = Pattern.getDstPattern(); if (Dst->isLeaf()) continue; Record *Op = Dst->getOperator(); if (!Op->isSubClassOf("Instruction")) continue; CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op); if (II.Operands.empty()) continue; // For now, ignore multi-instruction patterns. bool MultiInsts = false; for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) { TreePatternNode *ChildOp = Dst->getChild(i); if (ChildOp->isLeaf()) continue; if (ChildOp->getOperator()->isSubClassOf("Instruction")) { MultiInsts = true; break; } } if (MultiInsts) continue; // For now, ignore instructions where the first operand is not an // output register. const CodeGenRegisterClass *DstRC = nullptr; std::string SubRegNo; if (Op->getName() != "EXTRACT_SUBREG") { Record *Op0Rec = II.Operands[0].Rec; if (Op0Rec->isSubClassOf("RegisterOperand")) Op0Rec = Op0Rec->getValueAsDef("RegClass"); if (!Op0Rec->isSubClassOf("RegisterClass")) continue; DstRC = &Target.getRegisterClass(Op0Rec); if (!DstRC) continue; } else { // If this isn't a leaf, then continue since the register classes are // a bit too complicated for now. if (!Dst->getChild(1)->isLeaf()) continue; DefInit *SR = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue()); if (SR) SubRegNo = getQualifiedName(SR->getDef()); else SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString(); } // Inspect the pattern. TreePatternNode *InstPatNode = Pattern.getSrcPattern(); if (!InstPatNode) continue; if (InstPatNode->isLeaf()) continue; // Ignore multiple result nodes for now. if (InstPatNode->getNumTypes() > 1) continue; Record *InstPatOp = InstPatNode->getOperator(); std::string OpcodeName = getOpcodeName(InstPatOp, CGP); MVT::SimpleValueType RetVT = MVT::isVoid; if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getType(0); MVT::SimpleValueType VT = RetVT; if (InstPatNode->getNumChildren()) { assert(InstPatNode->getChild(0)->getNumTypes() == 1); VT = InstPatNode->getChild(0)->getType(0); } // For now, filter out any instructions with predicates. if (!InstPatNode->getPredicateFns().empty()) continue; // Check all the operands. OperandsSignature Operands; if (!Operands.initialize(InstPatNode, Target, VT, ImmediatePredicates, DstRC)) continue; std::vector<std::string>* PhysRegInputs = new std::vector<std::string>(); if (InstPatNode->getOperator()->getName() == "imm" || InstPatNode->getOperator()->getName() == "fpimm") PhysRegInputs->push_back(""); else { // Compute the PhysRegs used by the given pattern, and check that // the mapping from the src to dst patterns is simple. bool FoundNonSimplePattern = false; unsigned DstIndex = 0; for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) { std::string PhysReg = PhyRegForNode(InstPatNode->getChild(i), Target); if (PhysReg.empty()) { if (DstIndex >= Dst->getNumChildren() || Dst->getChild(DstIndex)->getName() != InstPatNode->getChild(i)->getName()) { FoundNonSimplePattern = true; break; } ++DstIndex; } PhysRegInputs->push_back(PhysReg); } if (Op->getName() != "EXTRACT_SUBREG" && DstIndex < Dst->getNumChildren()) FoundNonSimplePattern = true; if (FoundNonSimplePattern) continue; } // Check if the operands match one of the patterns handled by FastISel. std::string ManglingSuffix; raw_string_ostream SuffixOS(ManglingSuffix); Operands.PrintManglingSuffix(SuffixOS, ImmediatePredicates, true); SuffixOS.flush(); if (!StringSwitch<bool>(ManglingSuffix) .Cases("", "r", "rr", "ri", "i", "f", true) .Default(false)) continue; // Get the predicate that guards this pattern. std::string PredicateCheck = Pattern.getPredicateCheck(); // Ok, we found a pattern that we can handle. Remember it. InstructionMemo Memo = { Pattern.getDstPattern()->getOperator()->getName(), DstRC, SubRegNo, PhysRegInputs, PredicateCheck }; int complexity = Pattern.getPatternComplexity(CGP); if (SimplePatternsCheck[Operands][OpcodeName][VT] [RetVT].count(PredicateCheck)) { PrintFatalError(Pattern.getSrcRecord()->getLoc(), "Duplicate predicate in FastISel table!"); } SimplePatternsCheck[Operands][OpcodeName][VT][RetVT].insert( std::make_pair(PredicateCheck, true)); // Note: Instructions with the same complexity will appear in the order // that they are encountered. SimplePatterns[Operands][OpcodeName][VT][RetVT].insert( std::make_pair(complexity, Memo)); // If any of the operands were immediates with predicates on them, strip // them down to a signature that doesn't have predicates so that we can // associate them with the stripped predicate version. if (Operands.hasAnyImmediateCodes()) { SignaturesWithConstantForms[Operands.getWithoutImmCodes()] .push_back(Operands); } } }
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!"); }
CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R) : TheDef(R), Name(R->getName()), EnumValue(-1) { // Rename anonymous register classes. if (R->getName().size() > 9 && R->getName()[9] == '.') { static unsigned AnonCounter = 0; R->setName("AnonRegClass_"+utostr(AnonCounter++)); } std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes"); for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { Record *Type = TypeList[i]; if (!Type->isSubClassOf("ValueType")) throw "RegTypes list member '" + Type->getName() + "' does not derive from the ValueType class!"; VTs.push_back(getValueType(Type)); } assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!"); // Allocation order 0 is the full set. AltOrders provides others. const SetTheory::RecVec *Elements = RegBank.getSets().expand(R); ListInit *AltOrders = R->getValueAsListInit("AltOrders"); Orders.resize(1 + AltOrders->size()); // Default allocation order always contains all registers. for (unsigned i = 0, e = Elements->size(); i != e; ++i) { Orders[0].push_back((*Elements)[i]); Members.insert(RegBank.getReg((*Elements)[i])); } // Alternative allocation orders may be subsets. SetTheory::RecSet Order; for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) { RegBank.getSets().evaluate(AltOrders->getElement(i), Order); Orders[1 + i].append(Order.begin(), Order.end()); // Verify that all altorder members are regclass members. while (!Order.empty()) { CodeGenRegister *Reg = RegBank.getReg(Order.back()); Order.pop_back(); if (!contains(Reg)) throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() + " is not a class member"); } } // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags. ListInit *SRC = R->getValueAsListInit("SubRegClasses"); for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) { DagInit *DAG = dynamic_cast<DagInit*>(*i); if (!DAG) throw "SubRegClasses must contain DAGs"; DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator()); Record *RCRec; if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass")) throw "Operator '" + DAG->getOperator()->getAsString() + "' in SubRegClasses is not a RegisterClass"; // Iterate over args, all SubRegIndex instances. for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end(); ai != ae; ++ai) { DefInit *Idx = dynamic_cast<DefInit*>(*ai); Record *IdxRec; if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex")) throw "Argument '" + (*ai)->getAsString() + "' in SubRegClasses is not a SubRegIndex"; if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second) throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice"; } } // Allow targets to override the size in bits of the RegisterClass. unsigned Size = R->getValueAsInt("Size"); Namespace = R->getValueAsString("Namespace"); SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits(); SpillAlignment = R->getValueAsInt("Alignment"); CopyCost = R->getValueAsInt("CopyCost"); Allocatable = R->getValueAsBit("isAllocatable"); AltOrderSelect = R->getValueAsCode("AltOrderSelect"); }
/// 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; }
void ClangDiagGroupsEmitter::run(raw_ostream &OS) { // Compute a mapping from a DiagGroup to all of its parents. DiagGroupParentMap DGParentMap(Records); // Invert the 1-[0/1] mapping of diags to group into a one to many mapping of // groups to diags in the group. std::map<std::string, GroupInfo> DiagsInGroup; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record *R = Diags[i]; DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")); if (DI == 0) continue; std::string GroupName = DI->getDef()->getValueAsString("GroupName"); DiagsInGroup[GroupName].DiagsInGroup.push_back(R); } // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty // groups (these are warnings that GCC supports that clang never produces). std::vector<Record*> DiagGroups = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { Record *Group = DiagGroups[i]; GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")]; std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName")); } // Assign unique ID numbers to the groups. unsigned IDNo = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo) I->second.IDNo = IDNo; // Walk through the groups emitting an array for each diagnostic of the diags // that are mapped to. OS << "\n#ifdef GET_DIAG_ARRAYS\n"; unsigned MaxLen = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { MaxLen = std::max(MaxLen, (unsigned)I->first.size()); std::vector<const Record*> &V = I->second.DiagsInGroup; if (!V.empty()) { OS << "static const short DiagArray" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = V.size(); i != e; ++i) OS << "diag::" << V[i]->getName() << ", "; OS << "-1 };\n"; } const std::vector<std::string> &SubGroups = I->second.SubGroups; if (!SubGroups.empty()) { OS << "static const short DiagSubGroup" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) { std::map<std::string, GroupInfo>::iterator RI = DiagsInGroup.find(SubGroups[i]); assert(RI != DiagsInGroup.end() && "Referenced without existing?"); OS << RI->second.IDNo << ", "; } OS << "-1 };\n"; } } OS << "#endif // GET_DIAG_ARRAYS\n\n"; // Emit the table now. OS << "\n#ifdef GET_DIAG_TABLE\n"; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { // Group option string. OS << " { "; OS << I->first.size() << ", "; OS << "\""; OS.write_escaped(I->first) << "\"," << std::string(MaxLen-I->first.size()+1, ' '); // Diagnostics in the group. if (I->second.DiagsInGroup.empty()) OS << "0, "; else OS << "DiagArray" << I->second.IDNo << ", "; // Subgroups. if (I->second.SubGroups.empty()) OS << 0; else OS << "DiagSubGroup" << I->second.IDNo; OS << " },\n"; } OS << "#endif // GET_DIAG_TABLE\n\n"; // Emit the category table next. DiagCategoryIDMap CategoriesByID(Records); OS << "\n#ifdef GET_CATEGORY_TABLE\n"; for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(), E = CategoriesByID.end(); I != E; ++I) OS << "CATEGORY(\"" << *I << "\", " << getDiagCategoryEnum(*I) << ")\n"; OS << "#endif // GET_CATEGORY_TABLE\n\n"; }
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!"); }
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!"); }
void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) { const CodeGenTarget &Target = CGP.getTargetInfo(); // Determine the target's namespace name. InstNS = Target.getInstNamespace() + "::"; assert(InstNS.size() > 2 && "Can't determine target-specific namespace!"); // Scan through all the patterns and record the simple ones. for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end(); I != E; ++I) { const PatternToMatch &Pattern = *I; // For now, just look at Instructions, so that we don't have to worry // about emitting multiple instructions for a pattern. TreePatternNode *Dst = Pattern.getDstPattern(); if (Dst->isLeaf()) continue; Record *Op = Dst->getOperator(); if (!Op->isSubClassOf("Instruction")) continue; CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName()); if (II.OperandList.empty()) continue; // For now, ignore multi-instruction patterns. bool MultiInsts = false; for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) { TreePatternNode *ChildOp = Dst->getChild(i); if (ChildOp->isLeaf()) continue; if (ChildOp->getOperator()->isSubClassOf("Instruction")) { MultiInsts = true; break; } } if (MultiInsts) continue; // For now, ignore instructions where the first operand is not an // output register. const CodeGenRegisterClass *DstRC = 0; unsigned SubRegNo = ~0; if (Op->getName() != "EXTRACT_SUBREG") { Record *Op0Rec = II.OperandList[0].Rec; if (!Op0Rec->isSubClassOf("RegisterClass")) continue; DstRC = &Target.getRegisterClass(Op0Rec); if (!DstRC) continue; } else { SubRegNo = static_cast<IntInit*>( Dst->getChild(1)->getLeafValue())->getValue(); } // Inspect the pattern. TreePatternNode *InstPatNode = Pattern.getSrcPattern(); if (!InstPatNode) continue; if (InstPatNode->isLeaf()) continue; Record *InstPatOp = InstPatNode->getOperator(); std::string OpcodeName = getOpcodeName(InstPatOp, CGP); MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0); MVT::SimpleValueType VT = RetVT; if (InstPatNode->getNumChildren()) VT = InstPatNode->getChild(0)->getTypeNum(0); // For now, filter out instructions which just set a register to // an Operand or an immediate, like MOV32ri. if (InstPatOp->isSubClassOf("Operand")) continue; // For now, filter out any instructions with predicates. if (!InstPatNode->getPredicateFns().empty()) continue; // Check all the operands. OperandsSignature Operands; if (!Operands.initialize(InstPatNode, Target, VT)) continue; std::vector<std::string>* PhysRegInputs = new std::vector<std::string>(); if (!InstPatNode->isLeaf() && (InstPatNode->getOperator()->getName() == "imm" || InstPatNode->getOperator()->getName() == "fpimmm")) PhysRegInputs->push_back(""); else if (!InstPatNode->isLeaf()) { for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) { TreePatternNode *Op = InstPatNode->getChild(i); if (!Op->isLeaf()) { PhysRegInputs->push_back(""); continue; } DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue()); Record *OpLeafRec = OpDI->getDef(); std::string PhysReg; if (OpLeafRec->isSubClassOf("Register")) { PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \ "Namespace")->getValue())->getValue(); PhysReg += "::"; std::vector<CodeGenRegister> Regs = Target.getRegisters(); for (unsigned i = 0; i < Regs.size(); ++i) { if (Regs[i].TheDef == OpLeafRec) { PhysReg += Regs[i].getName(); break; } } } PhysRegInputs->push_back(PhysReg); } } else PhysRegInputs->push_back(""); // Get the predicate that guards this pattern. std::string PredicateCheck = Pattern.getPredicateCheck(); // Ok, we found a pattern that we can handle. Remember it. InstructionMemo Memo = { Pattern.getDstPattern()->getOperator()->getName(), DstRC, SubRegNo, PhysRegInputs }; assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) && "Duplicate pattern!"); SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo; } }
const CodeGenRegister::SubRegMap & CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) { // Only compute this map once. if (SubRegsComplete) return SubRegs; SubRegsComplete = true; std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs"); std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices"); if (SubList.size() != Indices.size()) throw TGError(TheDef->getLoc(), "Register " + getName() + " SubRegIndices doesn't match SubRegs"); // First insert the direct subregs and make sure they are fully indexed. for (unsigned i = 0, e = SubList.size(); i != e; ++i) { CodeGenRegister *SR = RegBank.getReg(SubList[i]); if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second) throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName() + " appears twice in Register " + getName()); } // Keep track of inherited subregs and how they can be reached. SmallVector<Orphan, 8> Orphans; // Clone inherited subregs and place duplicate entries on Orphans. // Here the order is important - earlier subregs take precedence. for (unsigned i = 0, e = SubList.size(); i != e; ++i) { CodeGenRegister *SR = RegBank.getReg(SubList[i]); const SubRegMap &Map = SR->getSubRegs(RegBank); // Add this as a super-register of SR now all sub-registers are in the list. // This creates a topological ordering, the exact order depends on the // order getSubRegs is called on all registers. SR->SuperRegs.push_back(this); for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE; ++SI) { if (!SubRegs.insert(*SI).second) Orphans.push_back(Orphan(SI->second, Indices[i], SI->first)); // Noop sub-register indexes are possible, so avoid duplicates. if (SI->second != SR) SI->second->SuperRegs.push_back(this); } } // Process the composites. ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices"); for (unsigned i = 0, e = Comps->size(); i != e; ++i) { DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i)); if (!Pat) throw TGError(TheDef->getLoc(), "Invalid dag '" + Comps->getElement(i)->getAsString() + "' in CompositeIndices"); DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator()); if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex")) throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " + Pat->getAsString()); // Resolve list of subreg indices into R2. CodeGenRegister *R2 = this; for (DagInit::const_arg_iterator di = Pat->arg_begin(), de = Pat->arg_end(); di != de; ++di) { DefInit *IdxInit = dynamic_cast<DefInit*>(*di); if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex")) throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " + Pat->getAsString()); const SubRegMap &R2Subs = R2->getSubRegs(RegBank); SubRegMap::const_iterator ni = R2Subs.find(IdxInit->getDef()); if (ni == R2Subs.end()) throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() + " refers to bad index in " + R2->getName()); R2 = ni->second; } // Insert composite index. Allow overriding inherited indices etc. SubRegs[BaseIdxInit->getDef()] = R2; // R2 is no longer an orphan. for (unsigned j = 0, je = Orphans.size(); j != je; ++j) if (Orphans[j].SubReg == R2) Orphans[j].SubReg = 0; } // Now Orphans contains the inherited subregisters without a direct index. // Create inferred indexes for all missing entries. for (unsigned i = 0, e = Orphans.size(); i != e; ++i) { Orphan &O = Orphans[i]; if (!O.SubReg) continue; SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] = O.SubReg; } return SubRegs; }
// // RegisterInfoEmitter::run - Main register file description emitter. // void RegisterInfoEmitter::run(raw_ostream &OS) { CodeGenTarget Target(Records); CodeGenRegBank &RegBank = Target.getRegBank(); RegBank.computeDerivedInfo(); std::map<const CodeGenRegister*, CodeGenRegister::Set> Overlaps; RegBank.computeOverlaps(Overlaps); EmitSourceFileHeader("Register Information Source Fragment", OS); OS << "namespace llvm {\n\n"; // Start out by emitting each of the register classes. const std::vector<CodeGenRegisterClass> &RegisterClasses = Target.getRegisterClasses(); // Collect all registers belonging to any allocatable class. std::set<Record*> AllocatableRegs; // 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(); // Collect allocatable registers. if (RC.Allocatable) AllocatableRegs.insert(Order.begin(), Order.end()); // 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"; } // 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> > SuperClassMap; std::map<unsigned, std::set<unsigned> > SuperRegClassMap; OS << "\n"; unsigned NumSubRegIndices = RegBank.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 = RegBank.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(); 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]; // 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 || !RC.hasSubClass(&RC2)) 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"; } // 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(" << 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.Allocatable << ", " << RC.getName() << ", " << RC.getName() << " + " << RC.getOrder().size() << ") {}\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 << " static const ArrayRef<unsigned> Order[] = {\n" << " ArrayRef<unsigned>(" << RC.getName(); for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi) OS << "),\n ArrayRef<unsigned>(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 << " &" << getQualifiedName(RegisterClasses[i].TheDef) << "RegClass,\n"; OS << " };\n"; typedef std::map<Record*, std::vector<int64_t>, LessRecord> DwarfRegNumsMapTy; DwarfRegNumsMapTy DwarfRegNums; 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 const TargetRegisterDesc RegisterDescriptors[] = { // Descriptors\n"; OS << " { \"NOREG\",\t0,\t0,\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,\t"; else OS << "Empty_SuperRegsSet,\t"; OS << Reg.CostPerUse << ",\t" << 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 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 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\n"; // End of anonymous namespace... 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 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" << "}\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 reverse information about the dwarf register numbers. OS << "int " << ClassName << "::getLLVMRegNumFull(unsigned DwarfRegNum, " << "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 (DwarfRegNum) {\n" << " default:\n" << " assert(0 && \"Invalid DwarfRegNum\");\n" << " return -1;\n"; for (DwarfRegNumsMapTy::iterator I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) { int DwarfRegNo = I->second[i]; if (DwarfRegNo >= 0) OS << " case " << DwarfRegNo << ":\n" << " return " << getQualifiedName(I->first) << ";\n"; } OS << " };\n"; } OS << " };\n}\n\n"; for (unsigned i = 0, e = Regs.size(); i != e; ++i) { Record *Reg = Regs[i]->TheDef; const RecordVal *V = Reg->getValue("DwarfAlias"); if (!V || !V->getValue()) continue; DefInit *DI = dynamic_cast<DefInit*>(V->getValue()); Record *Alias = DI->getDef(); DwarfRegNums[Reg] = DwarfRegNums[Alias]; } // 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]; OS << " case " << getQualifiedName(I->first) << ":\n" << " return " << RegNo << ";\n"; } OS << " };\n"; } OS << " };\n}\n\n"; OS << "} // End llvm namespace \n"; }
CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr) : TheDef(R), AsmString(AsmStr) { Name = R->getValueAsString("Name"); Namespace = R->getValueAsString("Namespace"); isReturn = R->getValueAsBit("isReturn"); isBranch = R->getValueAsBit("isBranch"); isBarrier = R->getValueAsBit("isBarrier"); isCall = R->getValueAsBit("isCall"); isLoad = R->getValueAsBit("isLoad"); isStore = R->getValueAsBit("isStore"); bool isTwoAddress = R->getValueAsBit("isTwoAddress"); isPredicated = false; // set below. isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress"); isCommutable = R->getValueAsBit("isCommutable"); isTerminator = R->getValueAsBit("isTerminator"); isReMaterializable = R->getValueAsBit("isReMaterializable"); hasDelaySlot = R->getValueAsBit("hasDelaySlot"); usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter"); hasCtrlDep = R->getValueAsBit("hasCtrlDep"); noResults = R->getValueAsBit("noResults"); hasVariableNumberOfOperands = false; DagInit *DI; try { DI = R->getValueAsDag("OperandList"); } catch (...) { // Error getting operand list, just ignore it (sparcv9). AsmString.clear(); OperandList.clear(); return; } unsigned MIOperandNo = 0; std::set<std::string> OperandNames; for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) { DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i)); if (!Arg) throw "Illegal operand for the '" + R->getName() + "' instruction!"; Record *Rec = Arg->getDef(); std::string PrintMethod = "printOperand"; unsigned NumOps = 1; DagInit *MIOpInfo = 0; if (Rec->isSubClassOf("Operand")) { PrintMethod = Rec->getValueAsString("PrintMethod"); MIOpInfo = Rec->getValueAsDag("MIOperandInfo"); // Verify that MIOpInfo has an 'ops' root value. if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) || dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ->getDef()->getName() != "ops") throw "Bad value for MIOperandInfo in operand '" + Rec->getName() + "'\n"; // If we have MIOpInfo, then we have #operands equal to number of entries // in MIOperandInfo. if (unsigned NumArgs = MIOpInfo->getNumArgs()) NumOps = NumArgs; isPredicated |= Rec->isSubClassOf("PredicateOperand"); } else if (Rec->getName() == "variable_ops") { hasVariableNumberOfOperands = true; continue; } else if (!Rec->isSubClassOf("RegisterClass") && Rec->getName() != "ptr_rc") throw "Unknown operand class '" + Rec->getName() + "' in instruction '" + R->getName() + "' instruction!"; // Check that the operand has a name and that it's unique. if (DI->getArgName(i).empty()) throw "In instruction '" + R->getName() + "', operand #" + utostr(i) + " has no name!"; if (!OperandNames.insert(DI->getArgName(i)).second) throw "In instruction '" + R->getName() + "', operand #" + utostr(i) + " has the same name as a previous operand!"; OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, MIOperandNo, NumOps, MIOpInfo)); MIOperandNo += NumOps; } // Parse Constraints. ParseConstraints(R->getValueAsString("Constraints"), this); // For backward compatibility: isTwoAddress means operand 1 is tied to // operand 0. if (isTwoAddress) { if (!OperandList[1].Constraints[0].empty()) throw R->getName() + ": cannot use isTwoAddress property: instruction " "already has constraint set!"; OperandList[1].Constraints[0] = "((0 << 16) | (1 << TOI::TIED_TO))"; } // Any operands with unset constraints get 0 as their constraint. for (unsigned op = 0, e = OperandList.size(); op != e; ++op) for (unsigned j = 0, e = OperandList[op].MINumOperands; j != e; ++j) if (OperandList[op].Constraints[j].empty()) OperandList[op].Constraints[j] = "0"; // Parse the DisableEncoding field. std::string DisableEncoding = R->getValueAsString("DisableEncoding"); while (1) { std::string OpName = getToken(DisableEncoding, " ,\t"); if (OpName.empty()) break; // Figure out which operand this is. std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false); // Mark the operand as not-to-be encoded. if (Op.second >= OperandList[Op.first].DoNotEncode.size()) OperandList[Op.first].DoNotEncode.resize(Op.second+1); OperandList[Op.first].DoNotEncode[Op.second] = true; } }
/// \brief Invert the 1-[0/1] mapping of diags to group into a one to many /// mapping of groups to diags in the group. static void groupDiagnostics(const std::vector<Record*> &Diags, const std::vector<Record*> &DiagGroups, std::map<std::string, GroupInfo> &DiagsInGroup) { for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record *R = Diags[i]; DefInit *DI = dyn_cast<DefInit>(R->getValueInit("Group")); if (!DI) continue; assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" && "Note can't be in a DiagGroup"); std::string GroupName = DI->getDef()->getValueAsString("GroupName"); DiagsInGroup[GroupName].DiagsInGroup.push_back(R); } typedef SmallPtrSet<GroupInfo *, 16> GroupSetTy; GroupSetTy ImplicitGroups; // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty // groups (these are warnings that GCC supports that clang never produces). for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { Record *Group = DiagGroups[i]; GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")]; if (Group->isAnonymous()) { if (GI.DiagsInGroup.size() > 1) ImplicitGroups.insert(&GI); } else { if (GI.ExplicitDef) assert(GI.ExplicitDef == Group); else GI.ExplicitDef = Group; } std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName")); } // Assign unique ID numbers to the groups. unsigned IDNo = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo) I->second.IDNo = IDNo; // Sort the implicit groups, so we can warn about them deterministically. SmallVector<GroupInfo *, 16> SortedGroups(ImplicitGroups.begin(), ImplicitGroups.end()); for (SmallVectorImpl<GroupInfo *>::iterator I = SortedGroups.begin(), E = SortedGroups.end(); I != E; ++I) { MutableArrayRef<const Record *> GroupDiags = (*I)->DiagsInGroup; std::sort(GroupDiags.begin(), GroupDiags.end(), beforeThanCompare); } std::sort(SortedGroups.begin(), SortedGroups.end(), beforeThanCompareGroups); // Warn about the same group being used anonymously in multiple places. for (SmallVectorImpl<GroupInfo *>::const_iterator I = SortedGroups.begin(), E = SortedGroups.end(); I != E; ++I) { ArrayRef<const Record *> GroupDiags = (*I)->DiagsInGroup; if ((*I)->ExplicitDef) { std::string Name = (*I)->ExplicitDef->getValueAsString("GroupName"); for (ArrayRef<const Record *>::const_iterator DI = GroupDiags.begin(), DE = GroupDiags.end(); DI != DE; ++DI) { const DefInit *GroupInit = cast<DefInit>((*DI)->getValueInit("Group")); const Record *NextDiagGroup = GroupInit->getDef(); if (NextDiagGroup == (*I)->ExplicitDef) continue; SMRange InGroupRange = findSuperClassRange(*DI, "InGroup"); SmallString<64> Replacement; if (InGroupRange.isValid()) { Replacement += "InGroup<"; Replacement += (*I)->ExplicitDef->getName(); Replacement += ">"; } SMFixIt FixIt(InGroupRange, Replacement.str()); SrcMgr.PrintMessage(NextDiagGroup->getLoc().front(), SourceMgr::DK_Error, Twine("group '") + Name + "' is referred to anonymously", None, InGroupRange.isValid() ? FixIt : ArrayRef<SMFixIt>()); SrcMgr.PrintMessage((*I)->ExplicitDef->getLoc().front(), SourceMgr::DK_Note, "group defined here"); } } else { // If there's no existing named group, we should just warn once and use // notes to list all the other cases. ArrayRef<const Record *>::const_iterator DI = GroupDiags.begin(), DE = GroupDiags.end(); assert(DI != DE && "We only care about groups with multiple uses!"); const DefInit *GroupInit = cast<DefInit>((*DI)->getValueInit("Group")); const Record *NextDiagGroup = GroupInit->getDef(); std::string Name = NextDiagGroup->getValueAsString("GroupName"); SMRange InGroupRange = findSuperClassRange(*DI, "InGroup"); SrcMgr.PrintMessage(NextDiagGroup->getLoc().front(), SourceMgr::DK_Error, Twine("group '") + Name + "' is referred to anonymously", InGroupRange); for (++DI; DI != DE; ++DI) { GroupInit = cast<DefInit>((*DI)->getValueInit("Group")); InGroupRange = findSuperClassRange(*DI, "InGroup"); SrcMgr.PrintMessage(GroupInit->getDef()->getLoc().front(), SourceMgr::DK_Note, "also referenced here", InGroupRange); } } } }
void RegisterInfoEmitter::EmitRegMappingTables(raw_ostream &OS, const std::vector<CodeGenRegister*> &Regs, bool isCtor) { // Collect all information about dwarf register numbers typedef std::map<Record*, std::vector<int64_t>, LessRecord> DwarfRegNumsMapTy; DwarfRegNumsMapTy DwarfRegNums; // 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)) PrintWarning(Reg->getLoc(), Twine("DWARF numbers for register ") + getQualifiedName(Reg) + "specified multiple times"); DwarfRegNums[Reg] = RegNums; } if (!maxLength) return; // 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); std::string Namespace = Regs[0]->TheDef->getValueAsString("Namespace"); OS << "// " << Namespace << " Dwarf<->LLVM register mappings.\n"; // Emit reverse information about the dwarf register numbers. for (unsigned j = 0; j < 2; ++j) { for (unsigned i = 0, e = maxLength; i != e; ++i) { OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace; OS << (j == 0 ? "DwarfFlavour" : "EHFlavour"); OS << i << "Dwarf2L[]"; if (!isCtor) { OS << " = {\n"; // Store the mapping sorted by the LLVM reg num so lookup can be done // with a binary search. std::map<uint64_t, Record*> Dwarf2LMap; for (DwarfRegNumsMapTy::iterator I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) { int DwarfRegNo = I->second[i]; if (DwarfRegNo < 0) continue; Dwarf2LMap[DwarfRegNo] = I->first; } for (std::map<uint64_t, Record*>::iterator I = Dwarf2LMap.begin(), E = Dwarf2LMap.end(); I != E; ++I) OS << " { " << I->first << "U, " << getQualifiedName(I->second) << " },\n"; OS << "};\n"; } else { OS << ";\n"; } // We have to store the size in a const global, it's used in multiple // places. OS << "extern const unsigned " << Namespace << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "Dwarf2LSize"; if (!isCtor) OS << " = sizeof(" << Namespace << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "Dwarf2L)/sizeof(MCRegisterInfo::DwarfLLVMRegPair);\n\n"; else OS << ";\n\n"; } } for (unsigned i = 0, e = Regs.size(); i != e; ++i) { Record *Reg = Regs[i]->TheDef; const RecordVal *V = Reg->getValue("DwarfAlias"); if (!V || !V->getValue()) continue; DefInit *DI = dynamic_cast<DefInit*>(V->getValue()); Record *Alias = DI->getDef(); DwarfRegNums[Reg] = DwarfRegNums[Alias]; } // Emit information about the dwarf register numbers. for (unsigned j = 0; j < 2; ++j) { for (unsigned i = 0, e = maxLength; i != e; ++i) { OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace; OS << (j == 0 ? "DwarfFlavour" : "EHFlavour"); OS << i << "L2Dwarf[]"; if (!isCtor) { OS << " = {\n"; // Store the mapping sorted by the Dwarf reg num so lookup can be done // with a binary search. for (DwarfRegNumsMapTy::iterator I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) { int RegNo = I->second[i]; if (RegNo == -1) // -1 is the default value, don't emit a mapping. continue; OS << " { " << getQualifiedName(I->first) << ", " << RegNo << "U },\n"; } OS << "};\n"; } else { OS << ";\n"; } // We have to store the size in a const global, it's used in multiple // places. OS << "extern const unsigned " << Namespace << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2DwarfSize"; if (!isCtor) OS << " = sizeof(" << Namespace << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2Dwarf)/sizeof(MCRegisterInfo::DwarfLLVMRegPair);\n\n"; else OS << ";\n\n"; } } }
CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr) : TheDef(R), AsmString(AsmStr) { Namespace = R->getValueAsString("Namespace"); isReturn = R->getValueAsBit("isReturn"); isBranch = R->getValueAsBit("isBranch"); isIndirectBranch = R->getValueAsBit("isIndirectBranch"); isBarrier = R->getValueAsBit("isBarrier"); isCall = R->getValueAsBit("isCall"); canFoldAsLoad = R->getValueAsBit("canFoldAsLoad"); mayLoad = R->getValueAsBit("mayLoad"); mayStore = R->getValueAsBit("mayStore"); bool isTwoAddress = R->getValueAsBit("isTwoAddress"); isPredicable = R->getValueAsBit("isPredicable"); isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress"); isCommutable = R->getValueAsBit("isCommutable"); isTerminator = R->getValueAsBit("isTerminator"); isReMaterializable = R->getValueAsBit("isReMaterializable"); hasDelaySlot = R->getValueAsBit("hasDelaySlot"); usesCustomInserter = R->getValueAsBit("usesCustomInserter"); hasCtrlDep = R->getValueAsBit("hasCtrlDep"); isNotDuplicable = R->getValueAsBit("isNotDuplicable"); hasSideEffects = R->getValueAsBit("hasSideEffects"); neverHasSideEffects = R->getValueAsBit("neverHasSideEffects"); isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove"); hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq"); hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq"); hasOptionalDef = false; isVariadic = false; ImplicitDefs = R->getValueAsListOfDefs("Defs"); ImplicitUses = R->getValueAsListOfDefs("Uses"); if (neverHasSideEffects + hasSideEffects > 1) throw R->getName() + ": multiple conflicting side-effect flags set!"; DagInit *OutDI = R->getValueAsDag("OutOperandList"); if (DefInit *Init = dynamic_cast<DefInit*>(OutDI->getOperator())) { if (Init->getDef()->getName() != "outs") throw R->getName() + ": invalid def name for output list: use 'outs'"; } else throw R->getName() + ": invalid output list: use 'outs'"; NumDefs = OutDI->getNumArgs(); DagInit *InDI = R->getValueAsDag("InOperandList"); if (DefInit *Init = dynamic_cast<DefInit*>(InDI->getOperator())) { if (Init->getDef()->getName() != "ins") throw R->getName() + ": invalid def name for input list: use 'ins'"; } else throw R->getName() + ": invalid input list: use 'ins'"; unsigned MIOperandNo = 0; std::set<std::string> OperandNames; for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i){ Init *ArgInit; std::string ArgName; if (i < NumDefs) { ArgInit = OutDI->getArg(i); ArgName = OutDI->getArgName(i); } else { ArgInit = InDI->getArg(i-NumDefs); ArgName = InDI->getArgName(i-NumDefs); } DefInit *Arg = dynamic_cast<DefInit*>(ArgInit); if (!Arg) throw "Illegal operand for the '" + R->getName() + "' instruction!"; Record *Rec = Arg->getDef(); std::string PrintMethod = "printOperand"; unsigned NumOps = 1; DagInit *MIOpInfo = 0; if (Rec->isSubClassOf("Operand")) { PrintMethod = Rec->getValueAsString("PrintMethod"); MIOpInfo = Rec->getValueAsDag("MIOperandInfo"); // Verify that MIOpInfo has an 'ops' root value. if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) || dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ->getDef()->getName() != "ops") throw "Bad value for MIOperandInfo in operand '" + Rec->getName() + "'\n"; // If we have MIOpInfo, then we have #operands equal to number of entries // in MIOperandInfo. if (unsigned NumArgs = MIOpInfo->getNumArgs()) NumOps = NumArgs; if (Rec->isSubClassOf("PredicateOperand")) isPredicable = true; else if (Rec->isSubClassOf("OptionalDefOperand")) hasOptionalDef = true; } else if (Rec->getName() == "variable_ops") { isVariadic = true; continue; } else if (!Rec->isSubClassOf("RegisterClass") && Rec->getName() != "ptr_rc" && Rec->getName() != "unknown") throw "Unknown operand class '" + Rec->getName() + "' in '" + R->getName() + "' instruction!"; // Check that the operand has a name and that it's unique. if (ArgName.empty()) throw "In instruction '" + R->getName() + "', operand #" + utostr(i) + " has no name!"; if (!OperandNames.insert(ArgName).second) throw "In instruction '" + R->getName() + "', operand #" + utostr(i) + " has the same name as a previous operand!"; OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, MIOperandNo, NumOps, MIOpInfo)); MIOperandNo += NumOps; } // Parse Constraints. ParseConstraints(R->getValueAsString("Constraints"), this); // For backward compatibility: isTwoAddress means operand 1 is tied to // operand 0. if (isTwoAddress) { if (!OperandList[1].Constraints[0].isNone()) throw R->getName() + ": cannot use isTwoAddress property: instruction " "already has constraint set!"; OperandList[1].Constraints[0] = CodeGenInstruction::ConstraintInfo::getTied(0); } // Parse the DisableEncoding field. std::string DisableEncoding = R->getValueAsString("DisableEncoding"); while (1) { std::string OpName; tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t"); if (OpName.empty()) break; // Figure out which operand this is. std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false); // Mark the operand as not-to-be encoded. if (Op.second >= OperandList[Op.first].DoNotEncode.size()) OperandList[Op.first].DoNotEncode.resize(Op.second+1); OperandList[Op.first].DoNotEncode[Op.second] = true; } }
/// EmitLeafMatchCode - Generate matching code for leaf nodes. void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) { assert(N->isLeaf() && "Not a leaf?"); // Direct match against an integer constant. if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) { // If this is the root of the dag we're matching, we emit a redundant opcode // check to ensure that this gets folded into the normal top-level // OpcodeSwitch. if (N == Pattern.getSrcPattern()) { const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm")); AddMatcher(new CheckOpcodeMatcher(NI)); } return AddMatcher(new CheckIntegerMatcher(II->getValue())); } DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue()); if (DI == 0) { errs() << "Unknown leaf kind: " << *DI << "\n"; abort(); } Record *LeafRec = DI->getDef(); if (// Handle register references. Nothing to do here, they always match. LeafRec->isSubClassOf("RegisterClass") || LeafRec->isSubClassOf("PointerLikeRegClass") || LeafRec->isSubClassOf("SubRegIndex") || // Place holder for SRCVALUE nodes. Nothing to do here. LeafRec->getName() == "srcvalue") return; // If we have a physreg reference like (mul gpr:$src, EAX) then we need to // record the register if (LeafRec->isSubClassOf("Register")) { AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(), NextRecordedOperandNo)); PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++)); return; } if (LeafRec->isSubClassOf("ValueType")) return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName())); if (LeafRec->isSubClassOf("CondCode")) return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName())); if (LeafRec->isSubClassOf("ComplexPattern")) { // We can't model ComplexPattern uses that don't have their name taken yet. // The OPC_CheckComplexPattern operation implicitly records the results. if (N->getName().empty()) { errs() << "We expect complex pattern uses to have names: " << *N << "\n"; exit(1); } // Remember this ComplexPattern so that we can emit it after all the other // structural matches are done. MatchedComplexPatterns.push_back(std::make_pair(N, 0)); return; } errs() << "Unknown leaf kind: " << *N << "\n"; abort(); }
// Calculate all subregindices for Reg. Loopy subregs cause infinite recursion. RegisterMaps::SubRegMap &RegisterMaps::inferSubRegIndices(Record *Reg) { SubRegMap &SRM = SubReg[Reg]; if (!SRM.empty()) return SRM; std::vector<Record*> SubRegs = Reg->getValueAsListOfDefs("SubRegs"); std::vector<Record*> Indices = Reg->getValueAsListOfDefs("SubRegIndices"); if (SubRegs.size() != Indices.size()) throw "Register " + Reg->getName() + " SubRegIndices doesn't match SubRegs"; // First insert the direct subregs and make sure they are fully indexed. for (unsigned i = 0, e = SubRegs.size(); i != e; ++i) { if (!SRM.insert(std::make_pair(Indices[i], SubRegs[i])).second) throw "SubRegIndex " + Indices[i]->getName() + " appears twice in Register " + Reg->getName(); inferSubRegIndices(SubRegs[i]); } // Keep track of inherited subregs and how they can be reached. // Register -> (SubRegIndex, SubRegIndex) typedef std::map<Record*, std::pair<Record*,Record*>, LessRecord> OrphanMap; OrphanMap Orphans; // Clone inherited subregs. Here the order is important - earlier subregs take // precedence. for (unsigned i = 0, e = SubRegs.size(); i != e; ++i) { SubRegMap &M = SubReg[SubRegs[i]]; for (SubRegMap::iterator si = M.begin(), se = M.end(); si != se; ++si) if (!SRM.insert(*si).second) Orphans[si->second] = std::make_pair(Indices[i], si->first); } // Finally process the composites. ListInit *Comps = Reg->getValueAsListInit("CompositeIndices"); for (unsigned i = 0, e = Comps->size(); i != e; ++i) { DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i)); if (!Pat) throw "Invalid dag '" + Comps->getElement(i)->getAsString() + "' in CompositeIndices"; DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator()); if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex")) throw "Invalid SubClassIndex in " + Pat->getAsString(); // Resolve list of subreg indices into R2. Record *R2 = Reg; for (DagInit::const_arg_iterator di = Pat->arg_begin(), de = Pat->arg_end(); di != de; ++di) { DefInit *IdxInit = dynamic_cast<DefInit*>(*di); if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex")) throw "Invalid SubClassIndex in " + Pat->getAsString(); SubRegMap::const_iterator ni = SubReg[R2].find(IdxInit->getDef()); if (ni == SubReg[R2].end()) throw "Composite " + Pat->getAsString() + " refers to bad index in " + R2->getName(); R2 = ni->second; } // Insert composite index. Allow overriding inherited indices etc. SRM[BaseIdxInit->getDef()] = R2; // R2 is now directly addressable, no longer an orphan. Orphans.erase(R2); } // Now, Orphans contains the inherited subregisters without a direct index. if (!Orphans.empty()) { errs() << "Error: Register " << getQualifiedName(Reg) << " inherited subregisters without an index:\n"; for (OrphanMap::iterator i = Orphans.begin(), e = Orphans.end(); i != e; ++i) { errs() << " " << getQualifiedName(i->first) << " = " << i->second.first->getName() << ", " << i->second.second->getName() << "\n"; } abort(); } return SRM; }
void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) { DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n"); // Validate that the result pattern has the corrent number and types // of arguments for the instruction it references. DagInit *Dag = Rec->getValueAsDag("ResultInst"); assert(Dag && "Missing result instruction in pseudo expansion!"); DEBUG(dbgs() << " Result: " << *Dag << "\n"); DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator()); if (!OpDef) PrintFatalError(Rec->getLoc(), Rec->getName() + " has unexpected operator type!"); Record *Operator = OpDef->getDef(); if (!Operator->isSubClassOf("Instruction")) PrintFatalError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' is not an instruction!"); CodeGenInstruction Insn(Operator); if (Insn.isCodeGenOnly || Insn.isPseudo) PrintFatalError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' cannot be another pseudo instruction!"); if (Insn.Operands.size() != Dag->getNumArgs()) PrintFatalError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' operand count mismatch"); unsigned NumMIOperands = 0; for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) NumMIOperands += Insn.Operands[i].MINumOperands; IndexedMap<OpData> OperandMap; OperandMap.grow(NumMIOperands); addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0); // If there are more operands that weren't in the DAG, they have to // be operands that have default values, or we have an error. Currently, // Operands that are a sublass of OperandWithDefaultOp have default values. // Validate that each result pattern argument has a matching (by name) // argument in the source instruction, in either the (outs) or (ins) list. // Also check that the type of the arguments match. // // Record the mapping of the source to result arguments for use by // the lowering emitter. CodeGenInstruction SourceInsn(Rec); StringMap<unsigned> SourceOperands; for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i) SourceOperands[SourceInsn.Operands[i].Name] = i; DEBUG(dbgs() << " Operand mapping:\n"); for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) { // We've already handled constant values. Just map instruction operands // here. if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand) continue; StringMap<unsigned>::iterator SourceOp = SourceOperands.find(Dag->getArgName(i)); if (SourceOp == SourceOperands.end()) PrintFatalError(Rec->getLoc(), "Pseudo output operand '" + Dag->getArgName(i) + "' has no matching source operand."); // Map the source operand to the destination operand index for each // MachineInstr operand. for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I) OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand = SourceOp->getValue(); DEBUG(dbgs() << " " << SourceOp->getValue() << " ==> " << i << "\n"); } Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap)); }
const CodeGenRegister::SubRegMap & CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) { // Only compute this map once. if (SubRegsComplete) return SubRegs; SubRegsComplete = true; std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs"); std::vector<Record*> IdxList = TheDef->getValueAsListOfDefs("SubRegIndices"); if (SubList.size() != IdxList.size()) throw TGError(TheDef->getLoc(), "Register " + getName() + " SubRegIndices doesn't match SubRegs"); // First insert the direct subregs and make sure they are fully indexed. SmallVector<CodeGenSubRegIndex*, 8> Indices; for (unsigned i = 0, e = SubList.size(); i != e; ++i) { CodeGenRegister *SR = RegBank.getReg(SubList[i]); CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxList[i]); Indices.push_back(Idx); if (!SubRegs.insert(std::make_pair(Idx, SR)).second) throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() + " appears twice in Register " + getName()); } // Keep track of inherited subregs and how they can be reached. SmallPtrSet<CodeGenRegister*, 8> Orphans; // Clone inherited subregs and place duplicate entries in Orphans. // Here the order is important - earlier subregs take precedence. for (unsigned i = 0, e = SubList.size(); i != e; ++i) { CodeGenRegister *SR = RegBank.getReg(SubList[i]); const SubRegMap &Map = SR->getSubRegs(RegBank); // Add this as a super-register of SR now all sub-registers are in the list. // This creates a topological ordering, the exact order depends on the // order getSubRegs is called on all registers. SR->SuperRegs.push_back(this); for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE; ++SI) { if (!SubRegs.insert(*SI).second) Orphans.insert(SI->second); // Noop sub-register indexes are possible, so avoid duplicates. if (SI->second != SR) SI->second->SuperRegs.push_back(this); } } // Expand any composed subreg indices. // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process // expanded subreg indices recursively. for (unsigned i = 0; i != Indices.size(); ++i) { CodeGenSubRegIndex *Idx = Indices[i]; const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites(); CodeGenRegister *SR = SubRegs[Idx]; const SubRegMap &Map = SR->getSubRegs(RegBank); // Look at the possible compositions of Idx. // They may not all be supported by SR. for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(), E = Comps.end(); I != E; ++I) { SubRegMap::const_iterator SRI = Map.find(I->first); if (SRI == Map.end()) continue; // Idx + I->first doesn't exist in SR. // Add I->second as a name for the subreg SRI->second, assuming it is // orphaned, and the name isn't already used for something else. if (SubRegs.count(I->second) || !Orphans.erase(SRI->second)) continue; // We found a new name for the orphaned sub-register. SubRegs.insert(std::make_pair(I->second, SRI->second)); Indices.push_back(I->second); } } // Process the composites. ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices"); for (unsigned i = 0, e = Comps->size(); i != e; ++i) { DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i)); if (!Pat) throw TGError(TheDef->getLoc(), "Invalid dag '" + Comps->getElement(i)->getAsString() + "' in CompositeIndices"); DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator()); if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex")) throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " + Pat->getAsString()); CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef()); // Resolve list of subreg indices into R2. CodeGenRegister *R2 = this; for (DagInit::const_arg_iterator di = Pat->arg_begin(), de = Pat->arg_end(); di != de; ++di) { DefInit *IdxInit = dynamic_cast<DefInit*>(*di); if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex")) throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " + Pat->getAsString()); CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef()); const SubRegMap &R2Subs = R2->getSubRegs(RegBank); SubRegMap::const_iterator ni = R2Subs.find(Idx); if (ni == R2Subs.end()) throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() + " refers to bad index in " + R2->getName()); R2 = ni->second; } // Insert composite index. Allow overriding inherited indices etc. SubRegs[BaseIdx] = R2; // R2 is no longer an orphan. Orphans.erase(R2); } // Now Orphans contains the inherited subregisters without a direct index. // Create inferred indexes for all missing entries. // Work backwards in the Indices vector in order to compose subregs bottom-up. // Consider this subreg sequence: // // qsub_1 -> dsub_0 -> ssub_0 // // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register // can be reached in two different ways: // // qsub_1 -> ssub_0 // dsub_2 -> ssub_0 // // We pick the latter composition because another register may have [dsub_0, // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg. The // dsub_2 -> ssub_0 composition can be shared. while (!Indices.empty() && !Orphans.empty()) { CodeGenSubRegIndex *Idx = Indices.pop_back_val(); CodeGenRegister *SR = SubRegs[Idx]; const SubRegMap &Map = SR->getSubRegs(RegBank); for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE; ++SI) if (Orphans.erase(SI->second)) SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second; } // Initialize RegUnitList. A register with no subregisters creates its own // unit. Otherwise, it inherits all its subregister's units. Because // getSubRegs is called recursively, this processes the register hierarchy in // postorder. // // TODO: We currently assume all register units correspond to a named "leaf" // register. We should also unify register units for ad-hoc register // aliases. This can be done by iteratively merging units for aliasing // registers using a worklist. assert(RegUnits.empty() && "Should only initialize RegUnits once"); if (SubRegs.empty()) { RegUnits.push_back(RegBank.newRegUnit()); } else { for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I) { // Strangely a register may have itself as a subreg (self-cycle) e.g. XMM. CodeGenRegister *SR = I->second; if (SR == this) { if (RegUnits.empty()) RegUnits.push_back(RegBank.newRegUnit()); continue; } // Merge the subregister's units into this register's RegUnits. mergeRegUnits(RegUnits, SR->RegUnits); } } return SubRegs; }