CodeGenInstruction.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the CodeGenInstruction class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenInstruction.h"
  13. #include "CodeGenTarget.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/StringMap.h"
  17. #include "llvm/TableGen/Error.h"
  18. #include "llvm/TableGen/Record.h"
  19. #include <set>
  20. using namespace llvm;
  21. //===----------------------------------------------------------------------===//
  22. // CGIOperandList Implementation
  23. //===----------------------------------------------------------------------===//
  24. CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
  25. isPredicable = false;
  26. hasOptionalDef = false;
  27. isVariadic = false;
  28. DagInit *OutDI = R->getValueAsDag("OutOperandList");
  29. if (DefInit *Init = dyn_cast<DefInit>(OutDI->getOperator())) {
  30. if (Init->getDef()->getName() != "outs")
  31. PrintFatalError(R->getLoc(),
  32. R->getName() +
  33. ": invalid def name for output list: use 'outs'");
  34. } else
  35. PrintFatalError(R->getLoc(),
  36. R->getName() + ": invalid output list: use 'outs'");
  37. NumDefs = OutDI->getNumArgs();
  38. DagInit *InDI = R->getValueAsDag("InOperandList");
  39. if (DefInit *Init = dyn_cast<DefInit>(InDI->getOperator())) {
  40. if (Init->getDef()->getName() != "ins")
  41. PrintFatalError(R->getLoc(),
  42. R->getName() +
  43. ": invalid def name for input list: use 'ins'");
  44. } else
  45. PrintFatalError(R->getLoc(),
  46. R->getName() + ": invalid input list: use 'ins'");
  47. unsigned MIOperandNo = 0;
  48. std::set<std::string> OperandNames;
  49. unsigned e = InDI->getNumArgs() + OutDI->getNumArgs();
  50. OperandList.reserve(e);
  51. bool VariadicOuts = false;
  52. for (unsigned i = 0; i != e; ++i){
  53. Init *ArgInit;
  54. StringRef ArgName;
  55. if (i < NumDefs) {
  56. ArgInit = OutDI->getArg(i);
  57. ArgName = OutDI->getArgNameStr(i);
  58. } else {
  59. ArgInit = InDI->getArg(i-NumDefs);
  60. ArgName = InDI->getArgNameStr(i-NumDefs);
  61. }
  62. DefInit *Arg = dyn_cast<DefInit>(ArgInit);
  63. if (!Arg)
  64. PrintFatalError(R->getLoc(), "Illegal operand for the '" + R->getName() +
  65. "' instruction!");
  66. Record *Rec = Arg->getDef();
  67. std::string PrintMethod = "printOperand";
  68. std::string EncoderMethod;
  69. std::string OperandType = "OPERAND_UNKNOWN";
  70. std::string OperandNamespace = "MCOI";
  71. unsigned NumOps = 1;
  72. DagInit *MIOpInfo = nullptr;
  73. if (Rec->isSubClassOf("RegisterOperand")) {
  74. PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
  75. OperandType = std::string(Rec->getValueAsString("OperandType"));
  76. OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
  77. EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
  78. } else if (Rec->isSubClassOf("Operand")) {
  79. PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
  80. OperandType = std::string(Rec->getValueAsString("OperandType"));
  81. OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
  82. // If there is an explicit encoder method, use it.
  83. EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
  84. MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
  85. // Verify that MIOpInfo has an 'ops' root value.
  86. if (!isa<DefInit>(MIOpInfo->getOperator()) ||
  87. cast<DefInit>(MIOpInfo->getOperator())->getDef()->getName() != "ops")
  88. PrintFatalError(R->getLoc(),
  89. "Bad value for MIOperandInfo in operand '" +
  90. Rec->getName() + "'\n");
  91. // If we have MIOpInfo, then we have #operands equal to number of entries
  92. // in MIOperandInfo.
  93. if (unsigned NumArgs = MIOpInfo->getNumArgs())
  94. NumOps = NumArgs;
  95. if (Rec->isSubClassOf("PredicateOp"))
  96. isPredicable = true;
  97. else if (Rec->isSubClassOf("OptionalDefOperand"))
  98. hasOptionalDef = true;
  99. } else if (Rec->getName() == "variable_ops") {
  100. if (i < NumDefs)
  101. VariadicOuts = true;
  102. isVariadic = true;
  103. continue;
  104. } else if (Rec->isSubClassOf("RegisterClass")) {
  105. OperandType = "OPERAND_REGISTER";
  106. } else if (!Rec->isSubClassOf("PointerLikeRegClass") &&
  107. !Rec->isSubClassOf("unknown_class"))
  108. PrintFatalError(R->getLoc(), "Unknown operand class '" + Rec->getName() +
  109. "' in '" + R->getName() +
  110. "' instruction!");
  111. // Check that the operand has a name and that it's unique.
  112. if (ArgName.empty())
  113. PrintFatalError(R->getLoc(), "In instruction '" + R->getName() +
  114. "', operand #" + Twine(i) +
  115. " has no name!");
  116. if (!OperandNames.insert(std::string(ArgName)).second)
  117. PrintFatalError(R->getLoc(),
  118. "In instruction '" + R->getName() + "', operand #" +
  119. Twine(i) +
  120. " has the same name as a previous operand!");
  121. OperandList.emplace_back(
  122. Rec, std::string(ArgName), std::string(PrintMethod),
  123. std::string(EncoderMethod), OperandNamespace + "::" + OperandType,
  124. MIOperandNo, NumOps, MIOpInfo);
  125. MIOperandNo += NumOps;
  126. }
  127. if (VariadicOuts)
  128. --NumDefs;
  129. // Make sure the constraints list for each operand is large enough to hold
  130. // constraint info, even if none is present.
  131. for (OperandInfo &OpInfo : OperandList)
  132. OpInfo.Constraints.resize(OpInfo.MINumOperands);
  133. }
  134. /// getOperandNamed - Return the index of the operand with the specified
  135. /// non-empty name. If the instruction does not have an operand with the
  136. /// specified name, abort.
  137. ///
  138. unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
  139. unsigned OpIdx;
  140. if (hasOperandNamed(Name, OpIdx))
  141. return OpIdx;
  142. PrintFatalError(TheDef->getLoc(), "'" + TheDef->getName() +
  143. "' does not have an operand named '$" +
  144. Name + "'!");
  145. }
  146. /// hasOperandNamed - Query whether the instruction has an operand of the
  147. /// given name. If so, return true and set OpIdx to the index of the
  148. /// operand. Otherwise, return false.
  149. bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
  150. assert(!Name.empty() && "Cannot search for operand with no name!");
  151. for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
  152. if (OperandList[i].Name == Name) {
  153. OpIdx = i;
  154. return true;
  155. }
  156. return false;
  157. }
  158. std::pair<unsigned,unsigned>
  159. CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) {
  160. if (Op.empty() || Op[0] != '$')
  161. PrintFatalError(TheDef->getLoc(),
  162. TheDef->getName() + ": Illegal operand name: '" + Op + "'");
  163. std::string OpName = Op.substr(1);
  164. std::string SubOpName;
  165. // Check to see if this is $foo.bar.
  166. std::string::size_type DotIdx = OpName.find_first_of('.');
  167. if (DotIdx != std::string::npos) {
  168. SubOpName = OpName.substr(DotIdx+1);
  169. if (SubOpName.empty())
  170. PrintFatalError(TheDef->getLoc(),
  171. TheDef->getName() +
  172. ": illegal empty suboperand name in '" + Op + "'");
  173. OpName = OpName.substr(0, DotIdx);
  174. }
  175. unsigned OpIdx = getOperandNamed(OpName);
  176. if (SubOpName.empty()) { // If no suboperand name was specified:
  177. // If one was needed, throw.
  178. if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
  179. SubOpName.empty())
  180. PrintFatalError(TheDef->getLoc(),
  181. TheDef->getName() +
  182. ": Illegal to refer to"
  183. " whole operand part of complex operand '" +
  184. Op + "'");
  185. // Otherwise, return the operand.
  186. return std::make_pair(OpIdx, 0U);
  187. }
  188. // Find the suboperand number involved.
  189. DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
  190. if (!MIOpInfo)
  191. PrintFatalError(TheDef->getLoc(), TheDef->getName() +
  192. ": unknown suboperand name in '" +
  193. Op + "'");
  194. // Find the operand with the right name.
  195. for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
  196. if (MIOpInfo->getArgNameStr(i) == SubOpName)
  197. return std::make_pair(OpIdx, i);
  198. // Otherwise, didn't find it!
  199. PrintFatalError(TheDef->getLoc(), TheDef->getName() +
  200. ": unknown suboperand name in '" + Op +
  201. "'");
  202. return std::make_pair(0U, 0U);
  203. }
  204. static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops,
  205. Record *Rec) {
  206. // EARLY_CLOBBER: @early $reg
  207. std::string::size_type wpos = CStr.find_first_of(" \t");
  208. std::string::size_type start = CStr.find_first_not_of(" \t");
  209. std::string Tok = CStr.substr(start, wpos - start);
  210. if (Tok == "@earlyclobber") {
  211. std::string Name = CStr.substr(wpos+1);
  212. wpos = Name.find_first_not_of(" \t");
  213. if (wpos == std::string::npos)
  214. PrintFatalError(
  215. Rec->getLoc(), "Illegal format for @earlyclobber constraint in '" +
  216. Rec->getName() + "': '" + CStr + "'");
  217. Name = Name.substr(wpos);
  218. std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
  219. // Build the string for the operand
  220. if (!Ops[Op.first].Constraints[Op.second].isNone())
  221. PrintFatalError(
  222. Rec->getLoc(), "Operand '" + Name + "' of '" + Rec->getName() +
  223. "' cannot have multiple constraints!");
  224. Ops[Op.first].Constraints[Op.second] =
  225. CGIOperandList::ConstraintInfo::getEarlyClobber();
  226. return;
  227. }
  228. // Only other constraint is "TIED_TO" for now.
  229. std::string::size_type pos = CStr.find_first_of('=');
  230. if (pos == std::string::npos)
  231. PrintFatalError(
  232. Rec->getLoc(), "Unrecognized constraint '" + CStr +
  233. "' in '" + Rec->getName() + "'");
  234. start = CStr.find_first_not_of(" \t");
  235. // TIED_TO: $src1 = $dst
  236. wpos = CStr.find_first_of(" \t", start);
  237. if (wpos == std::string::npos || wpos > pos)
  238. PrintFatalError(
  239. Rec->getLoc(), "Illegal format for tied-to constraint in '" +
  240. Rec->getName() + "': '" + CStr + "'");
  241. std::string LHSOpName =
  242. std::string(StringRef(CStr).substr(start, wpos - start));
  243. std::pair<unsigned,unsigned> LHSOp = Ops.ParseOperandName(LHSOpName, false);
  244. wpos = CStr.find_first_not_of(" \t", pos + 1);
  245. if (wpos == std::string::npos)
  246. PrintFatalError(
  247. Rec->getLoc(), "Illegal format for tied-to constraint: '" + CStr + "'");
  248. std::string RHSOpName = std::string(StringRef(CStr).substr(wpos));
  249. std::pair<unsigned,unsigned> RHSOp = Ops.ParseOperandName(RHSOpName, false);
  250. // Sort the operands into order, which should put the output one
  251. // first. But keep the original order, for use in diagnostics.
  252. bool FirstIsDest = (LHSOp < RHSOp);
  253. std::pair<unsigned,unsigned> DestOp = (FirstIsDest ? LHSOp : RHSOp);
  254. StringRef DestOpName = (FirstIsDest ? LHSOpName : RHSOpName);
  255. std::pair<unsigned,unsigned> SrcOp = (FirstIsDest ? RHSOp : LHSOp);
  256. StringRef SrcOpName = (FirstIsDest ? RHSOpName : LHSOpName);
  257. // Ensure one operand is a def and the other is a use.
  258. if (DestOp.first >= Ops.NumDefs)
  259. PrintFatalError(
  260. Rec->getLoc(), "Input operands '" + LHSOpName + "' and '" + RHSOpName +
  261. "' of '" + Rec->getName() + "' cannot be tied!");
  262. if (SrcOp.first < Ops.NumDefs)
  263. PrintFatalError(
  264. Rec->getLoc(), "Output operands '" + LHSOpName + "' and '" + RHSOpName +
  265. "' of '" + Rec->getName() + "' cannot be tied!");
  266. // The constraint has to go on the operand with higher index, i.e.
  267. // the source one. Check there isn't another constraint there
  268. // already.
  269. if (!Ops[SrcOp.first].Constraints[SrcOp.second].isNone())
  270. PrintFatalError(
  271. Rec->getLoc(), "Operand '" + SrcOpName + "' of '" + Rec->getName() +
  272. "' cannot have multiple constraints!");
  273. unsigned DestFlatOpNo = Ops.getFlattenedOperandNumber(DestOp);
  274. auto NewConstraint = CGIOperandList::ConstraintInfo::getTied(DestFlatOpNo);
  275. // Check that the earlier operand is not the target of another tie
  276. // before making it the target of this one.
  277. for (const CGIOperandList::OperandInfo &Op : Ops) {
  278. for (unsigned i = 0; i < Op.MINumOperands; i++)
  279. if (Op.Constraints[i] == NewConstraint)
  280. PrintFatalError(
  281. Rec->getLoc(), "Operand '" + DestOpName + "' of '" + Rec->getName() +
  282. "' cannot have multiple operands tied to it!");
  283. }
  284. Ops[SrcOp.first].Constraints[SrcOp.second] = NewConstraint;
  285. }
  286. static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops,
  287. Record *Rec) {
  288. if (CStr.empty()) return;
  289. const std::string delims(",");
  290. std::string::size_type bidx, eidx;
  291. bidx = CStr.find_first_not_of(delims);
  292. while (bidx != std::string::npos) {
  293. eidx = CStr.find_first_of(delims, bidx);
  294. if (eidx == std::string::npos)
  295. eidx = CStr.length();
  296. ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops, Rec);
  297. bidx = CStr.find_first_not_of(delims, eidx);
  298. }
  299. }
  300. void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
  301. while (1) {
  302. std::pair<StringRef, StringRef> P = getToken(DisableEncoding, " ,\t");
  303. std::string OpName = std::string(P.first);
  304. DisableEncoding = std::string(P.second);
  305. if (OpName.empty()) break;
  306. // Figure out which operand this is.
  307. std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
  308. // Mark the operand as not-to-be encoded.
  309. if (Op.second >= OperandList[Op.first].DoNotEncode.size())
  310. OperandList[Op.first].DoNotEncode.resize(Op.second+1);
  311. OperandList[Op.first].DoNotEncode[Op.second] = true;
  312. }
  313. }
  314. //===----------------------------------------------------------------------===//
  315. // CodeGenInstruction Implementation
  316. //===----------------------------------------------------------------------===//
  317. CodeGenInstruction::CodeGenInstruction(Record *R)
  318. : TheDef(R), Operands(R), InferredFrom(nullptr) {
  319. Namespace = R->getValueAsString("Namespace");
  320. AsmString = std::string(R->getValueAsString("AsmString"));
  321. isPreISelOpcode = R->getValueAsBit("isPreISelOpcode");
  322. isReturn = R->getValueAsBit("isReturn");
  323. isEHScopeReturn = R->getValueAsBit("isEHScopeReturn");
  324. isBranch = R->getValueAsBit("isBranch");
  325. isIndirectBranch = R->getValueAsBit("isIndirectBranch");
  326. isCompare = R->getValueAsBit("isCompare");
  327. isMoveImm = R->getValueAsBit("isMoveImm");
  328. isMoveReg = R->getValueAsBit("isMoveReg");
  329. isBitcast = R->getValueAsBit("isBitcast");
  330. isSelect = R->getValueAsBit("isSelect");
  331. isBarrier = R->getValueAsBit("isBarrier");
  332. isCall = R->getValueAsBit("isCall");
  333. isAdd = R->getValueAsBit("isAdd");
  334. isTrap = R->getValueAsBit("isTrap");
  335. canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
  336. isPredicable = !R->getValueAsBit("isUnpredicable") && (
  337. Operands.isPredicable || R->getValueAsBit("isPredicable"));
  338. isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
  339. isCommutable = R->getValueAsBit("isCommutable");
  340. isTerminator = R->getValueAsBit("isTerminator");
  341. isReMaterializable = R->getValueAsBit("isReMaterializable");
  342. hasDelaySlot = R->getValueAsBit("hasDelaySlot");
  343. usesCustomInserter = R->getValueAsBit("usesCustomInserter");
  344. hasPostISelHook = R->getValueAsBit("hasPostISelHook");
  345. hasCtrlDep = R->getValueAsBit("hasCtrlDep");
  346. isNotDuplicable = R->getValueAsBit("isNotDuplicable");
  347. isRegSequence = R->getValueAsBit("isRegSequence");
  348. isExtractSubreg = R->getValueAsBit("isExtractSubreg");
  349. isInsertSubreg = R->getValueAsBit("isInsertSubreg");
  350. isConvergent = R->getValueAsBit("isConvergent");
  351. hasNoSchedulingInfo = R->getValueAsBit("hasNoSchedulingInfo");
  352. FastISelShouldIgnore = R->getValueAsBit("FastISelShouldIgnore");
  353. variadicOpsAreDefs = R->getValueAsBit("variadicOpsAreDefs");
  354. isAuthenticated = R->getValueAsBit("isAuthenticated");
  355. bool Unset;
  356. mayLoad = R->getValueAsBitOrUnset("mayLoad", Unset);
  357. mayLoad_Unset = Unset;
  358. mayStore = R->getValueAsBitOrUnset("mayStore", Unset);
  359. mayStore_Unset = Unset;
  360. mayRaiseFPException = R->getValueAsBit("mayRaiseFPException");
  361. hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects", Unset);
  362. hasSideEffects_Unset = Unset;
  363. isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
  364. hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
  365. hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
  366. isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
  367. isPseudo = R->getValueAsBit("isPseudo");
  368. ImplicitDefs = R->getValueAsListOfDefs("Defs");
  369. ImplicitUses = R->getValueAsListOfDefs("Uses");
  370. // This flag is only inferred from the pattern.
  371. hasChain = false;
  372. hasChain_Inferred = false;
  373. // Parse Constraints.
  374. ParseConstraints(std::string(R->getValueAsString("Constraints")), Operands,
  375. R);
  376. // Parse the DisableEncoding field.
  377. Operands.ProcessDisableEncoding(
  378. std::string(R->getValueAsString("DisableEncoding")));
  379. // First check for a ComplexDeprecationPredicate.
  380. if (R->getValue("ComplexDeprecationPredicate")) {
  381. HasComplexDeprecationPredicate = true;
  382. DeprecatedReason =
  383. std::string(R->getValueAsString("ComplexDeprecationPredicate"));
  384. } else if (RecordVal *Dep = R->getValue("DeprecatedFeatureMask")) {
  385. // Check if we have a Subtarget feature mask.
  386. HasComplexDeprecationPredicate = false;
  387. DeprecatedReason = Dep->getValue()->getAsString();
  388. } else {
  389. // This instruction isn't deprecated.
  390. HasComplexDeprecationPredicate = false;
  391. DeprecatedReason = "";
  392. }
  393. }
  394. /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
  395. /// implicit def and it has a known VT, return the VT, otherwise return
  396. /// MVT::Other.
  397. MVT::SimpleValueType CodeGenInstruction::
  398. HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
  399. if (ImplicitDefs.empty()) return MVT::Other;
  400. // Check to see if the first implicit def has a resolvable type.
  401. Record *FirstImplicitDef = ImplicitDefs[0];
  402. assert(FirstImplicitDef->isSubClassOf("Register"));
  403. const std::vector<ValueTypeByHwMode> &RegVTs =
  404. TargetInfo.getRegisterVTs(FirstImplicitDef);
  405. if (RegVTs.size() == 1 && RegVTs[0].isSimple())
  406. return RegVTs[0].getSimple().SimpleTy;
  407. return MVT::Other;
  408. }
  409. /// FlattenAsmStringVariants - Flatten the specified AsmString to only
  410. /// include text from the specified variant, returning the new string.
  411. std::string CodeGenInstruction::
  412. FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
  413. std::string Res;
  414. for (;;) {
  415. // Find the start of the next variant string.
  416. size_t VariantsStart = 0;
  417. for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
  418. if (Cur[VariantsStart] == '{' &&
  419. (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
  420. Cur[VariantsStart-1] != '\\')))
  421. break;
  422. // Add the prefix to the result.
  423. Res += Cur.slice(0, VariantsStart);
  424. if (VariantsStart == Cur.size())
  425. break;
  426. ++VariantsStart; // Skip the '{'.
  427. // Scan to the end of the variants string.
  428. size_t VariantsEnd = VariantsStart;
  429. unsigned NestedBraces = 1;
  430. for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
  431. if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
  432. if (--NestedBraces == 0)
  433. break;
  434. } else if (Cur[VariantsEnd] == '{')
  435. ++NestedBraces;
  436. }
  437. // Select the Nth variant (or empty).
  438. StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
  439. for (unsigned i = 0; i != Variant; ++i)
  440. Selection = Selection.split('|').second;
  441. Res += Selection.split('|').first;
  442. assert(VariantsEnd != Cur.size() &&
  443. "Unterminated variants in assembly string!");
  444. Cur = Cur.substr(VariantsEnd + 1);
  445. }
  446. return Res;
  447. }
  448. bool CodeGenInstruction::isOperandImpl(unsigned i,
  449. StringRef PropertyName) const {
  450. DagInit *ConstraintList = TheDef->getValueAsDag("InOperandList");
  451. if (!ConstraintList || i >= ConstraintList->getNumArgs())
  452. return false;
  453. DefInit *Constraint = dyn_cast<DefInit>(ConstraintList->getArg(i));
  454. if (!Constraint)
  455. return false;
  456. return Constraint->getDef()->isSubClassOf("TypedOperand") &&
  457. Constraint->getDef()->getValueAsBit(PropertyName);
  458. }
  459. //===----------------------------------------------------------------------===//
  460. /// CodeGenInstAlias Implementation
  461. //===----------------------------------------------------------------------===//
  462. /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
  463. /// constructor. It checks if an argument in an InstAlias pattern matches
  464. /// the corresponding operand of the instruction. It returns true on a
  465. /// successful match, with ResOp set to the result operand to be used.
  466. bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
  467. Record *InstOpRec, bool hasSubOps,
  468. ArrayRef<SMLoc> Loc, CodeGenTarget &T,
  469. ResultOperand &ResOp) {
  470. Init *Arg = Result->getArg(AliasOpNo);
  471. DefInit *ADI = dyn_cast<DefInit>(Arg);
  472. Record *ResultRecord = ADI ? ADI->getDef() : nullptr;
  473. if (ADI && ADI->getDef() == InstOpRec) {
  474. // If the operand is a record, it must have a name, and the record type
  475. // must match up with the instruction's argument type.
  476. if (!Result->getArgName(AliasOpNo))
  477. PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
  478. " must have a name!");
  479. ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
  480. ResultRecord);
  481. return true;
  482. }
  483. // For register operands, the source register class can be a subclass
  484. // of the instruction register class, not just an exact match.
  485. if (InstOpRec->isSubClassOf("RegisterOperand"))
  486. InstOpRec = InstOpRec->getValueAsDef("RegClass");
  487. if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
  488. ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();
  489. if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
  490. if (!InstOpRec->isSubClassOf("RegisterClass"))
  491. return false;
  492. if (!T.getRegisterClass(InstOpRec)
  493. .hasSubClass(&T.getRegisterClass(ADI->getDef())))
  494. return false;
  495. ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
  496. ResultRecord);
  497. return true;
  498. }
  499. // Handle explicit registers.
  500. if (ADI && ADI->getDef()->isSubClassOf("Register")) {
  501. if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
  502. DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
  503. // The operand info should only have a single (register) entry. We
  504. // want the register class of it.
  505. InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
  506. }
  507. if (!InstOpRec->isSubClassOf("RegisterClass"))
  508. return false;
  509. if (!T.getRegisterClass(InstOpRec)
  510. .contains(T.getRegBank().getReg(ADI->getDef())))
  511. PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
  512. " is not a member of the " + InstOpRec->getName() +
  513. " register class!");
  514. if (Result->getArgName(AliasOpNo))
  515. PrintFatalError(Loc, "result fixed register argument must "
  516. "not have a name!");
  517. ResOp = ResultOperand(ResultRecord);
  518. return true;
  519. }
  520. // Handle "zero_reg" for optional def operands.
  521. if (ADI && ADI->getDef()->getName() == "zero_reg") {
  522. // Check if this is an optional def.
  523. // Tied operands where the source is a sub-operand of a complex operand
  524. // need to represent both operands in the alias destination instruction.
  525. // Allow zero_reg for the tied portion. This can and should go away once
  526. // the MC representation of things doesn't use tied operands at all.
  527. //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
  528. // throw TGError(Loc, "reg0 used for result that is not an "
  529. // "OptionalDefOperand!");
  530. ResOp = ResultOperand(static_cast<Record*>(nullptr));
  531. return true;
  532. }
  533. // Literal integers.
  534. if (IntInit *II = dyn_cast<IntInit>(Arg)) {
  535. if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
  536. return false;
  537. // Integer arguments can't have names.
  538. if (Result->getArgName(AliasOpNo))
  539. PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
  540. " must not have a name!");
  541. ResOp = ResultOperand(II->getValue());
  542. return true;
  543. }
  544. // Bits<n> (also used for 0bxx literals)
  545. if (BitsInit *BI = dyn_cast<BitsInit>(Arg)) {
  546. if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
  547. return false;
  548. if (!BI->isComplete())
  549. return false;
  550. // Convert the bits init to an integer and use that for the result.
  551. IntInit *II =
  552. dyn_cast_or_null<IntInit>(BI->convertInitializerTo(IntRecTy::get()));
  553. if (!II)
  554. return false;
  555. ResOp = ResultOperand(II->getValue());
  556. return true;
  557. }
  558. // If both are Operands with the same MVT, allow the conversion. It's
  559. // up to the user to make sure the values are appropriate, just like
  560. // for isel Pat's.
  561. if (InstOpRec->isSubClassOf("Operand") && ADI &&
  562. ADI->getDef()->isSubClassOf("Operand")) {
  563. // FIXME: What other attributes should we check here? Identical
  564. // MIOperandInfo perhaps?
  565. if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
  566. return false;
  567. ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
  568. ADI->getDef());
  569. return true;
  570. }
  571. return false;
  572. }
  573. unsigned CodeGenInstAlias::ResultOperand::getMINumOperands() const {
  574. if (!isRecord())
  575. return 1;
  576. Record *Rec = getRecord();
  577. if (!Rec->isSubClassOf("Operand"))
  578. return 1;
  579. DagInit *MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
  580. if (MIOpInfo->getNumArgs() == 0) {
  581. // Unspecified, so it defaults to 1
  582. return 1;
  583. }
  584. return MIOpInfo->getNumArgs();
  585. }
  586. CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T)
  587. : TheDef(R) {
  588. Result = R->getValueAsDag("ResultInst");
  589. AsmString = std::string(R->getValueAsString("AsmString"));
  590. // Verify that the root of the result is an instruction.
  591. DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
  592. if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
  593. PrintFatalError(R->getLoc(),
  594. "result of inst alias should be an instruction");
  595. ResultInst = &T.getInstruction(DI->getDef());
  596. // NameClass - If argument names are repeated, we need to verify they have
  597. // the same class.
  598. StringMap<Record*> NameClass;
  599. for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
  600. DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
  601. if (!ADI || !Result->getArgName(i))
  602. continue;
  603. // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
  604. // $foo can exist multiple times in the result list, but it must have the
  605. // same type.
  606. Record *&Entry = NameClass[Result->getArgNameStr(i)];
  607. if (Entry && Entry != ADI->getDef())
  608. PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) +
  609. " is both " + Entry->getName() + " and " +
  610. ADI->getDef()->getName() + "!");
  611. Entry = ADI->getDef();
  612. }
  613. // Decode and validate the arguments of the result.
  614. unsigned AliasOpNo = 0;
  615. for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
  616. // Tied registers don't have an entry in the result dag unless they're part
  617. // of a complex operand, in which case we include them anyways, as we
  618. // don't have any other way to specify the whole operand.
  619. if (ResultInst->Operands[i].MINumOperands == 1 &&
  620. ResultInst->Operands[i].getTiedRegister() != -1) {
  621. // Tied operands of different RegisterClass should be explicit within an
  622. // instruction's syntax and so cannot be skipped.
  623. int TiedOpNum = ResultInst->Operands[i].getTiedRegister();
  624. if (ResultInst->Operands[i].Rec->getName() ==
  625. ResultInst->Operands[TiedOpNum].Rec->getName())
  626. continue;
  627. }
  628. if (AliasOpNo >= Result->getNumArgs())
  629. PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
  630. Record *InstOpRec = ResultInst->Operands[i].Rec;
  631. unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
  632. ResultOperand ResOp(static_cast<int64_t>(0));
  633. if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
  634. R->getLoc(), T, ResOp)) {
  635. // If this is a simple operand, or a complex operand with a custom match
  636. // class, then we can match is verbatim.
  637. if (NumSubOps == 1 ||
  638. (InstOpRec->getValue("ParserMatchClass") &&
  639. InstOpRec->getValueAsDef("ParserMatchClass")
  640. ->getValueAsString("Name") != "Imm")) {
  641. ResultOperands.push_back(ResOp);
  642. ResultInstOperandIndex.push_back(std::make_pair(i, -1));
  643. ++AliasOpNo;
  644. // Otherwise, we need to match each of the suboperands individually.
  645. } else {
  646. DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
  647. for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
  648. Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
  649. // Take care to instantiate each of the suboperands with the correct
  650. // nomenclature: $foo.bar
  651. ResultOperands.emplace_back(
  652. Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." +
  653. MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec);
  654. ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
  655. }
  656. ++AliasOpNo;
  657. }
  658. continue;
  659. }
  660. // If the argument did not match the instruction operand, and the operand
  661. // is composed of multiple suboperands, try matching the suboperands.
  662. if (NumSubOps > 1) {
  663. DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
  664. for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
  665. if (AliasOpNo >= Result->getNumArgs())
  666. PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
  667. Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
  668. if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
  669. R->getLoc(), T, ResOp)) {
  670. ResultOperands.push_back(ResOp);
  671. ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
  672. ++AliasOpNo;
  673. } else {
  674. PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
  675. " does not match instruction operand class " +
  676. (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
  677. }
  678. }
  679. continue;
  680. }
  681. PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
  682. " does not match instruction operand class " +
  683. InstOpRec->getName());
  684. }
  685. if (AliasOpNo != Result->getNumArgs())
  686. PrintFatalError(R->getLoc(), "too many operands for instruction!");
  687. }