CodeGenInstruction.cpp 33 KB

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