PageRenderTime 77ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/3rd_party/llvm/utils/TableGen/CodeGenDAGPatterns.cpp

https://code.google.com/p/softart/
C++ | 3598 lines | 2441 code | 551 blank | 606 comment | 992 complexity | 50d18ca4d9763c33a656f73137f5068a MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, JSON, MPL-2.0-no-copyleft-exception, GPL-2.0, GPL-3.0, LGPL-3.0, BSD-2-Clause
  1. //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the CodeGenDAGPatterns class, which is used to read and
  11. // represent the patterns present in a .td file for instructions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenDAGPatterns.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/TableGen/Error.h"
  21. #include "llvm/TableGen/Record.h"
  22. #include <algorithm>
  23. #include <cstdio>
  24. #include <set>
  25. using namespace llvm;
  26. //===----------------------------------------------------------------------===//
  27. // EEVT::TypeSet Implementation
  28. //===----------------------------------------------------------------------===//
  29. static inline bool isInteger(MVT::SimpleValueType VT) {
  30. return MVT(VT).isInteger();
  31. }
  32. static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
  33. return MVT(VT).isFloatingPoint();
  34. }
  35. static inline bool isVector(MVT::SimpleValueType VT) {
  36. return MVT(VT).isVector();
  37. }
  38. static inline bool isScalar(MVT::SimpleValueType VT) {
  39. return !MVT(VT).isVector();
  40. }
  41. EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
  42. if (VT == MVT::iAny)
  43. EnforceInteger(TP);
  44. else if (VT == MVT::fAny)
  45. EnforceFloatingPoint(TP);
  46. else if (VT == MVT::vAny)
  47. EnforceVector(TP);
  48. else {
  49. assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
  50. VT == MVT::iPTRAny) && "Not a concrete type!");
  51. TypeVec.push_back(VT);
  52. }
  53. }
  54. EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
  55. assert(!VTList.empty() && "empty list?");
  56. TypeVec.append(VTList.begin(), VTList.end());
  57. if (!VTList.empty())
  58. assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
  59. VTList[0] != MVT::fAny);
  60. // Verify no duplicates.
  61. array_pod_sort(TypeVec.begin(), TypeVec.end());
  62. assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
  63. }
  64. /// FillWithPossibleTypes - Set to all legal types and return true, only valid
  65. /// on completely unknown type sets.
  66. bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
  67. bool (*Pred)(MVT::SimpleValueType),
  68. const char *PredicateName) {
  69. assert(isCompletelyUnknown());
  70. ArrayRef<MVT::SimpleValueType> LegalTypes =
  71. TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
  72. if (TP.hasError())
  73. return false;
  74. for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
  75. if (Pred == 0 || Pred(LegalTypes[i]))
  76. TypeVec.push_back(LegalTypes[i]);
  77. // If we have nothing that matches the predicate, bail out.
  78. if (TypeVec.empty()) {
  79. TP.error("Type inference contradiction found, no " +
  80. std::string(PredicateName) + " types found");
  81. return false;
  82. }
  83. // No need to sort with one element.
  84. if (TypeVec.size() == 1) return true;
  85. // Remove duplicates.
  86. array_pod_sort(TypeVec.begin(), TypeVec.end());
  87. TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
  88. return true;
  89. }
  90. /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
  91. /// integer value type.
  92. bool EEVT::TypeSet::hasIntegerTypes() const {
  93. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  94. if (isInteger(TypeVec[i]))
  95. return true;
  96. return false;
  97. }
  98. /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
  99. /// a floating point value type.
  100. bool EEVT::TypeSet::hasFloatingPointTypes() const {
  101. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  102. if (isFloatingPoint(TypeVec[i]))
  103. return true;
  104. return false;
  105. }
  106. /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
  107. /// value type.
  108. bool EEVT::TypeSet::hasVectorTypes() const {
  109. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  110. if (isVector(TypeVec[i]))
  111. return true;
  112. return false;
  113. }
  114. std::string EEVT::TypeSet::getName() const {
  115. if (TypeVec.empty()) return "<empty>";
  116. std::string Result;
  117. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
  118. std::string VTName = llvm::getEnumName(TypeVec[i]);
  119. // Strip off MVT:: prefix if present.
  120. if (VTName.substr(0,5) == "MVT::")
  121. VTName = VTName.substr(5);
  122. if (i) Result += ':';
  123. Result += VTName;
  124. }
  125. if (TypeVec.size() == 1)
  126. return Result;
  127. return "{" + Result + "}";
  128. }
  129. /// MergeInTypeInfo - This merges in type information from the specified
  130. /// argument. If 'this' changes, it returns true. If the two types are
  131. /// contradictory (e.g. merge f32 into i32) then this flags an error.
  132. bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
  133. if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
  134. return false;
  135. if (isCompletelyUnknown()) {
  136. *this = InVT;
  137. return true;
  138. }
  139. assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
  140. // Handle the abstract cases, seeing if we can resolve them better.
  141. switch (TypeVec[0]) {
  142. default: break;
  143. case MVT::iPTR:
  144. case MVT::iPTRAny:
  145. if (InVT.hasIntegerTypes()) {
  146. EEVT::TypeSet InCopy(InVT);
  147. InCopy.EnforceInteger(TP);
  148. InCopy.EnforceScalar(TP);
  149. if (InCopy.isConcrete()) {
  150. // If the RHS has one integer type, upgrade iPTR to i32.
  151. TypeVec[0] = InVT.TypeVec[0];
  152. return true;
  153. }
  154. // If the input has multiple scalar integers, this doesn't add any info.
  155. if (!InCopy.isCompletelyUnknown())
  156. return false;
  157. }
  158. break;
  159. }
  160. // If the input constraint is iAny/iPTR and this is an integer type list,
  161. // remove non-integer types from the list.
  162. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  163. hasIntegerTypes()) {
  164. bool MadeChange = EnforceInteger(TP);
  165. // If we're merging in iPTR/iPTRAny and the node currently has a list of
  166. // multiple different integer types, replace them with a single iPTR.
  167. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  168. TypeVec.size() != 1) {
  169. TypeVec.resize(1);
  170. TypeVec[0] = InVT.TypeVec[0];
  171. MadeChange = true;
  172. }
  173. return MadeChange;
  174. }
  175. // If this is a type list and the RHS is a typelist as well, eliminate entries
  176. // from this list that aren't in the other one.
  177. bool MadeChange = false;
  178. TypeSet InputSet(*this);
  179. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  180. bool InInVT = false;
  181. for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
  182. if (TypeVec[i] == InVT.TypeVec[j]) {
  183. InInVT = true;
  184. break;
  185. }
  186. if (InInVT) continue;
  187. TypeVec.erase(TypeVec.begin()+i--);
  188. MadeChange = true;
  189. }
  190. // If we removed all of our types, we have a type contradiction.
  191. if (!TypeVec.empty())
  192. return MadeChange;
  193. // FIXME: Really want an SMLoc here!
  194. TP.error("Type inference contradiction found, merging '" +
  195. InVT.getName() + "' into '" + InputSet.getName() + "'");
  196. return false;
  197. }
  198. /// EnforceInteger - Remove all non-integer types from this set.
  199. bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
  200. if (TP.hasError())
  201. return false;
  202. // If we know nothing, then get the full set.
  203. if (TypeVec.empty())
  204. return FillWithPossibleTypes(TP, isInteger, "integer");
  205. if (!hasFloatingPointTypes())
  206. return false;
  207. TypeSet InputSet(*this);
  208. // Filter out all the fp types.
  209. for (unsigned i = 0; i != TypeVec.size(); ++i)
  210. if (!isInteger(TypeVec[i]))
  211. TypeVec.erase(TypeVec.begin()+i--);
  212. if (TypeVec.empty()) {
  213. TP.error("Type inference contradiction found, '" +
  214. InputSet.getName() + "' needs to be integer");
  215. return false;
  216. }
  217. return true;
  218. }
  219. /// EnforceFloatingPoint - Remove all integer types from this set.
  220. bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
  221. if (TP.hasError())
  222. return false;
  223. // If we know nothing, then get the full set.
  224. if (TypeVec.empty())
  225. return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
  226. if (!hasIntegerTypes())
  227. return false;
  228. TypeSet InputSet(*this);
  229. // Filter out all the fp types.
  230. for (unsigned i = 0; i != TypeVec.size(); ++i)
  231. if (!isFloatingPoint(TypeVec[i]))
  232. TypeVec.erase(TypeVec.begin()+i--);
  233. if (TypeVec.empty()) {
  234. TP.error("Type inference contradiction found, '" +
  235. InputSet.getName() + "' needs to be floating point");
  236. return false;
  237. }
  238. return true;
  239. }
  240. /// EnforceScalar - Remove all vector types from this.
  241. bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
  242. if (TP.hasError())
  243. return false;
  244. // If we know nothing, then get the full set.
  245. if (TypeVec.empty())
  246. return FillWithPossibleTypes(TP, isScalar, "scalar");
  247. if (!hasVectorTypes())
  248. return false;
  249. TypeSet InputSet(*this);
  250. // Filter out all the vector types.
  251. for (unsigned i = 0; i != TypeVec.size(); ++i)
  252. if (!isScalar(TypeVec[i]))
  253. TypeVec.erase(TypeVec.begin()+i--);
  254. if (TypeVec.empty()) {
  255. TP.error("Type inference contradiction found, '" +
  256. InputSet.getName() + "' needs to be scalar");
  257. return false;
  258. }
  259. return true;
  260. }
  261. /// EnforceVector - Remove all vector types from this.
  262. bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
  263. if (TP.hasError())
  264. return false;
  265. // If we know nothing, then get the full set.
  266. if (TypeVec.empty())
  267. return FillWithPossibleTypes(TP, isVector, "vector");
  268. TypeSet InputSet(*this);
  269. bool MadeChange = false;
  270. // Filter out all the scalar types.
  271. for (unsigned i = 0; i != TypeVec.size(); ++i)
  272. if (!isVector(TypeVec[i])) {
  273. TypeVec.erase(TypeVec.begin()+i--);
  274. MadeChange = true;
  275. }
  276. if (TypeVec.empty()) {
  277. TP.error("Type inference contradiction found, '" +
  278. InputSet.getName() + "' needs to be a vector");
  279. return false;
  280. }
  281. return MadeChange;
  282. }
  283. /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
  284. /// this an other based on this information.
  285. bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
  286. if (TP.hasError())
  287. return false;
  288. // Both operands must be integer or FP, but we don't care which.
  289. bool MadeChange = false;
  290. if (isCompletelyUnknown())
  291. MadeChange = FillWithPossibleTypes(TP);
  292. if (Other.isCompletelyUnknown())
  293. MadeChange = Other.FillWithPossibleTypes(TP);
  294. // If one side is known to be integer or known to be FP but the other side has
  295. // no information, get at least the type integrality info in there.
  296. if (!hasFloatingPointTypes())
  297. MadeChange |= Other.EnforceInteger(TP);
  298. else if (!hasIntegerTypes())
  299. MadeChange |= Other.EnforceFloatingPoint(TP);
  300. if (!Other.hasFloatingPointTypes())
  301. MadeChange |= EnforceInteger(TP);
  302. else if (!Other.hasIntegerTypes())
  303. MadeChange |= EnforceFloatingPoint(TP);
  304. assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
  305. "Should have a type list now");
  306. // If one contains vectors but the other doesn't pull vectors out.
  307. if (!hasVectorTypes())
  308. MadeChange |= Other.EnforceScalar(TP);
  309. if (!hasVectorTypes())
  310. MadeChange |= EnforceScalar(TP);
  311. if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
  312. // If we are down to concrete types, this code does not currently
  313. // handle nodes which have multiple types, where some types are
  314. // integer, and some are fp. Assert that this is not the case.
  315. assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
  316. !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
  317. "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
  318. // Otherwise, if these are both vector types, either this vector
  319. // must have a larger bitsize than the other, or this element type
  320. // must be larger than the other.
  321. MVT Type(TypeVec[0]);
  322. MVT OtherType(Other.TypeVec[0]);
  323. if (hasVectorTypes() && Other.hasVectorTypes()) {
  324. if (Type.getSizeInBits() >= OtherType.getSizeInBits())
  325. if (Type.getVectorElementType().getSizeInBits()
  326. >= OtherType.getVectorElementType().getSizeInBits()) {
  327. TP.error("Type inference contradiction found, '" +
  328. getName() + "' element type not smaller than '" +
  329. Other.getName() +"'!");
  330. return false;
  331. }
  332. } else
  333. // For scalar types, the bitsize of this type must be larger
  334. // than that of the other.
  335. if (Type.getSizeInBits() >= OtherType.getSizeInBits()) {
  336. TP.error("Type inference contradiction found, '" +
  337. getName() + "' is not smaller than '" +
  338. Other.getName() +"'!");
  339. return false;
  340. }
  341. }
  342. // Handle int and fp as disjoint sets. This won't work for patterns
  343. // that have mixed fp/int types but those are likely rare and would
  344. // not have been accepted by this code previously.
  345. // Okay, find the smallest type from the current set and remove it from the
  346. // largest set.
  347. MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
  348. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  349. if (isInteger(TypeVec[i])) {
  350. SmallestInt = TypeVec[i];
  351. break;
  352. }
  353. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  354. if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
  355. SmallestInt = TypeVec[i];
  356. MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
  357. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  358. if (isFloatingPoint(TypeVec[i])) {
  359. SmallestFP = TypeVec[i];
  360. break;
  361. }
  362. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  363. if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
  364. SmallestFP = TypeVec[i];
  365. int OtherIntSize = 0;
  366. int OtherFPSize = 0;
  367. for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
  368. Other.TypeVec.begin();
  369. TVI != Other.TypeVec.end();
  370. /* NULL */) {
  371. if (isInteger(*TVI)) {
  372. ++OtherIntSize;
  373. if (*TVI == SmallestInt) {
  374. TVI = Other.TypeVec.erase(TVI);
  375. --OtherIntSize;
  376. MadeChange = true;
  377. continue;
  378. }
  379. } else if (isFloatingPoint(*TVI)) {
  380. ++OtherFPSize;
  381. if (*TVI == SmallestFP) {
  382. TVI = Other.TypeVec.erase(TVI);
  383. --OtherFPSize;
  384. MadeChange = true;
  385. continue;
  386. }
  387. }
  388. ++TVI;
  389. }
  390. // If this is the only type in the large set, the constraint can never be
  391. // satisfied.
  392. if ((Other.hasIntegerTypes() && OtherIntSize == 0) ||
  393. (Other.hasFloatingPointTypes() && OtherFPSize == 0)) {
  394. TP.error("Type inference contradiction found, '" +
  395. Other.getName() + "' has nothing larger than '" + getName() +"'!");
  396. return false;
  397. }
  398. // Okay, find the largest type in the Other set and remove it from the
  399. // current set.
  400. MVT::SimpleValueType LargestInt = MVT::Other;
  401. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  402. if (isInteger(Other.TypeVec[i])) {
  403. LargestInt = Other.TypeVec[i];
  404. break;
  405. }
  406. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  407. if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
  408. LargestInt = Other.TypeVec[i];
  409. MVT::SimpleValueType LargestFP = MVT::Other;
  410. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  411. if (isFloatingPoint(Other.TypeVec[i])) {
  412. LargestFP = Other.TypeVec[i];
  413. break;
  414. }
  415. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  416. if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
  417. LargestFP = Other.TypeVec[i];
  418. int IntSize = 0;
  419. int FPSize = 0;
  420. for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
  421. TypeVec.begin();
  422. TVI != TypeVec.end();
  423. /* NULL */) {
  424. if (isInteger(*TVI)) {
  425. ++IntSize;
  426. if (*TVI == LargestInt) {
  427. TVI = TypeVec.erase(TVI);
  428. --IntSize;
  429. MadeChange = true;
  430. continue;
  431. }
  432. } else if (isFloatingPoint(*TVI)) {
  433. ++FPSize;
  434. if (*TVI == LargestFP) {
  435. TVI = TypeVec.erase(TVI);
  436. --FPSize;
  437. MadeChange = true;
  438. continue;
  439. }
  440. }
  441. ++TVI;
  442. }
  443. // If this is the only type in the small set, the constraint can never be
  444. // satisfied.
  445. if ((hasIntegerTypes() && IntSize == 0) ||
  446. (hasFloatingPointTypes() && FPSize == 0)) {
  447. TP.error("Type inference contradiction found, '" +
  448. getName() + "' has nothing smaller than '" + Other.getName()+"'!");
  449. return false;
  450. }
  451. return MadeChange;
  452. }
  453. /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
  454. /// whose element is specified by VTOperand.
  455. bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
  456. TreePattern &TP) {
  457. if (TP.hasError())
  458. return false;
  459. // "This" must be a vector and "VTOperand" must be a scalar.
  460. bool MadeChange = false;
  461. MadeChange |= EnforceVector(TP);
  462. MadeChange |= VTOperand.EnforceScalar(TP);
  463. // If we know the vector type, it forces the scalar to agree.
  464. if (isConcrete()) {
  465. MVT IVT = getConcrete();
  466. IVT = IVT.getVectorElementType();
  467. return MadeChange |
  468. VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
  469. }
  470. // If the scalar type is known, filter out vector types whose element types
  471. // disagree.
  472. if (!VTOperand.isConcrete())
  473. return MadeChange;
  474. MVT::SimpleValueType VT = VTOperand.getConcrete();
  475. TypeSet InputSet(*this);
  476. // Filter out all the types which don't have the right element type.
  477. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  478. assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
  479. if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
  480. TypeVec.erase(TypeVec.begin()+i--);
  481. MadeChange = true;
  482. }
  483. }
  484. if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
  485. TP.error("Type inference contradiction found, forcing '" +
  486. InputSet.getName() + "' to have a vector element");
  487. return false;
  488. }
  489. return MadeChange;
  490. }
  491. /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
  492. /// vector type specified by VTOperand.
  493. bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
  494. TreePattern &TP) {
  495. // "This" must be a vector and "VTOperand" must be a vector.
  496. bool MadeChange = false;
  497. MadeChange |= EnforceVector(TP);
  498. MadeChange |= VTOperand.EnforceVector(TP);
  499. // "This" must be larger than "VTOperand."
  500. MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
  501. // If we know the vector type, it forces the scalar types to agree.
  502. if (isConcrete()) {
  503. MVT IVT = getConcrete();
  504. IVT = IVT.getVectorElementType();
  505. EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
  506. MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
  507. } else if (VTOperand.isConcrete()) {
  508. MVT IVT = VTOperand.getConcrete();
  509. IVT = IVT.getVectorElementType();
  510. EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
  511. MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
  512. }
  513. return MadeChange;
  514. }
  515. //===----------------------------------------------------------------------===//
  516. // Helpers for working with extended types.
  517. /// Dependent variable map for CodeGenDAGPattern variant generation
  518. typedef std::map<std::string, int> DepVarMap;
  519. /// Const iterator shorthand for DepVarMap
  520. typedef DepVarMap::const_iterator DepVarMap_citer;
  521. static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
  522. if (N->isLeaf()) {
  523. if (isa<DefInit>(N->getLeafValue()))
  524. DepMap[N->getName()]++;
  525. } else {
  526. for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
  527. FindDepVarsOf(N->getChild(i), DepMap);
  528. }
  529. }
  530. /// Find dependent variables within child patterns
  531. static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
  532. DepVarMap depcounts;
  533. FindDepVarsOf(N, depcounts);
  534. for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
  535. if (i->second > 1) // std::pair<std::string, int>
  536. DepVars.insert(i->first);
  537. }
  538. }
  539. #ifndef NDEBUG
  540. /// Dump the dependent variable set:
  541. static void DumpDepVars(MultipleUseVarSet &DepVars) {
  542. if (DepVars.empty()) {
  543. DEBUG(errs() << "<empty set>");
  544. } else {
  545. DEBUG(errs() << "[ ");
  546. for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
  547. e = DepVars.end(); i != e; ++i) {
  548. DEBUG(errs() << (*i) << " ");
  549. }
  550. DEBUG(errs() << "]");
  551. }
  552. }
  553. #endif
  554. //===----------------------------------------------------------------------===//
  555. // TreePredicateFn Implementation
  556. //===----------------------------------------------------------------------===//
  557. /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
  558. TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
  559. assert((getPredCode().empty() || getImmCode().empty()) &&
  560. ".td file corrupt: can't have a node predicate *and* an imm predicate");
  561. }
  562. std::string TreePredicateFn::getPredCode() const {
  563. return PatFragRec->getRecord()->getValueAsString("PredicateCode");
  564. }
  565. std::string TreePredicateFn::getImmCode() const {
  566. return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
  567. }
  568. /// isAlwaysTrue - Return true if this is a noop predicate.
  569. bool TreePredicateFn::isAlwaysTrue() const {
  570. return getPredCode().empty() && getImmCode().empty();
  571. }
  572. /// Return the name to use in the generated code to reference this, this is
  573. /// "Predicate_foo" if from a pattern fragment "foo".
  574. std::string TreePredicateFn::getFnName() const {
  575. return "Predicate_" + PatFragRec->getRecord()->getName();
  576. }
  577. /// getCodeToRunOnSDNode - Return the code for the function body that
  578. /// evaluates this predicate. The argument is expected to be in "Node",
  579. /// not N. This handles casting and conversion to a concrete node type as
  580. /// appropriate.
  581. std::string TreePredicateFn::getCodeToRunOnSDNode() const {
  582. // Handle immediate predicates first.
  583. std::string ImmCode = getImmCode();
  584. if (!ImmCode.empty()) {
  585. std::string Result =
  586. " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
  587. return Result + ImmCode;
  588. }
  589. // Handle arbitrary node predicates.
  590. assert(!getPredCode().empty() && "Don't have any predicate code!");
  591. std::string ClassName;
  592. if (PatFragRec->getOnlyTree()->isLeaf())
  593. ClassName = "SDNode";
  594. else {
  595. Record *Op = PatFragRec->getOnlyTree()->getOperator();
  596. ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
  597. }
  598. std::string Result;
  599. if (ClassName == "SDNode")
  600. Result = " SDNode *N = Node;\n";
  601. else
  602. Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
  603. return Result + getPredCode();
  604. }
  605. //===----------------------------------------------------------------------===//
  606. // PatternToMatch implementation
  607. //
  608. /// getPatternSize - Return the 'size' of this pattern. We want to match large
  609. /// patterns before small ones. This is used to determine the size of a
  610. /// pattern.
  611. static unsigned getPatternSize(const TreePatternNode *P,
  612. const CodeGenDAGPatterns &CGP) {
  613. unsigned Size = 3; // The node itself.
  614. // If the root node is a ConstantSDNode, increases its size.
  615. // e.g. (set R32:$dst, 0).
  616. if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
  617. Size += 2;
  618. // FIXME: This is a hack to statically increase the priority of patterns
  619. // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
  620. // Later we can allow complexity / cost for each pattern to be (optionally)
  621. // specified. To get best possible pattern match we'll need to dynamically
  622. // calculate the complexity of all patterns a dag can potentially map to.
  623. const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
  624. if (AM)
  625. Size += AM->getNumOperands() * 3;
  626. // If this node has some predicate function that must match, it adds to the
  627. // complexity of this node.
  628. if (!P->getPredicateFns().empty())
  629. ++Size;
  630. // Count children in the count if they are also nodes.
  631. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
  632. TreePatternNode *Child = P->getChild(i);
  633. if (!Child->isLeaf() && Child->getNumTypes() &&
  634. Child->getType(0) != MVT::Other)
  635. Size += getPatternSize(Child, CGP);
  636. else if (Child->isLeaf()) {
  637. if (isa<IntInit>(Child->getLeafValue()))
  638. Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
  639. else if (Child->getComplexPatternInfo(CGP))
  640. Size += getPatternSize(Child, CGP);
  641. else if (!Child->getPredicateFns().empty())
  642. ++Size;
  643. }
  644. }
  645. return Size;
  646. }
  647. /// Compute the complexity metric for the input pattern. This roughly
  648. /// corresponds to the number of nodes that are covered.
  649. unsigned PatternToMatch::
  650. getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
  651. return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
  652. }
  653. /// getPredicateCheck - Return a single string containing all of this
  654. /// pattern's predicates concatenated with "&&" operators.
  655. ///
  656. std::string PatternToMatch::getPredicateCheck() const {
  657. std::string PredicateCheck;
  658. for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
  659. if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
  660. Record *Def = Pred->getDef();
  661. if (!Def->isSubClassOf("Predicate")) {
  662. #ifndef NDEBUG
  663. Def->dump();
  664. #endif
  665. llvm_unreachable("Unknown predicate type!");
  666. }
  667. if (!PredicateCheck.empty())
  668. PredicateCheck += " && ";
  669. PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
  670. }
  671. }
  672. return PredicateCheck;
  673. }
  674. //===----------------------------------------------------------------------===//
  675. // SDTypeConstraint implementation
  676. //
  677. SDTypeConstraint::SDTypeConstraint(Record *R) {
  678. OperandNo = R->getValueAsInt("OperandNum");
  679. if (R->isSubClassOf("SDTCisVT")) {
  680. ConstraintType = SDTCisVT;
  681. x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
  682. if (x.SDTCisVT_Info.VT == MVT::isVoid)
  683. PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
  684. } else if (R->isSubClassOf("SDTCisPtrTy")) {
  685. ConstraintType = SDTCisPtrTy;
  686. } else if (R->isSubClassOf("SDTCisInt")) {
  687. ConstraintType = SDTCisInt;
  688. } else if (R->isSubClassOf("SDTCisFP")) {
  689. ConstraintType = SDTCisFP;
  690. } else if (R->isSubClassOf("SDTCisVec")) {
  691. ConstraintType = SDTCisVec;
  692. } else if (R->isSubClassOf("SDTCisSameAs")) {
  693. ConstraintType = SDTCisSameAs;
  694. x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
  695. } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
  696. ConstraintType = SDTCisVTSmallerThanOp;
  697. x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
  698. R->getValueAsInt("OtherOperandNum");
  699. } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
  700. ConstraintType = SDTCisOpSmallerThanOp;
  701. x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
  702. R->getValueAsInt("BigOperandNum");
  703. } else if (R->isSubClassOf("SDTCisEltOfVec")) {
  704. ConstraintType = SDTCisEltOfVec;
  705. x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
  706. } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
  707. ConstraintType = SDTCisSubVecOfVec;
  708. x.SDTCisSubVecOfVec_Info.OtherOperandNum =
  709. R->getValueAsInt("OtherOpNum");
  710. } else {
  711. errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
  712. exit(1);
  713. }
  714. }
  715. /// getOperandNum - Return the node corresponding to operand #OpNo in tree
  716. /// N, and the result number in ResNo.
  717. static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
  718. const SDNodeInfo &NodeInfo,
  719. unsigned &ResNo) {
  720. unsigned NumResults = NodeInfo.getNumResults();
  721. if (OpNo < NumResults) {
  722. ResNo = OpNo;
  723. return N;
  724. }
  725. OpNo -= NumResults;
  726. if (OpNo >= N->getNumChildren()) {
  727. errs() << "Invalid operand number in type constraint "
  728. << (OpNo+NumResults) << " ";
  729. N->dump();
  730. errs() << '\n';
  731. exit(1);
  732. }
  733. return N->getChild(OpNo);
  734. }
  735. /// ApplyTypeConstraint - Given a node in a pattern, apply this type
  736. /// constraint to the nodes operands. This returns true if it makes a
  737. /// change, false otherwise. If a type contradiction is found, flag an error.
  738. bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
  739. const SDNodeInfo &NodeInfo,
  740. TreePattern &TP) const {
  741. if (TP.hasError())
  742. return false;
  743. unsigned ResNo = 0; // The result number being referenced.
  744. TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
  745. switch (ConstraintType) {
  746. case SDTCisVT:
  747. // Operand must be a particular type.
  748. return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
  749. case SDTCisPtrTy:
  750. // Operand must be same as target pointer type.
  751. return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
  752. case SDTCisInt:
  753. // Require it to be one of the legal integer VTs.
  754. return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
  755. case SDTCisFP:
  756. // Require it to be one of the legal fp VTs.
  757. return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
  758. case SDTCisVec:
  759. // Require it to be one of the legal vector VTs.
  760. return NodeToApply->getExtType(ResNo).EnforceVector(TP);
  761. case SDTCisSameAs: {
  762. unsigned OResNo = 0;
  763. TreePatternNode *OtherNode =
  764. getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
  765. return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
  766. OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
  767. }
  768. case SDTCisVTSmallerThanOp: {
  769. // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
  770. // have an integer type that is smaller than the VT.
  771. if (!NodeToApply->isLeaf() ||
  772. !isa<DefInit>(NodeToApply->getLeafValue()) ||
  773. !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
  774. ->isSubClassOf("ValueType")) {
  775. TP.error(N->getOperator()->getName() + " expects a VT operand!");
  776. return false;
  777. }
  778. MVT::SimpleValueType VT =
  779. getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
  780. EEVT::TypeSet TypeListTmp(VT, TP);
  781. unsigned OResNo = 0;
  782. TreePatternNode *OtherNode =
  783. getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
  784. OResNo);
  785. return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
  786. }
  787. case SDTCisOpSmallerThanOp: {
  788. unsigned BResNo = 0;
  789. TreePatternNode *BigOperand =
  790. getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
  791. BResNo);
  792. return NodeToApply->getExtType(ResNo).
  793. EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
  794. }
  795. case SDTCisEltOfVec: {
  796. unsigned VResNo = 0;
  797. TreePatternNode *VecOperand =
  798. getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
  799. VResNo);
  800. // Filter vector types out of VecOperand that don't have the right element
  801. // type.
  802. return VecOperand->getExtType(VResNo).
  803. EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
  804. }
  805. case SDTCisSubVecOfVec: {
  806. unsigned VResNo = 0;
  807. TreePatternNode *BigVecOperand =
  808. getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
  809. VResNo);
  810. // Filter vector types out of BigVecOperand that don't have the
  811. // right subvector type.
  812. return BigVecOperand->getExtType(VResNo).
  813. EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
  814. }
  815. }
  816. llvm_unreachable("Invalid ConstraintType!");
  817. }
  818. // Update the node type to match an instruction operand or result as specified
  819. // in the ins or outs lists on the instruction definition. Return true if the
  820. // type was actually changed.
  821. bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
  822. Record *Operand,
  823. TreePattern &TP) {
  824. // The 'unknown' operand indicates that types should be inferred from the
  825. // context.
  826. if (Operand->isSubClassOf("unknown_class"))
  827. return false;
  828. // The Operand class specifies a type directly.
  829. if (Operand->isSubClassOf("Operand"))
  830. return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
  831. TP);
  832. // PointerLikeRegClass has a type that is determined at runtime.
  833. if (Operand->isSubClassOf("PointerLikeRegClass"))
  834. return UpdateNodeType(ResNo, MVT::iPTR, TP);
  835. // Both RegisterClass and RegisterOperand operands derive their types from a
  836. // register class def.
  837. Record *RC = 0;
  838. if (Operand->isSubClassOf("RegisterClass"))
  839. RC = Operand;
  840. else if (Operand->isSubClassOf("RegisterOperand"))
  841. RC = Operand->getValueAsDef("RegClass");
  842. assert(RC && "Unknown operand type");
  843. CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
  844. return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
  845. }
  846. //===----------------------------------------------------------------------===//
  847. // SDNodeInfo implementation
  848. //
  849. SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
  850. EnumName = R->getValueAsString("Opcode");
  851. SDClassName = R->getValueAsString("SDClass");
  852. Record *TypeProfile = R->getValueAsDef("TypeProfile");
  853. NumResults = TypeProfile->getValueAsInt("NumResults");
  854. NumOperands = TypeProfile->getValueAsInt("NumOperands");
  855. // Parse the properties.
  856. Properties = 0;
  857. std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
  858. for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
  859. if (PropList[i]->getName() == "SDNPCommutative") {
  860. Properties |= 1 << SDNPCommutative;
  861. } else if (PropList[i]->getName() == "SDNPAssociative") {
  862. Properties |= 1 << SDNPAssociative;
  863. } else if (PropList[i]->getName() == "SDNPHasChain") {
  864. Properties |= 1 << SDNPHasChain;
  865. } else if (PropList[i]->getName() == "SDNPOutGlue") {
  866. Properties |= 1 << SDNPOutGlue;
  867. } else if (PropList[i]->getName() == "SDNPInGlue") {
  868. Properties |= 1 << SDNPInGlue;
  869. } else if (PropList[i]->getName() == "SDNPOptInGlue") {
  870. Properties |= 1 << SDNPOptInGlue;
  871. } else if (PropList[i]->getName() == "SDNPMayStore") {
  872. Properties |= 1 << SDNPMayStore;
  873. } else if (PropList[i]->getName() == "SDNPMayLoad") {
  874. Properties |= 1 << SDNPMayLoad;
  875. } else if (PropList[i]->getName() == "SDNPSideEffect") {
  876. Properties |= 1 << SDNPSideEffect;
  877. } else if (PropList[i]->getName() == "SDNPMemOperand") {
  878. Properties |= 1 << SDNPMemOperand;
  879. } else if (PropList[i]->getName() == "SDNPVariadic") {
  880. Properties |= 1 << SDNPVariadic;
  881. } else {
  882. errs() << "Unknown SD Node property '" << PropList[i]->getName()
  883. << "' on node '" << R->getName() << "'!\n";
  884. exit(1);
  885. }
  886. }
  887. // Parse the type constraints.
  888. std::vector<Record*> ConstraintList =
  889. TypeProfile->getValueAsListOfDefs("Constraints");
  890. TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
  891. }
  892. /// getKnownType - If the type constraints on this node imply a fixed type
  893. /// (e.g. all stores return void, etc), then return it as an
  894. /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
  895. MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
  896. unsigned NumResults = getNumResults();
  897. assert(NumResults <= 1 &&
  898. "We only work with nodes with zero or one result so far!");
  899. assert(ResNo == 0 && "Only handles single result nodes so far");
  900. for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
  901. // Make sure that this applies to the correct node result.
  902. if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
  903. continue;
  904. switch (TypeConstraints[i].ConstraintType) {
  905. default: break;
  906. case SDTypeConstraint::SDTCisVT:
  907. return TypeConstraints[i].x.SDTCisVT_Info.VT;
  908. case SDTypeConstraint::SDTCisPtrTy:
  909. return MVT::iPTR;
  910. }
  911. }
  912. return MVT::Other;
  913. }
  914. //===----------------------------------------------------------------------===//
  915. // TreePatternNode implementation
  916. //
  917. TreePatternNode::~TreePatternNode() {
  918. #if 0 // FIXME: implement refcounted tree nodes!
  919. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  920. delete getChild(i);
  921. #endif
  922. }
  923. static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
  924. if (Operator->getName() == "set" ||
  925. Operator->getName() == "implicit")
  926. return 0; // All return nothing.
  927. if (Operator->isSubClassOf("Intrinsic"))
  928. return CDP.getIntrinsic(Operator).IS.RetVTs.size();
  929. if (Operator->isSubClassOf("SDNode"))
  930. return CDP.getSDNodeInfo(Operator).getNumResults();
  931. if (Operator->isSubClassOf("PatFrag")) {
  932. // If we've already parsed this pattern fragment, get it. Otherwise, handle
  933. // the forward reference case where one pattern fragment references another
  934. // before it is processed.
  935. if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
  936. return PFRec->getOnlyTree()->getNumTypes();
  937. // Get the result tree.
  938. DagInit *Tree = Operator->getValueAsDag("Fragment");
  939. Record *Op = 0;
  940. if (Tree)
  941. if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
  942. Op = DI->getDef();
  943. assert(Op && "Invalid Fragment");
  944. return GetNumNodeResults(Op, CDP);
  945. }
  946. if (Operator->isSubClassOf("Instruction")) {
  947. CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
  948. // FIXME: Should allow access to all the results here.
  949. unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
  950. // Add on one implicit def if it has a resolvable type.
  951. if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
  952. ++NumDefsToAdd;
  953. return NumDefsToAdd;
  954. }
  955. if (Operator->isSubClassOf("SDNodeXForm"))
  956. return 1; // FIXME: Generalize SDNodeXForm
  957. Operator->dump();
  958. errs() << "Unhandled node in GetNumNodeResults\n";
  959. exit(1);
  960. }
  961. void TreePatternNode::print(raw_ostream &OS) const {
  962. if (isLeaf())
  963. OS << *getLeafValue();
  964. else
  965. OS << '(' << getOperator()->getName();
  966. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  967. OS << ':' << getExtType(i).getName();
  968. if (!isLeaf()) {
  969. if (getNumChildren() != 0) {
  970. OS << " ";
  971. getChild(0)->print(OS);
  972. for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
  973. OS << ", ";
  974. getChild(i)->print(OS);
  975. }
  976. }
  977. OS << ")";
  978. }
  979. for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
  980. OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
  981. if (TransformFn)
  982. OS << "<<X:" << TransformFn->getName() << ">>";
  983. if (!getName().empty())
  984. OS << ":$" << getName();
  985. }
  986. void TreePatternNode::dump() const {
  987. print(errs());
  988. }
  989. /// isIsomorphicTo - Return true if this node is recursively
  990. /// isomorphic to the specified node. For this comparison, the node's
  991. /// entire state is considered. The assigned name is ignored, since
  992. /// nodes with differing names are considered isomorphic. However, if
  993. /// the assigned name is present in the dependent variable set, then
  994. /// the assigned name is considered significant and the node is
  995. /// isomorphic if the names match.
  996. bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
  997. const MultipleUseVarSet &DepVars) const {
  998. if (N == this) return true;
  999. if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
  1000. getPredicateFns() != N->getPredicateFns() ||
  1001. getTransformFn() != N->getTransformFn())
  1002. return false;
  1003. if (isLeaf()) {
  1004. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  1005. if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
  1006. return ((DI->getDef() == NDI->getDef())
  1007. && (DepVars.find(getName()) == DepVars.end()
  1008. || getName() == N->getName()));
  1009. }
  1010. }
  1011. return getLeafValue() == N->getLeafValue();
  1012. }
  1013. if (N->getOperator() != getOperator() ||
  1014. N->getNumChildren() != getNumChildren()) return false;
  1015. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1016. if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
  1017. return false;
  1018. return true;
  1019. }
  1020. /// clone - Make a copy of this tree and all of its children.
  1021. ///
  1022. TreePatternNode *TreePatternNode::clone() const {
  1023. TreePatternNode *New;
  1024. if (isLeaf()) {
  1025. New = new TreePatternNode(getLeafValue(), getNumTypes());
  1026. } else {
  1027. std::vector<TreePatternNode*> CChildren;
  1028. CChildren.reserve(Children.size());
  1029. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1030. CChildren.push_back(getChild(i)->clone());
  1031. New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
  1032. }
  1033. New->setName(getName());
  1034. New->Types = Types;
  1035. New->setPredicateFns(getPredicateFns());
  1036. New->setTransformFn(getTransformFn());
  1037. return New;
  1038. }
  1039. /// RemoveAllTypes - Recursively strip all the types of this tree.
  1040. void TreePatternNode::RemoveAllTypes() {
  1041. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1042. Types[i] = EEVT::TypeSet(); // Reset to unknown type.
  1043. if (isLeaf()) return;
  1044. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1045. getChild(i)->RemoveAllTypes();
  1046. }
  1047. /// SubstituteFormalArguments - Replace the formal arguments in this tree
  1048. /// with actual values specified by ArgMap.
  1049. void TreePatternNode::
  1050. SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
  1051. if (isLeaf()) return;
  1052. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1053. TreePatternNode *Child = getChild(i);
  1054. if (Child->isLeaf()) {
  1055. Init *Val = Child->getLeafValue();
  1056. if (isa<DefInit>(Val) &&
  1057. cast<DefInit>(Val)->getDef()->getName() == "node") {
  1058. // We found a use of a formal argument, replace it with its value.
  1059. TreePatternNode *NewChild = ArgMap[Child->getName()];
  1060. assert(NewChild && "Couldn't find formal argument!");
  1061. assert((Child->getPredicateFns().empty() ||
  1062. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1063. "Non-empty child predicate clobbered!");
  1064. setChild(i, NewChild);
  1065. }
  1066. } else {
  1067. getChild(i)->SubstituteFormalArguments(ArgMap);
  1068. }
  1069. }
  1070. }
  1071. /// InlinePatternFragments - If this pattern refers to any pattern
  1072. /// fragments, inline them into place, giving us a pattern without any
  1073. /// PatFrag references.
  1074. TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
  1075. if (TP.hasError())
  1076. return 0;
  1077. if (isLeaf())
  1078. return this; // nothing to do.
  1079. Record *Op = getOperator();
  1080. if (!Op->isSubClassOf("PatFrag")) {
  1081. // Just recursively inline children nodes.
  1082. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1083. TreePatternNode *Child = getChild(i);
  1084. TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
  1085. assert((Child->getPredicateFns().empty() ||
  1086. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1087. "Non-empty child predicate clobbered!");
  1088. setChild(i, NewChild);
  1089. }
  1090. return this;
  1091. }
  1092. // Otherwise, we found a reference to a fragment. First, look up its
  1093. // TreePattern record.
  1094. TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
  1095. // Verify that we are passing the right number of operands.
  1096. if (Frag->getNumArgs() != Children.size()) {
  1097. TP.error("'" + Op->getName() + "' fragment requires " +
  1098. utostr(Frag->getNumArgs()) + " operands!");
  1099. return 0;
  1100. }
  1101. TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
  1102. TreePredicateFn PredFn(Frag);
  1103. if (!PredFn.isAlwaysTrue())
  1104. FragTree->addPredicateFn(PredFn);
  1105. // Resolve formal arguments to their actual value.
  1106. if (Frag->getNumArgs()) {
  1107. // Compute the map of formal to actual arguments.
  1108. std::map<std::string, TreePatternNode*> ArgMap;
  1109. for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
  1110. ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
  1111. FragTree->SubstituteFormalArguments(ArgMap);
  1112. }
  1113. FragTree->setName(getName());
  1114. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1115. FragTree->UpdateNodeType(i, getExtType(i), TP);
  1116. // Transfer in the old predicates.
  1117. for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
  1118. FragTree->addPredicateFn(getPredicateFns()[i]);
  1119. // Get a new copy of this fragment to stitch into here.
  1120. //delete this; // FIXME: implement refcounting!
  1121. // The fragment we inlined could have recursive inlining that is needed. See
  1122. // if there are any pattern fragments in it and inline them as needed.
  1123. return FragTree->InlinePatternFragments(TP);
  1124. }
  1125. /// getImplicitType - Check to see if the specified record has an implicit
  1126. /// type which should be applied to it. This will infer the type of register
  1127. /// references from the register file information, for example.
  1128. ///
  1129. /// When Unnamed is set, return the type of a DAG operand with no name, such as
  1130. /// the F8RC register class argument in:
  1131. ///
  1132. /// (COPY_TO_REGCLASS GPR:$src, F8RC)
  1133. ///
  1134. /// When Unnamed is false, return the type of a named DAG operand such as the
  1135. /// GPR:$src operand above.
  1136. ///
  1137. static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
  1138. bool NotRegisters,
  1139. bool Unnamed,
  1140. TreePattern &TP) {
  1141. // Check to see if this is a register operand.
  1142. if (R->isSubClassOf("RegisterOperand")) {
  1143. assert(ResNo == 0 && "Regoperand ref only has one result!");
  1144. if (NotRegisters)
  1145. return EEVT::TypeSet(); // Unknown.
  1146. Record *RegClass = R->getValueAsDef("RegClass");
  1147. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1148. return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
  1149. }
  1150. // Check to see if this is a register or a register class.
  1151. if (R->isSubClassOf("RegisterClass")) {
  1152. assert(ResNo == 0 && "Regclass ref only has one result!");
  1153. // An unnamed register class represents itself as an i32 immediate, for
  1154. // example on a COPY_TO_REGCLASS instruction.
  1155. if (Unnamed)
  1156. return EEVT::TypeSet(MVT::i32, TP);
  1157. // In a named operand, the register class provides the possible set of
  1158. // types.
  1159. if (NotRegisters)
  1160. return EEVT::TypeSet(); // Unknown.
  1161. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1162. return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
  1163. }
  1164. if (R->isSubClassOf("PatFrag")) {
  1165. assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
  1166. // Pattern fragment types will be resolved when they are inlined.
  1167. return EEVT::TypeSet(); // Unknown.
  1168. }
  1169. if (R->isSubClassOf("Register")) {
  1170. assert(ResNo == 0 && "Registers only produce one result!");
  1171. if (NotRegisters)
  1172. return EEVT::TypeSet(); // Unknown.
  1173. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1174. return EEVT::TypeSet(T.getRegisterVTs(R));
  1175. }
  1176. if (R->isSubClassOf("SubRegIndex")) {
  1177. assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
  1178. return EEVT::TypeSet();
  1179. }
  1180. if (R->isSubClassOf("ValueType")) {
  1181. assert(ResNo == 0 && "This node only has one result!");
  1182. // An unnamed VTSDNode represents itself as an MVT::Other immediate.
  1183. //
  1184. // (sext_inreg GPR:$src, i16)
  1185. // ~~~
  1186. if (Unnamed)
  1187. return EEVT::TypeSet(MVT::Other, TP);
  1188. // With a name, the ValueType simply provides the type of the named
  1189. // variable.
  1190. //
  1191. // (sext_inreg i32:$src, i16)
  1192. // ~~~~~~~~
  1193. if (NotRegisters)
  1194. return EEVT::TypeSet(); // Unknown.
  1195. return EEVT::TypeSet(getValueType(R), TP);
  1196. }
  1197. if (R->isSubClassOf("CondCode")) {
  1198. assert(ResNo == 0 && "This node only has one result!");
  1199. // Using a CondCodeSDNode.
  1200. return EEVT::TypeSet(MVT::Other, TP);
  1201. }
  1202. if (R->isSubClassOf("ComplexPattern")) {
  1203. assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
  1204. if (NotRegisters)
  1205. return EEVT::TypeSet(); // Unknown.
  1206. return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
  1207. TP);
  1208. }
  1209. if (R->isSubClassOf("PointerLikeRegClass")) {
  1210. assert(ResNo == 0 && "Regclass can only have one result!");
  1211. return EEVT::TypeSet(MVT::iPTR, TP);
  1212. }
  1213. if (R->getName() == "node" || R->getName() == "srcvalue" ||
  1214. R->getName() == "zero_reg") {
  1215. // Placeholder.
  1216. return EEVT::TypeSet(); // Unknown.
  1217. }
  1218. TP.error("Unknown node flavor used in pattern: " + R->getName());
  1219. return EEVT::TypeSet(MVT::Other, TP);
  1220. }
  1221. /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
  1222. /// CodeGenIntrinsic information for it, otherwise return a null pointer.
  1223. const CodeGenIntrinsic *TreePatternNode::
  1224. getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
  1225. if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
  1226. getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
  1227. getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
  1228. return 0;
  1229. unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
  1230. return &CDP.getIntrinsicInfo(IID);
  1231. }
  1232. /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
  1233. /// return the ComplexPattern information, otherwise return null.
  1234. const ComplexPattern *
  1235. TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
  1236. if (!isLeaf()) return 0;
  1237. DefInit *DI = dyn_cast<DefInit>(getLeafValue());
  1238. if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
  1239. return &CGP.getComplexPattern(DI->getDef());
  1240. return 0;
  1241. }
  1242. /// NodeHasProperty - Return true if this node has the specified property.
  1243. bool TreePatternNode::NodeHasProperty(SDNP Property,
  1244. const CodeGenDAGPatterns &CGP) const {
  1245. if (isLeaf()) {
  1246. if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
  1247. return CP->hasProperty(Property);
  1248. return false;
  1249. }
  1250. Record *Operator = getOperator();
  1251. if (!Operator->isSubClassOf("SDNode")) return false;
  1252. return CGP.getSDNodeInfo(Operator).hasProperty(Property);
  1253. }
  1254. /// TreeHasProperty - Return true if any node in this tree has the specified
  1255. /// property.
  1256. bool TreePatternNode::TreeHasProperty(SDNP Property,
  1257. const CodeGenDAGPatterns &CGP) const {
  1258. if (NodeHasProperty(Property, CGP))
  1259. return true;
  1260. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1261. if (getChild(i)->TreeHasProperty(Property, CGP))
  1262. return true;
  1263. return false;
  1264. }
  1265. /// isCommutativeIntrinsic - Return true if the node corresponds to a
  1266. /// commutative intrinsic.
  1267. bool
  1268. TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
  1269. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
  1270. return Int->isCommutative;
  1271. return false;
  1272. }
  1273. /// ApplyTypeConstraints - Apply all of the type constraints relevant to
  1274. /// this node and its children in the tree. This returns true if it makes a
  1275. /// change, false otherwise. If a type contradiction is found, flag an error.
  1276. bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
  1277. if (TP.hasError())
  1278. return false;
  1279. CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
  1280. if (isLeaf()) {
  1281. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  1282. // If it's a regclass or something else known, include the type.
  1283. bool MadeChange = false;
  1284. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1285. MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
  1286. NotRegisters,
  1287. !hasName(), TP), TP);
  1288. return MadeChange;
  1289. }
  1290. if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
  1291. assert(Types.size() == 1 && "Invalid IntInit");
  1292. // Int inits are always integers. :)
  1293. bool MadeChange = Types[0].EnforceInteger(TP);
  1294. if (!Types[0].isConcrete())
  1295. return MadeChange;
  1296. MVT::SimpleValueType VT = getType(0);
  1297. if (VT == MVT::iPTR || VT == MVT::iPTRAny)
  1298. return MadeChange;
  1299. unsigned Size = MVT(VT).getSizeInBits();
  1300. // Make sure that the value is representable for this type.
  1301. if (Size >= 32) return MadeChange;
  1302. // Check that the value doesn't use more bits than we have. It must either
  1303. // be a sign- or zero-extended equivalent of the original.
  1304. int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
  1305. if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
  1306. return MadeChange;
  1307. TP.error("Integer value '" + itostr(II->getValue()) +
  1308. "' is out of range for type '" + getEnumName(getType(0)) + "'!");
  1309. return false;
  1310. }
  1311. return false;
  1312. }
  1313. // special handling for set, which isn't really an SDNode.
  1314. if (getOperator()->getName() == "set") {
  1315. assert(getNumTypes() == 0 && "Set doesn't produce a value");
  1316. assert(getNumChildren() >= 2 && "Missing RHS of a set?");
  1317. unsigned NC = getNumChildren();
  1318. TreePatternNode *SetVal = getChild(NC-1);
  1319. bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
  1320. for (unsigned i = 0; i < NC-1; ++i) {
  1321. TreePatternNode *Child = getChild(i);
  1322. MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
  1323. // Types of operands must match.
  1324. MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
  1325. MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
  1326. }
  1327. return MadeChange;
  1328. }
  1329. if (getOperator()->getName() == "implicit") {
  1330. assert(getNumTypes() == 0 && "Node doesn't produce a value");
  1331. bool MadeChange = false;
  1332. for (unsigned i = 0; i < getNumChildren(); ++i)
  1333. MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  1334. return MadeChange;
  1335. }
  1336. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
  1337. bool MadeChange = false;
  1338. // Apply the result type to the node.
  1339. unsigned NumRetVTs = Int->IS.RetVTs.size();
  1340. unsigned NumParamVTs = Int->IS.ParamVTs.size();
  1341. for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
  1342. MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
  1343. if (getNumChildren() != NumParamVTs + 1) {
  1344. TP.error("Intrinsic '" + Int->Name + "' expects " +
  1345. utostr(NumParamVTs) + " operands, not " +
  1346. utostr(getNumChildren() - 1) + " operands!");
  1347. return false;
  1348. }
  1349. // Apply type info to the intrinsic ID.
  1350. MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
  1351. for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
  1352. MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
  1353. MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
  1354. assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
  1355. MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
  1356. }
  1357. return MadeChange;
  1358. }
  1359. if (getOperator()->isSubClassOf("SDNode")) {
  1360. const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
  1361. // Check that the number of operands is sane. Negative operands -> varargs.
  1362. if (NI.getNumOperands() >= 0 &&
  1363. getNumChildren() != (unsigned)NI.getNumOperands()) {
  1364. TP.error(getOperator()->getName() + " node requires exactly " +
  1365. itostr(NI.getNumOperands()) + " operands!");
  1366. return false;
  1367. }
  1368. bool MadeChange = NI.ApplyTypeConstraints(this, TP);
  1369. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1370. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  1371. return MadeChange;
  1372. }
  1373. if (getOperator()->isSubClassOf("Instruction")) {
  1374. const DAGInstruction &Inst = CDP.getInstruction(getOperator());
  1375. CodeGenInstruction &InstInfo =
  1376. CDP.getTargetInfo().getInstruction(getOperator());
  1377. bool MadeChange = false;
  1378. // Apply the result types to the node, these come from the things in the
  1379. // (outs) list of the instruction.
  1380. // FIXME: Cap at one result so far.
  1381. unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
  1382. for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
  1383. MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
  1384. // If the instruction has implicit defs, we apply the first one as a result.
  1385. // FIXME: This sucks, it should apply all implicit defs.
  1386. if (!InstInfo.ImplicitDefs.empty()) {
  1387. unsigned ResNo = NumResultsToAdd;
  1388. // FIXME: Generalize to multiple possible types and multiple possible
  1389. // ImplicitDefs.
  1390. MVT::SimpleValueType VT =
  1391. InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
  1392. if (VT != MVT::Other)
  1393. MadeChange |= UpdateNodeType(ResNo, VT, TP);
  1394. }
  1395. // If this is an INSERT_SUBREG, constrain the source and destination VTs to
  1396. // be the same.
  1397. if (getOperator()->getName() == "INSERT_SUBREG") {
  1398. assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
  1399. MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
  1400. MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
  1401. }
  1402. unsigned ChildNo = 0;
  1403. for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
  1404. Record *OperandNode = Inst.getOperand(i);
  1405. // If the instruction expects a predicate or optional def operand, we
  1406. // codegen this by setting the operand to it's default value if it has a
  1407. // non-empty DefaultOps field.
  1408. if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
  1409. !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
  1410. continue;
  1411. // Verify that we didn't run out of provided operands.
  1412. if (ChildNo >= getNumChildren()) {
  1413. TP.error("Instruction '" + getOperator()->getName() +
  1414. "' expects more operands than were provided.");
  1415. return false;
  1416. }
  1417. TreePatternNode *Child = getChild(ChildNo++);
  1418. unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
  1419. // If the operand has sub-operands, they may be provided by distinct
  1420. // child patterns, so attempt to match each sub-operand separately.
  1421. if (OperandNode->isSubClassOf("Operand")) {
  1422. DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
  1423. if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
  1424. // But don't do that if the whole operand is being provided by
  1425. // a single ComplexPattern.
  1426. const ComplexPattern *AM = Child->getComplexPatternInfo(CDP);
  1427. if (!AM || AM->getNumOperands() < NumArgs) {
  1428. // Match first sub-operand against the child we already have.
  1429. Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
  1430. MadeChange |=
  1431. Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
  1432. // And the remaining sub-operands against subsequent children.
  1433. for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
  1434. if (ChildNo >= getNumChildren()) {
  1435. TP.error("Instruction '" + getOperator()->getName() +
  1436. "' expects more operands than were provided.");
  1437. return false;
  1438. }
  1439. Child = getChild(ChildNo++);
  1440. SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
  1441. MadeChange |=
  1442. Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
  1443. }
  1444. continue;
  1445. }
  1446. }
  1447. }
  1448. // If we didn't match by pieces above, attempt to match the whole
  1449. // operand now.
  1450. MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
  1451. }
  1452. if (ChildNo != getNumChildren()) {
  1453. TP.error("Instruction '" + getOperator()->getName() +
  1454. "' was provided too many operands!");
  1455. return false;
  1456. }
  1457. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1458. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  1459. return MadeChange;
  1460. }
  1461. assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
  1462. // Node transforms always take one operand.
  1463. if (getNumChildren() != 1) {
  1464. TP.error("Node transform '" + getOperator()->getName() +
  1465. "' requires one operand!");
  1466. return false;
  1467. }
  1468. bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
  1469. // If either the output or input of the xform does not have exact
  1470. // type info. We assume they must be the same. Otherwise, it is perfectly
  1471. // legal to transform from one type to a completely different type.
  1472. #if 0
  1473. if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
  1474. bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
  1475. MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
  1476. return MadeChange;
  1477. }
  1478. #endif
  1479. return MadeChange;
  1480. }
  1481. /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
  1482. /// RHS of a commutative operation, not the on LHS.
  1483. static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
  1484. if (!N->isLeaf() && N->getOperator()->getName() == "imm")
  1485. return true;
  1486. if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
  1487. return true;
  1488. return false;
  1489. }
  1490. /// canPatternMatch - If it is impossible for this pattern to match on this
  1491. /// target, fill in Reason and return false. Otherwise, return true. This is
  1492. /// used as a sanity check for .td files (to prevent people from writing stuff
  1493. /// that can never possibly work), and to prevent the pattern permuter from
  1494. /// generating stuff that is useless.
  1495. bool TreePatternNode::canPatternMatch(std::string &Reason,
  1496. const CodeGenDAGPatterns &CDP) {
  1497. if (isLeaf()) return true;
  1498. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1499. if (!getChild(i)->canPatternMatch(Reason, CDP))
  1500. return false;
  1501. // If this is an intrinsic, handle cases that would make it not match. For
  1502. // example, if an operand is required to be an immediate.
  1503. if (getOperator()->isSubClassOf("Intrinsic")) {
  1504. // TODO:
  1505. return true;
  1506. }
  1507. // If this node is a commutative operator, check that the LHS isn't an
  1508. // immediate.
  1509. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
  1510. bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
  1511. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  1512. // Scan all of the operands of the node and make sure that only the last one
  1513. // is a constant node, unless the RHS also is.
  1514. if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
  1515. bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
  1516. for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
  1517. if (OnlyOnRHSOfCommutative(getChild(i))) {
  1518. Reason="Immediate value must be on the RHS of commutative operators!";
  1519. return false;
  1520. }
  1521. }
  1522. }
  1523. return true;
  1524. }
  1525. //===----------------------------------------------------------------------===//
  1526. // TreePattern implementation
  1527. //
  1528. TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
  1529. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  1530. isInputPattern(isInput), HasError(false) {
  1531. for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
  1532. Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
  1533. }
  1534. TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
  1535. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  1536. isInputPattern(isInput), HasError(false) {
  1537. Trees.push_back(ParseTreePattern(Pat, ""));
  1538. }
  1539. TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
  1540. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  1541. isInputPattern(isInput), HasError(false) {
  1542. Trees.push_back(Pat);
  1543. }
  1544. void TreePattern::error(const std::string &Msg) {
  1545. if (HasError)
  1546. return;
  1547. dump();
  1548. PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
  1549. HasError = true;
  1550. }
  1551. void TreePattern::ComputeNamedNodes() {
  1552. for (unsigned i = 0, e = Trees.size(); i != e; ++i)
  1553. ComputeNamedNodes(Trees[i]);
  1554. }
  1555. void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
  1556. if (!N->getName().empty())
  1557. NamedNodes[N->getName()].push_back(N);
  1558. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  1559. ComputeNamedNodes(N->getChild(i));
  1560. }
  1561. TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
  1562. if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
  1563. Record *R = DI->getDef();
  1564. // Direct reference to a leaf DagNode or PatFrag? Turn it into a
  1565. // TreePatternNode of its own. For example:
  1566. /// (foo GPR, imm) -> (foo GPR, (imm))
  1567. if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
  1568. return ParseTreePattern(
  1569. DagInit::get(DI, "",
  1570. std::vector<std::pair<Init*, std::string> >()),
  1571. OpName);
  1572. // Input argument?
  1573. TreePatternNode *Res = new TreePatternNode(DI, 1);
  1574. if (R->getName() == "node" && !OpName.empty()) {
  1575. if (OpName.empty())
  1576. error("'node' argument requires a name to match with operand list");
  1577. Args.push_back(OpName);
  1578. }
  1579. Res->setName(OpName);
  1580. return Res;
  1581. }
  1582. // ?:$name or just $name.
  1583. if (TheInit == UnsetInit::get()) {
  1584. if (OpName.empty())
  1585. error("'?' argument requires a name to match with operand list");
  1586. TreePatternNode *Res = new TreePatternNode(TheInit, 1);
  1587. Args.push_back(OpName);
  1588. Res->setName(OpName);
  1589. return Res;
  1590. }
  1591. if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
  1592. if (!OpName.empty())
  1593. error("Constant int argument should not have a name!");
  1594. return new TreePatternNode(II, 1);
  1595. }
  1596. if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
  1597. // Turn this into an IntInit.
  1598. Init *II = BI->convertInitializerTo(IntRecTy::get());
  1599. if (II == 0 || !isa<IntInit>(II))
  1600. error("Bits value must be constants!");
  1601. return ParseTreePattern(II, OpName);
  1602. }
  1603. DagInit *Dag = dyn_cast<DagInit>(TheInit);
  1604. if (!Dag) {
  1605. TheInit->dump();
  1606. error("Pattern has unexpected init kind!");
  1607. }
  1608. DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
  1609. if (!OpDef) error("Pattern has unexpected operator type!");
  1610. Record *Operator = OpDef->getDef();
  1611. if (Operator->isSubClassOf("ValueType")) {
  1612. // If the operator is a ValueType, then this must be "type cast" of a leaf
  1613. // node.
  1614. if (Dag->getNumArgs() != 1)
  1615. error("Type cast only takes one operand!");
  1616. TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
  1617. // Apply the type cast.
  1618. assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
  1619. New->UpdateNodeType(0, getValueType(Operator), *this);
  1620. if (!OpName.empty())
  1621. error("ValueType cast should not have a name!");
  1622. return New;
  1623. }
  1624. // Verify that this is something that makes sense for an operator.
  1625. if (!Operator->isSubClassOf("PatFrag") &&
  1626. !Operator->isSubClassOf("SDNode") &&
  1627. !Operator->isSubClassOf("Instruction") &&
  1628. !Operator->isSubClassOf("SDNodeXForm") &&
  1629. !Operator->isSubClassOf("Intrinsic") &&
  1630. Operator->getName() != "set" &&
  1631. Operator->getName() != "implicit")
  1632. error("Unrecognized node '" + Operator->getName() + "'!");
  1633. // Check to see if this is something that is illegal in an input pattern.
  1634. if (isInputPattern) {
  1635. if (Operator->isSubClassOf("Instruction") ||
  1636. Operator->isSubClassOf("SDNodeXForm"))
  1637. error("Cannot use '" + Operator->getName() + "' in an input pattern!");
  1638. } else {
  1639. if (Operator->isSubClassOf("Intrinsic"))
  1640. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  1641. if (Operator->isSubClassOf("SDNode") &&
  1642. Operator->getName() != "imm" &&
  1643. Operator->getName() != "fpimm" &&
  1644. Operator->getName() != "tglobaltlsaddr" &&
  1645. Operator->getName() != "tconstpool" &&
  1646. Operator->getName() != "tjumptable" &&
  1647. Operator->getName() != "tframeindex" &&
  1648. Operator->getName() != "texternalsym" &&
  1649. Operator->getName() != "tblockaddress" &&
  1650. Operator->getName() != "tglobaladdr" &&
  1651. Operator->getName() != "bb" &&
  1652. Operator->getName() != "vt")
  1653. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  1654. }
  1655. std::vector<TreePatternNode*> Children;
  1656. // Parse all the operands.
  1657. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
  1658. Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
  1659. // If the operator is an intrinsic, then this is just syntactic sugar for for
  1660. // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
  1661. // convert the intrinsic name to a number.
  1662. if (Operator->isSubClassOf("Intrinsic")) {
  1663. const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
  1664. unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
  1665. // If this intrinsic returns void, it must have side-effects and thus a
  1666. // chain.
  1667. if (Int.IS.RetVTs.empty())
  1668. Operator = getDAGPatterns().get_intrinsic_void_sdnode();
  1669. else if (Int.ModRef != CodeGenIntrinsic::NoMem)
  1670. // Has side-effects, requires chain.
  1671. Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
  1672. else // Otherwise, no chain.
  1673. Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
  1674. TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
  1675. Children.insert(Children.begin(), IIDNode);
  1676. }
  1677. unsigned NumResults = GetNumNodeResults(Operator, CDP);
  1678. TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
  1679. Result->setName(OpName);
  1680. if (!Dag->getName().empty()) {
  1681. assert(Result->getName().empty());
  1682. Result->setName(Dag->getName());
  1683. }
  1684. return Result;
  1685. }
  1686. /// SimplifyTree - See if we can simplify this tree to eliminate something that
  1687. /// will never match in favor of something obvious that will. This is here
  1688. /// strictly as a convenience to target authors because it allows them to write
  1689. /// more type generic things and have useless type casts fold away.
  1690. ///
  1691. /// This returns true if any change is made.
  1692. static bool SimplifyTree(TreePatternNode *&N) {
  1693. if (N->isLeaf())
  1694. return false;
  1695. // If we have a bitconvert with a resolved type and if the source and
  1696. // destination types are the same, then the bitconvert is useless, remove it.
  1697. if (N->getOperator()->getName() == "bitconvert" &&
  1698. N->getExtType(0).isConcrete() &&
  1699. N->getExtType(0) == N->getChild(0)->getExtType(0) &&
  1700. N->getName().empty()) {
  1701. N = N->getChild(0);
  1702. SimplifyTree(N);
  1703. return true;
  1704. }
  1705. // Walk all children.
  1706. bool MadeChange = false;
  1707. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  1708. TreePatternNode *Child = N->getChild(i);
  1709. MadeChange |= SimplifyTree(Child);
  1710. N->setChild(i, Child);
  1711. }
  1712. return MadeChange;
  1713. }
  1714. /// InferAllTypes - Infer/propagate as many types throughout the expression
  1715. /// patterns as possible. Return true if all types are inferred, false
  1716. /// otherwise. Flags an error if a type contradiction is found.
  1717. bool TreePattern::
  1718. InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
  1719. if (NamedNodes.empty())
  1720. ComputeNamedNodes();
  1721. bool MadeChange = true;
  1722. while (MadeChange) {
  1723. MadeChange = false;
  1724. for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
  1725. MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
  1726. MadeChange |= SimplifyTree(Trees[i]);
  1727. }
  1728. // If there are constraints on our named nodes, apply them.
  1729. for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
  1730. I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
  1731. SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
  1732. // If we have input named node types, propagate their types to the named
  1733. // values here.
  1734. if (InNamedTypes) {
  1735. // FIXME: Should be error?
  1736. assert(InNamedTypes->count(I->getKey()) &&
  1737. "Named node in output pattern but not input pattern?");
  1738. const SmallVectorImpl<TreePatternNode*> &InNodes =
  1739. InNamedTypes->find(I->getKey())->second;
  1740. // The input types should be fully resolved by now.
  1741. for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
  1742. // If this node is a register class, and it is the root of the pattern
  1743. // then we're mapping something onto an input register. We allow
  1744. // changing the type of the input register in this case. This allows
  1745. // us to match things like:
  1746. // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
  1747. if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
  1748. DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
  1749. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  1750. DI->getDef()->isSubClassOf("RegisterOperand")))
  1751. continue;
  1752. }
  1753. assert(Nodes[i]->getNumTypes() == 1 &&
  1754. InNodes[0]->getNumTypes() == 1 &&
  1755. "FIXME: cannot name multiple result nodes yet");
  1756. MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
  1757. *this);
  1758. }
  1759. }
  1760. // If there are multiple nodes with the same name, they must all have the
  1761. // same type.
  1762. if (I->second.size() > 1) {
  1763. for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
  1764. TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
  1765. assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
  1766. "FIXME: cannot name multiple result nodes yet");
  1767. MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
  1768. MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
  1769. }
  1770. }
  1771. }
  1772. }
  1773. bool HasUnresolvedTypes = false;
  1774. for (unsigned i = 0, e = Trees.size(); i != e; ++i)
  1775. HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
  1776. return !HasUnresolvedTypes;
  1777. }
  1778. void TreePattern::print(raw_ostream &OS) const {
  1779. OS << getRecord()->getName();
  1780. if (!Args.empty()) {
  1781. OS << "(" << Args[0];
  1782. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  1783. OS << ", " << Args[i];
  1784. OS << ")";
  1785. }
  1786. OS << ": ";
  1787. if (Trees.size() > 1)
  1788. OS << "[\n";
  1789. for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
  1790. OS << "\t";
  1791. Trees[i]->print(OS);
  1792. OS << "\n";
  1793. }
  1794. if (Trees.size() > 1)
  1795. OS << "]\n";
  1796. }
  1797. void TreePattern::dump() const { print(errs()); }
  1798. //===----------------------------------------------------------------------===//
  1799. // CodeGenDAGPatterns implementation
  1800. //
  1801. CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
  1802. Records(R), Target(R) {
  1803. Intrinsics = LoadIntrinsics(Records, false);
  1804. TgtIntrinsics = LoadIntrinsics(Records, true);
  1805. ParseNodeInfo();
  1806. ParseNodeTransforms();
  1807. ParseComplexPatterns();
  1808. ParsePatternFragments();
  1809. ParseDefaultOperands();
  1810. ParseInstructions();
  1811. ParsePatterns();
  1812. // Generate variants. For example, commutative patterns can match
  1813. // multiple ways. Add them to PatternsToMatch as well.
  1814. GenerateVariants();
  1815. // Infer instruction flags. For example, we can detect loads,
  1816. // stores, and side effects in many cases by examining an
  1817. // instruction's pattern.
  1818. InferInstructionFlags();
  1819. // Verify that instruction flags match the patterns.
  1820. VerifyInstructionFlags();
  1821. }
  1822. CodeGenDAGPatterns::~CodeGenDAGPatterns() {
  1823. for (pf_iterator I = PatternFragments.begin(),
  1824. E = PatternFragments.end(); I != E; ++I)
  1825. delete I->second;
  1826. }
  1827. Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
  1828. Record *N = Records.getDef(Name);
  1829. if (!N || !N->isSubClassOf("SDNode")) {
  1830. errs() << "Error getting SDNode '" << Name << "'!\n";
  1831. exit(1);
  1832. }
  1833. return N;
  1834. }
  1835. // Parse all of the SDNode definitions for the target, populating SDNodes.
  1836. void CodeGenDAGPatterns::ParseNodeInfo() {
  1837. std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
  1838. while (!Nodes.empty()) {
  1839. SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
  1840. Nodes.pop_back();
  1841. }
  1842. // Get the builtin intrinsic nodes.
  1843. intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
  1844. intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
  1845. intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
  1846. }
  1847. /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
  1848. /// map, and emit them to the file as functions.
  1849. void CodeGenDAGPatterns::ParseNodeTransforms() {
  1850. std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
  1851. while (!Xforms.empty()) {
  1852. Record *XFormNode = Xforms.back();
  1853. Record *SDNode = XFormNode->getValueAsDef("Opcode");
  1854. std::string Code = XFormNode->getValueAsString("XFormFunction");
  1855. SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
  1856. Xforms.pop_back();
  1857. }
  1858. }
  1859. void CodeGenDAGPatterns::ParseComplexPatterns() {
  1860. std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
  1861. while (!AMs.empty()) {
  1862. ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
  1863. AMs.pop_back();
  1864. }
  1865. }
  1866. /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
  1867. /// file, building up the PatternFragments map. After we've collected them all,
  1868. /// inline fragments together as necessary, so that there are no references left
  1869. /// inside a pattern fragment to a pattern fragment.
  1870. ///
  1871. void CodeGenDAGPatterns::ParsePatternFragments() {
  1872. std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
  1873. // First step, parse all of the fragments.
  1874. for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
  1875. DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
  1876. TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
  1877. PatternFragments[Fragments[i]] = P;
  1878. // Validate the argument list, converting it to set, to discard duplicates.
  1879. std::vector<std::string> &Args = P->getArgList();
  1880. std::set<std::string> OperandsSet(Args.begin(), Args.end());
  1881. if (OperandsSet.count(""))
  1882. P->error("Cannot have unnamed 'node' values in pattern fragment!");
  1883. // Parse the operands list.
  1884. DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
  1885. DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
  1886. // Special cases: ops == outs == ins. Different names are used to
  1887. // improve readability.
  1888. if (!OpsOp ||
  1889. (OpsOp->getDef()->getName() != "ops" &&
  1890. OpsOp->getDef()->getName() != "outs" &&
  1891. OpsOp->getDef()->getName() != "ins"))
  1892. P->error("Operands list should start with '(ops ... '!");
  1893. // Copy over the arguments.
  1894. Args.clear();
  1895. for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
  1896. if (!isa<DefInit>(OpsList->getArg(j)) ||
  1897. cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
  1898. P->error("Operands list should all be 'node' values.");
  1899. if (OpsList->getArgName(j).empty())
  1900. P->error("Operands list should have names for each operand!");
  1901. if (!OperandsSet.count(OpsList->getArgName(j)))
  1902. P->error("'" + OpsList->getArgName(j) +
  1903. "' does not occur in pattern or was multiply specified!");
  1904. OperandsSet.erase(OpsList->getArgName(j));
  1905. Args.push_back(OpsList->getArgName(j));
  1906. }
  1907. if (!OperandsSet.empty())
  1908. P->error("Operands list does not contain an entry for operand '" +
  1909. *OperandsSet.begin() + "'!");
  1910. // If there is a code init for this fragment, keep track of the fact that
  1911. // this fragment uses it.
  1912. TreePredicateFn PredFn(P);
  1913. if (!PredFn.isAlwaysTrue())
  1914. P->getOnlyTree()->addPredicateFn(PredFn);
  1915. // If there is a node transformation corresponding to this, keep track of
  1916. // it.
  1917. Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
  1918. if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
  1919. P->getOnlyTree()->setTransformFn(Transform);
  1920. }
  1921. // Now that we've parsed all of the tree fragments, do a closure on them so
  1922. // that there are not references to PatFrags left inside of them.
  1923. for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
  1924. TreePattern *ThePat = PatternFragments[Fragments[i]];
  1925. ThePat->InlinePatternFragments();
  1926. // Infer as many types as possible. Don't worry about it if we don't infer
  1927. // all of them, some may depend on the inputs of the pattern.
  1928. ThePat->InferAllTypes();
  1929. ThePat->resetError();
  1930. // If debugging, print out the pattern fragment result.
  1931. DEBUG(ThePat->dump());
  1932. }
  1933. }
  1934. void CodeGenDAGPatterns::ParseDefaultOperands() {
  1935. std::vector<Record*> DefaultOps;
  1936. DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
  1937. // Find some SDNode.
  1938. assert(!SDNodes.empty() && "No SDNodes parsed?");
  1939. Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
  1940. for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
  1941. DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
  1942. // Clone the DefaultInfo dag node, changing the operator from 'ops' to
  1943. // SomeSDnode so that we can parse this.
  1944. std::vector<std::pair<Init*, std::string> > Ops;
  1945. for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
  1946. Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
  1947. DefaultInfo->getArgName(op)));
  1948. DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
  1949. // Create a TreePattern to parse this.
  1950. TreePattern P(DefaultOps[i], DI, false, *this);
  1951. assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
  1952. // Copy the operands over into a DAGDefaultOperand.
  1953. DAGDefaultOperand DefaultOpInfo;
  1954. TreePatternNode *T = P.getTree(0);
  1955. for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
  1956. TreePatternNode *TPN = T->getChild(op);
  1957. while (TPN->ApplyTypeConstraints(P, false))
  1958. /* Resolve all types */;
  1959. if (TPN->ContainsUnresolvedType()) {
  1960. PrintFatalError("Value #" + utostr(i) + " of OperandWithDefaultOps '" +
  1961. DefaultOps[i]->getName() +"' doesn't have a concrete type!");
  1962. }
  1963. DefaultOpInfo.DefaultOps.push_back(TPN);
  1964. }
  1965. // Insert it into the DefaultOperands map so we can find it later.
  1966. DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
  1967. }
  1968. }
  1969. /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
  1970. /// instruction input. Return true if this is a real use.
  1971. static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
  1972. std::map<std::string, TreePatternNode*> &InstInputs) {
  1973. // No name -> not interesting.
  1974. if (Pat->getName().empty()) {
  1975. if (Pat->isLeaf()) {
  1976. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  1977. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  1978. DI->getDef()->isSubClassOf("RegisterOperand")))
  1979. I->error("Input " + DI->getDef()->getName() + " must be named!");
  1980. }
  1981. return false;
  1982. }
  1983. Record *Rec;
  1984. if (Pat->isLeaf()) {
  1985. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  1986. if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
  1987. Rec = DI->getDef();
  1988. } else {
  1989. Rec = Pat->getOperator();
  1990. }
  1991. // SRCVALUE nodes are ignored.
  1992. if (Rec->getName() == "srcvalue")
  1993. return false;
  1994. TreePatternNode *&Slot = InstInputs[Pat->getName()];
  1995. if (!Slot) {
  1996. Slot = Pat;
  1997. return true;
  1998. }
  1999. Record *SlotRec;
  2000. if (Slot->isLeaf()) {
  2001. SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
  2002. } else {
  2003. assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
  2004. SlotRec = Slot->getOperator();
  2005. }
  2006. // Ensure that the inputs agree if we've already seen this input.
  2007. if (Rec != SlotRec)
  2008. I->error("All $" + Pat->getName() + " inputs must agree with each other");
  2009. if (Slot->getExtTypes() != Pat->getExtTypes())
  2010. I->error("All $" + Pat->getName() + " inputs must agree with each other");
  2011. return true;
  2012. }
  2013. /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
  2014. /// part of "I", the instruction), computing the set of inputs and outputs of
  2015. /// the pattern. Report errors if we see anything naughty.
  2016. void CodeGenDAGPatterns::
  2017. FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
  2018. std::map<std::string, TreePatternNode*> &InstInputs,
  2019. std::map<std::string, TreePatternNode*>&InstResults,
  2020. std::vector<Record*> &InstImpResults) {
  2021. if (Pat->isLeaf()) {
  2022. bool isUse = HandleUse(I, Pat, InstInputs);
  2023. if (!isUse && Pat->getTransformFn())
  2024. I->error("Cannot specify a transform function for a non-input value!");
  2025. return;
  2026. }
  2027. if (Pat->getOperator()->getName() == "implicit") {
  2028. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  2029. TreePatternNode *Dest = Pat->getChild(i);
  2030. if (!Dest->isLeaf())
  2031. I->error("implicitly defined value should be a register!");
  2032. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  2033. if (!Val || !Val->getDef()->isSubClassOf("Register"))
  2034. I->error("implicitly defined value should be a register!");
  2035. InstImpResults.push_back(Val->getDef());
  2036. }
  2037. return;
  2038. }
  2039. if (Pat->getOperator()->getName() != "set") {
  2040. // If this is not a set, verify that the children nodes are not void typed,
  2041. // and recurse.
  2042. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  2043. if (Pat->getChild(i)->getNumTypes() == 0)
  2044. I->error("Cannot have void nodes inside of patterns!");
  2045. FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
  2046. InstImpResults);
  2047. }
  2048. // If this is a non-leaf node with no children, treat it basically as if
  2049. // it were a leaf. This handles nodes like (imm).
  2050. bool isUse = HandleUse(I, Pat, InstInputs);
  2051. if (!isUse && Pat->getTransformFn())
  2052. I->error("Cannot specify a transform function for a non-input value!");
  2053. return;
  2054. }
  2055. // Otherwise, this is a set, validate and collect instruction results.
  2056. if (Pat->getNumChildren() == 0)
  2057. I->error("set requires operands!");
  2058. if (Pat->getTransformFn())
  2059. I->error("Cannot specify a transform function on a set node!");
  2060. // Check the set destinations.
  2061. unsigned NumDests = Pat->getNumChildren()-1;
  2062. for (unsigned i = 0; i != NumDests; ++i) {
  2063. TreePatternNode *Dest = Pat->getChild(i);
  2064. if (!Dest->isLeaf())
  2065. I->error("set destination should be a register!");
  2066. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  2067. if (!Val)
  2068. I->error("set destination should be a register!");
  2069. if (Val->getDef()->isSubClassOf("RegisterClass") ||
  2070. Val->getDef()->isSubClassOf("ValueType") ||
  2071. Val->getDef()->isSubClassOf("RegisterOperand") ||
  2072. Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
  2073. if (Dest->getName().empty())
  2074. I->error("set destination must have a name!");
  2075. if (InstResults.count(Dest->getName()))
  2076. I->error("cannot set '" + Dest->getName() +"' multiple times");
  2077. InstResults[Dest->getName()] = Dest;
  2078. } else if (Val->getDef()->isSubClassOf("Register")) {
  2079. InstImpResults.push_back(Val->getDef());
  2080. } else {
  2081. I->error("set destination should be a register!");
  2082. }
  2083. }
  2084. // Verify and collect info from the computation.
  2085. FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
  2086. InstInputs, InstResults, InstImpResults);
  2087. }
  2088. //===----------------------------------------------------------------------===//
  2089. // Instruction Analysis
  2090. //===----------------------------------------------------------------------===//
  2091. class InstAnalyzer {
  2092. const CodeGenDAGPatterns &CDP;
  2093. public:
  2094. bool hasSideEffects;
  2095. bool mayStore;
  2096. bool mayLoad;
  2097. bool isBitcast;
  2098. bool isVariadic;
  2099. InstAnalyzer(const CodeGenDAGPatterns &cdp)
  2100. : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
  2101. isBitcast(false), isVariadic(false) {}
  2102. void Analyze(const TreePattern *Pat) {
  2103. // Assume only the first tree is the pattern. The others are clobber nodes.
  2104. AnalyzeNode(Pat->getTree(0));
  2105. }
  2106. void Analyze(const PatternToMatch *Pat) {
  2107. AnalyzeNode(Pat->getSrcPattern());
  2108. }
  2109. private:
  2110. bool IsNodeBitcast(const TreePatternNode *N) const {
  2111. if (hasSideEffects || mayLoad || mayStore || isVariadic)
  2112. return false;
  2113. if (N->getNumChildren() != 2)
  2114. return false;
  2115. const TreePatternNode *N0 = N->getChild(0);
  2116. if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
  2117. return false;
  2118. const TreePatternNode *N1 = N->getChild(1);
  2119. if (N1->isLeaf())
  2120. return false;
  2121. if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
  2122. return false;
  2123. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
  2124. if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
  2125. return false;
  2126. return OpInfo.getEnumName() == "ISD::BITCAST";
  2127. }
  2128. public:
  2129. void AnalyzeNode(const TreePatternNode *N) {
  2130. if (N->isLeaf()) {
  2131. if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
  2132. Record *LeafRec = DI->getDef();
  2133. // Handle ComplexPattern leaves.
  2134. if (LeafRec->isSubClassOf("ComplexPattern")) {
  2135. const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
  2136. if (CP.hasProperty(SDNPMayStore)) mayStore = true;
  2137. if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
  2138. if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
  2139. }
  2140. }
  2141. return;
  2142. }
  2143. // Analyze children.
  2144. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2145. AnalyzeNode(N->getChild(i));
  2146. // Ignore set nodes, which are not SDNodes.
  2147. if (N->getOperator()->getName() == "set") {
  2148. isBitcast = IsNodeBitcast(N);
  2149. return;
  2150. }
  2151. // Get information about the SDNode for the operator.
  2152. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
  2153. // Notice properties of the node.
  2154. if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
  2155. if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
  2156. if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
  2157. if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
  2158. if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
  2159. // If this is an intrinsic, analyze it.
  2160. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
  2161. mayLoad = true;// These may load memory.
  2162. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
  2163. mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
  2164. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
  2165. // WriteMem intrinsics can have other strange effects.
  2166. hasSideEffects = true;
  2167. }
  2168. }
  2169. };
  2170. static bool InferFromPattern(CodeGenInstruction &InstInfo,
  2171. const InstAnalyzer &PatInfo,
  2172. Record *PatDef) {
  2173. bool Error = false;
  2174. // Remember where InstInfo got its flags.
  2175. if (InstInfo.hasUndefFlags())
  2176. InstInfo.InferredFrom = PatDef;
  2177. // Check explicitly set flags for consistency.
  2178. if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
  2179. !InstInfo.hasSideEffects_Unset) {
  2180. // Allow explicitly setting hasSideEffects = 1 on instructions, even when
  2181. // the pattern has no side effects. That could be useful for div/rem
  2182. // instructions that may trap.
  2183. if (!InstInfo.hasSideEffects) {
  2184. Error = true;
  2185. PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
  2186. Twine(InstInfo.hasSideEffects));
  2187. }
  2188. }
  2189. if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
  2190. Error = true;
  2191. PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
  2192. Twine(InstInfo.mayStore));
  2193. }
  2194. if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
  2195. // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
  2196. // Some targets translate imediates to loads.
  2197. if (!InstInfo.mayLoad) {
  2198. Error = true;
  2199. PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
  2200. Twine(InstInfo.mayLoad));
  2201. }
  2202. }
  2203. // Transfer inferred flags.
  2204. InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
  2205. InstInfo.mayStore |= PatInfo.mayStore;
  2206. InstInfo.mayLoad |= PatInfo.mayLoad;
  2207. // These flags are silently added without any verification.
  2208. InstInfo.isBitcast |= PatInfo.isBitcast;
  2209. // Don't infer isVariadic. This flag means something different on SDNodes and
  2210. // instructions. For example, a CALL SDNode is variadic because it has the
  2211. // call arguments as operands, but a CALL instruction is not variadic - it
  2212. // has argument registers as implicit, not explicit uses.
  2213. return Error;
  2214. }
  2215. /// hasNullFragReference - Return true if the DAG has any reference to the
  2216. /// null_frag operator.
  2217. static bool hasNullFragReference(DagInit *DI) {
  2218. DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
  2219. if (!OpDef) return false;
  2220. Record *Operator = OpDef->getDef();
  2221. // If this is the null fragment, return true.
  2222. if (Operator->getName() == "null_frag") return true;
  2223. // If any of the arguments reference the null fragment, return true.
  2224. for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
  2225. DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
  2226. if (Arg && hasNullFragReference(Arg))
  2227. return true;
  2228. }
  2229. return false;
  2230. }
  2231. /// hasNullFragReference - Return true if any DAG in the list references
  2232. /// the null_frag operator.
  2233. static bool hasNullFragReference(ListInit *LI) {
  2234. for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
  2235. DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
  2236. assert(DI && "non-dag in an instruction Pattern list?!");
  2237. if (hasNullFragReference(DI))
  2238. return true;
  2239. }
  2240. return false;
  2241. }
  2242. /// Get all the instructions in a tree.
  2243. static void
  2244. getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
  2245. if (Tree->isLeaf())
  2246. return;
  2247. if (Tree->getOperator()->isSubClassOf("Instruction"))
  2248. Instrs.push_back(Tree->getOperator());
  2249. for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
  2250. getInstructionsInTree(Tree->getChild(i), Instrs);
  2251. }
  2252. /// Check the class of a pattern leaf node against the instruction operand it
  2253. /// represents.
  2254. static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
  2255. Record *Leaf) {
  2256. if (OI.Rec == Leaf)
  2257. return true;
  2258. // Allow direct value types to be used in instruction set patterns.
  2259. // The type will be checked later.
  2260. if (Leaf->isSubClassOf("ValueType"))
  2261. return true;
  2262. // Patterns can also be ComplexPattern instances.
  2263. if (Leaf->isSubClassOf("ComplexPattern"))
  2264. return true;
  2265. return false;
  2266. }
  2267. const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
  2268. CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
  2269. assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
  2270. // Parse the instruction.
  2271. TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
  2272. // Inline pattern fragments into it.
  2273. I->InlinePatternFragments();
  2274. // Infer as many types as possible. If we cannot infer all of them, we can
  2275. // never do anything with this instruction pattern: report it to the user.
  2276. if (!I->InferAllTypes())
  2277. I->error("Could not infer all types in pattern!");
  2278. // InstInputs - Keep track of all of the inputs of the instruction, along
  2279. // with the record they are declared as.
  2280. std::map<std::string, TreePatternNode*> InstInputs;
  2281. // InstResults - Keep track of all the virtual registers that are 'set'
  2282. // in the instruction, including what reg class they are.
  2283. std::map<std::string, TreePatternNode*> InstResults;
  2284. std::vector<Record*> InstImpResults;
  2285. // Verify that the top-level forms in the instruction are of void type, and
  2286. // fill in the InstResults map.
  2287. for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
  2288. TreePatternNode *Pat = I->getTree(j);
  2289. if (Pat->getNumTypes() != 0)
  2290. I->error("Top-level forms in instruction pattern should have"
  2291. " void types");
  2292. // Find inputs and outputs, and verify the structure of the uses/defs.
  2293. FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
  2294. InstImpResults);
  2295. }
  2296. // Now that we have inputs and outputs of the pattern, inspect the operands
  2297. // list for the instruction. This determines the order that operands are
  2298. // added to the machine instruction the node corresponds to.
  2299. unsigned NumResults = InstResults.size();
  2300. // Parse the operands list from the (ops) list, validating it.
  2301. assert(I->getArgList().empty() && "Args list should still be empty here!");
  2302. // Check that all of the results occur first in the list.
  2303. std::vector<Record*> Results;
  2304. TreePatternNode *Res0Node = 0;
  2305. for (unsigned i = 0; i != NumResults; ++i) {
  2306. if (i == CGI.Operands.size())
  2307. I->error("'" + InstResults.begin()->first +
  2308. "' set but does not appear in operand list!");
  2309. const std::string &OpName = CGI.Operands[i].Name;
  2310. // Check that it exists in InstResults.
  2311. TreePatternNode *RNode = InstResults[OpName];
  2312. if (RNode == 0)
  2313. I->error("Operand $" + OpName + " does not exist in operand list!");
  2314. if (i == 0)
  2315. Res0Node = RNode;
  2316. Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
  2317. if (R == 0)
  2318. I->error("Operand $" + OpName + " should be a set destination: all "
  2319. "outputs must occur before inputs in operand list!");
  2320. if (!checkOperandClass(CGI.Operands[i], R))
  2321. I->error("Operand $" + OpName + " class mismatch!");
  2322. // Remember the return type.
  2323. Results.push_back(CGI.Operands[i].Rec);
  2324. // Okay, this one checks out.
  2325. InstResults.erase(OpName);
  2326. }
  2327. // Loop over the inputs next. Make a copy of InstInputs so we can destroy
  2328. // the copy while we're checking the inputs.
  2329. std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
  2330. std::vector<TreePatternNode*> ResultNodeOperands;
  2331. std::vector<Record*> Operands;
  2332. for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
  2333. CGIOperandList::OperandInfo &Op = CGI.Operands[i];
  2334. const std::string &OpName = Op.Name;
  2335. if (OpName.empty())
  2336. I->error("Operand #" + utostr(i) + " in operands list has no name!");
  2337. if (!InstInputsCheck.count(OpName)) {
  2338. // If this is an operand with a DefaultOps set filled in, we can ignore
  2339. // this. When we codegen it, we will do so as always executed.
  2340. if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
  2341. // Does it have a non-empty DefaultOps field? If so, ignore this
  2342. // operand.
  2343. if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
  2344. continue;
  2345. }
  2346. I->error("Operand $" + OpName +
  2347. " does not appear in the instruction pattern");
  2348. }
  2349. TreePatternNode *InVal = InstInputsCheck[OpName];
  2350. InstInputsCheck.erase(OpName); // It occurred, remove from map.
  2351. if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
  2352. Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
  2353. if (!checkOperandClass(Op, InRec))
  2354. I->error("Operand $" + OpName + "'s register class disagrees"
  2355. " between the operand and pattern");
  2356. }
  2357. Operands.push_back(Op.Rec);
  2358. // Construct the result for the dest-pattern operand list.
  2359. TreePatternNode *OpNode = InVal->clone();
  2360. // No predicate is useful on the result.
  2361. OpNode->clearPredicateFns();
  2362. // Promote the xform function to be an explicit node if set.
  2363. if (Record *Xform = OpNode->getTransformFn()) {
  2364. OpNode->setTransformFn(0);
  2365. std::vector<TreePatternNode*> Children;
  2366. Children.push_back(OpNode);
  2367. OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
  2368. }
  2369. ResultNodeOperands.push_back(OpNode);
  2370. }
  2371. if (!InstInputsCheck.empty())
  2372. I->error("Input operand $" + InstInputsCheck.begin()->first +
  2373. " occurs in pattern but not in operands list!");
  2374. TreePatternNode *ResultPattern =
  2375. new TreePatternNode(I->getRecord(), ResultNodeOperands,
  2376. GetNumNodeResults(I->getRecord(), *this));
  2377. // Copy fully inferred output node type to instruction result pattern.
  2378. for (unsigned i = 0; i != NumResults; ++i)
  2379. ResultPattern->setType(i, Res0Node->getExtType(i));
  2380. // Create and insert the instruction.
  2381. // FIXME: InstImpResults should not be part of DAGInstruction.
  2382. DAGInstruction TheInst(I, Results, Operands, InstImpResults);
  2383. DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
  2384. // Use a temporary tree pattern to infer all types and make sure that the
  2385. // constructed result is correct. This depends on the instruction already
  2386. // being inserted into the DAGInsts map.
  2387. TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
  2388. Temp.InferAllTypes(&I->getNamedNodesMap());
  2389. DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
  2390. TheInsertedInst.setResultPattern(Temp.getOnlyTree());
  2391. return TheInsertedInst;
  2392. }
  2393. /// ParseInstructions - Parse all of the instructions, inlining and resolving
  2394. /// any fragments involved. This populates the Instructions list with fully
  2395. /// resolved instructions.
  2396. void CodeGenDAGPatterns::ParseInstructions() {
  2397. std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
  2398. for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
  2399. ListInit *LI = 0;
  2400. if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
  2401. LI = Instrs[i]->getValueAsListInit("Pattern");
  2402. // If there is no pattern, only collect minimal information about the
  2403. // instruction for its operand list. We have to assume that there is one
  2404. // result, as we have no detailed info. A pattern which references the
  2405. // null_frag operator is as-if no pattern were specified. Normally this
  2406. // is from a multiclass expansion w/ a SDPatternOperator passed in as
  2407. // null_frag.
  2408. if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
  2409. std::vector<Record*> Results;
  2410. std::vector<Record*> Operands;
  2411. CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
  2412. if (InstInfo.Operands.size() != 0) {
  2413. if (InstInfo.Operands.NumDefs == 0) {
  2414. // These produce no results
  2415. for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
  2416. Operands.push_back(InstInfo.Operands[j].Rec);
  2417. } else {
  2418. // Assume the first operand is the result.
  2419. Results.push_back(InstInfo.Operands[0].Rec);
  2420. // The rest are inputs.
  2421. for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
  2422. Operands.push_back(InstInfo.Operands[j].Rec);
  2423. }
  2424. }
  2425. // Create and insert the instruction.
  2426. std::vector<Record*> ImpResults;
  2427. Instructions.insert(std::make_pair(Instrs[i],
  2428. DAGInstruction(0, Results, Operands, ImpResults)));
  2429. continue; // no pattern.
  2430. }
  2431. CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
  2432. const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
  2433. (void)DI;
  2434. DEBUG(DI.getPattern()->dump());
  2435. }
  2436. // If we can, convert the instructions to be patterns that are matched!
  2437. for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
  2438. Instructions.begin(),
  2439. E = Instructions.end(); II != E; ++II) {
  2440. DAGInstruction &TheInst = II->second;
  2441. TreePattern *I = TheInst.getPattern();
  2442. if (I == 0) continue; // No pattern.
  2443. // FIXME: Assume only the first tree is the pattern. The others are clobber
  2444. // nodes.
  2445. TreePatternNode *Pattern = I->getTree(0);
  2446. TreePatternNode *SrcPattern;
  2447. if (Pattern->getOperator()->getName() == "set") {
  2448. SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
  2449. } else{
  2450. // Not a set (store or something?)
  2451. SrcPattern = Pattern;
  2452. }
  2453. Record *Instr = II->first;
  2454. AddPatternToMatch(I,
  2455. PatternToMatch(Instr,
  2456. Instr->getValueAsListInit("Predicates"),
  2457. SrcPattern,
  2458. TheInst.getResultPattern(),
  2459. TheInst.getImpResults(),
  2460. Instr->getValueAsInt("AddedComplexity"),
  2461. Instr->getID()));
  2462. }
  2463. }
  2464. typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
  2465. static void FindNames(const TreePatternNode *P,
  2466. std::map<std::string, NameRecord> &Names,
  2467. TreePattern *PatternTop) {
  2468. if (!P->getName().empty()) {
  2469. NameRecord &Rec = Names[P->getName()];
  2470. // If this is the first instance of the name, remember the node.
  2471. if (Rec.second++ == 0)
  2472. Rec.first = P;
  2473. else if (Rec.first->getExtTypes() != P->getExtTypes())
  2474. PatternTop->error("repetition of value: $" + P->getName() +
  2475. " where different uses have different types!");
  2476. }
  2477. if (!P->isLeaf()) {
  2478. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
  2479. FindNames(P->getChild(i), Names, PatternTop);
  2480. }
  2481. }
  2482. void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
  2483. const PatternToMatch &PTM) {
  2484. // Do some sanity checking on the pattern we're about to match.
  2485. std::string Reason;
  2486. if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
  2487. PrintWarning(Pattern->getRecord()->getLoc(),
  2488. Twine("Pattern can never match: ") + Reason);
  2489. return;
  2490. }
  2491. // If the source pattern's root is a complex pattern, that complex pattern
  2492. // must specify the nodes it can potentially match.
  2493. if (const ComplexPattern *CP =
  2494. PTM.getSrcPattern()->getComplexPatternInfo(*this))
  2495. if (CP->getRootNodes().empty())
  2496. Pattern->error("ComplexPattern at root must specify list of opcodes it"
  2497. " could match");
  2498. // Find all of the named values in the input and output, ensure they have the
  2499. // same type.
  2500. std::map<std::string, NameRecord> SrcNames, DstNames;
  2501. FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
  2502. FindNames(PTM.getDstPattern(), DstNames, Pattern);
  2503. // Scan all of the named values in the destination pattern, rejecting them if
  2504. // they don't exist in the input pattern.
  2505. for (std::map<std::string, NameRecord>::iterator
  2506. I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
  2507. if (SrcNames[I->first].first == 0)
  2508. Pattern->error("Pattern has input without matching name in output: $" +
  2509. I->first);
  2510. }
  2511. // Scan all of the named values in the source pattern, rejecting them if the
  2512. // name isn't used in the dest, and isn't used to tie two values together.
  2513. for (std::map<std::string, NameRecord>::iterator
  2514. I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
  2515. if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
  2516. Pattern->error("Pattern has dead named input: $" + I->first);
  2517. PatternsToMatch.push_back(PTM);
  2518. }
  2519. void CodeGenDAGPatterns::InferInstructionFlags() {
  2520. const std::vector<const CodeGenInstruction*> &Instructions =
  2521. Target.getInstructionsByEnumValue();
  2522. // First try to infer flags from the primary instruction pattern, if any.
  2523. SmallVector<CodeGenInstruction*, 8> Revisit;
  2524. unsigned Errors = 0;
  2525. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  2526. CodeGenInstruction &InstInfo =
  2527. const_cast<CodeGenInstruction &>(*Instructions[i]);
  2528. // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
  2529. // This flag is obsolete and will be removed.
  2530. if (InstInfo.neverHasSideEffects) {
  2531. assert(!InstInfo.hasSideEffects);
  2532. InstInfo.hasSideEffects_Unset = false;
  2533. }
  2534. // Get the primary instruction pattern.
  2535. const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
  2536. if (!Pattern) {
  2537. if (InstInfo.hasUndefFlags())
  2538. Revisit.push_back(&InstInfo);
  2539. continue;
  2540. }
  2541. InstAnalyzer PatInfo(*this);
  2542. PatInfo.Analyze(Pattern);
  2543. Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
  2544. }
  2545. // Second, look for single-instruction patterns defined outside the
  2546. // instruction.
  2547. for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
  2548. const PatternToMatch &PTM = *I;
  2549. // We can only infer from single-instruction patterns, otherwise we won't
  2550. // know which instruction should get the flags.
  2551. SmallVector<Record*, 8> PatInstrs;
  2552. getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
  2553. if (PatInstrs.size() != 1)
  2554. continue;
  2555. // Get the single instruction.
  2556. CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
  2557. // Only infer properties from the first pattern. We'll verify the others.
  2558. if (InstInfo.InferredFrom)
  2559. continue;
  2560. InstAnalyzer PatInfo(*this);
  2561. PatInfo.Analyze(&PTM);
  2562. Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
  2563. }
  2564. if (Errors)
  2565. PrintFatalError("pattern conflicts");
  2566. // Revisit instructions with undefined flags and no pattern.
  2567. if (Target.guessInstructionProperties()) {
  2568. for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
  2569. CodeGenInstruction &InstInfo = *Revisit[i];
  2570. if (InstInfo.InferredFrom)
  2571. continue;
  2572. // The mayLoad and mayStore flags default to false.
  2573. // Conservatively assume hasSideEffects if it wasn't explicit.
  2574. if (InstInfo.hasSideEffects_Unset)
  2575. InstInfo.hasSideEffects = true;
  2576. }
  2577. return;
  2578. }
  2579. // Complain about any flags that are still undefined.
  2580. for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
  2581. CodeGenInstruction &InstInfo = *Revisit[i];
  2582. if (InstInfo.InferredFrom)
  2583. continue;
  2584. if (InstInfo.hasSideEffects_Unset)
  2585. PrintError(InstInfo.TheDef->getLoc(),
  2586. "Can't infer hasSideEffects from patterns");
  2587. if (InstInfo.mayStore_Unset)
  2588. PrintError(InstInfo.TheDef->getLoc(),
  2589. "Can't infer mayStore from patterns");
  2590. if (InstInfo.mayLoad_Unset)
  2591. PrintError(InstInfo.TheDef->getLoc(),
  2592. "Can't infer mayLoad from patterns");
  2593. }
  2594. }
  2595. /// Verify instruction flags against pattern node properties.
  2596. void CodeGenDAGPatterns::VerifyInstructionFlags() {
  2597. unsigned Errors = 0;
  2598. for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
  2599. const PatternToMatch &PTM = *I;
  2600. SmallVector<Record*, 8> Instrs;
  2601. getInstructionsInTree(PTM.getDstPattern(), Instrs);
  2602. if (Instrs.empty())
  2603. continue;
  2604. // Count the number of instructions with each flag set.
  2605. unsigned NumSideEffects = 0;
  2606. unsigned NumStores = 0;
  2607. unsigned NumLoads = 0;
  2608. for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
  2609. const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
  2610. NumSideEffects += InstInfo.hasSideEffects;
  2611. NumStores += InstInfo.mayStore;
  2612. NumLoads += InstInfo.mayLoad;
  2613. }
  2614. // Analyze the source pattern.
  2615. InstAnalyzer PatInfo(*this);
  2616. PatInfo.Analyze(&PTM);
  2617. // Collect error messages.
  2618. SmallVector<std::string, 4> Msgs;
  2619. // Check for missing flags in the output.
  2620. // Permit extra flags for now at least.
  2621. if (PatInfo.hasSideEffects && !NumSideEffects)
  2622. Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
  2623. // Don't verify store flags on instructions with side effects. At least for
  2624. // intrinsics, side effects implies mayStore.
  2625. if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
  2626. Msgs.push_back("pattern may store, but mayStore isn't set");
  2627. // Similarly, mayStore implies mayLoad on intrinsics.
  2628. if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
  2629. Msgs.push_back("pattern may load, but mayLoad isn't set");
  2630. // Print error messages.
  2631. if (Msgs.empty())
  2632. continue;
  2633. ++Errors;
  2634. for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
  2635. PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
  2636. (Instrs.size() == 1 ?
  2637. "instruction" : "output instructions"));
  2638. // Provide the location of the relevant instruction definitions.
  2639. for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
  2640. if (Instrs[i] != PTM.getSrcRecord())
  2641. PrintError(Instrs[i]->getLoc(), "defined here");
  2642. const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
  2643. if (InstInfo.InferredFrom &&
  2644. InstInfo.InferredFrom != InstInfo.TheDef &&
  2645. InstInfo.InferredFrom != PTM.getSrcRecord())
  2646. PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
  2647. }
  2648. }
  2649. if (Errors)
  2650. PrintFatalError("Errors in DAG patterns");
  2651. }
  2652. /// Given a pattern result with an unresolved type, see if we can find one
  2653. /// instruction with an unresolved result type. Force this result type to an
  2654. /// arbitrary element if it's possible types to converge results.
  2655. static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
  2656. if (N->isLeaf())
  2657. return false;
  2658. // Analyze children.
  2659. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2660. if (ForceArbitraryInstResultType(N->getChild(i), TP))
  2661. return true;
  2662. if (!N->getOperator()->isSubClassOf("Instruction"))
  2663. return false;
  2664. // If this type is already concrete or completely unknown we can't do
  2665. // anything.
  2666. for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
  2667. if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
  2668. continue;
  2669. // Otherwise, force its type to the first possibility (an arbitrary choice).
  2670. if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
  2671. return true;
  2672. }
  2673. return false;
  2674. }
  2675. void CodeGenDAGPatterns::ParsePatterns() {
  2676. std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
  2677. for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
  2678. Record *CurPattern = Patterns[i];
  2679. DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
  2680. // If the pattern references the null_frag, there's nothing to do.
  2681. if (hasNullFragReference(Tree))
  2682. continue;
  2683. TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
  2684. // Inline pattern fragments into it.
  2685. Pattern->InlinePatternFragments();
  2686. ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
  2687. if (LI->getSize() == 0) continue; // no pattern.
  2688. // Parse the instruction.
  2689. TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
  2690. // Inline pattern fragments into it.
  2691. Result->InlinePatternFragments();
  2692. if (Result->getNumTrees() != 1)
  2693. Result->error("Cannot handle instructions producing instructions "
  2694. "with temporaries yet!");
  2695. bool IterateInference;
  2696. bool InferredAllPatternTypes, InferredAllResultTypes;
  2697. do {
  2698. // Infer as many types as possible. If we cannot infer all of them, we
  2699. // can never do anything with this pattern: report it to the user.
  2700. InferredAllPatternTypes =
  2701. Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
  2702. // Infer as many types as possible. If we cannot infer all of them, we
  2703. // can never do anything with this pattern: report it to the user.
  2704. InferredAllResultTypes =
  2705. Result->InferAllTypes(&Pattern->getNamedNodesMap());
  2706. IterateInference = false;
  2707. // Apply the type of the result to the source pattern. This helps us
  2708. // resolve cases where the input type is known to be a pointer type (which
  2709. // is considered resolved), but the result knows it needs to be 32- or
  2710. // 64-bits. Infer the other way for good measure.
  2711. for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
  2712. Pattern->getTree(0)->getNumTypes());
  2713. i != e; ++i) {
  2714. IterateInference = Pattern->getTree(0)->
  2715. UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
  2716. IterateInference |= Result->getTree(0)->
  2717. UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
  2718. }
  2719. // If our iteration has converged and the input pattern's types are fully
  2720. // resolved but the result pattern is not fully resolved, we may have a
  2721. // situation where we have two instructions in the result pattern and
  2722. // the instructions require a common register class, but don't care about
  2723. // what actual MVT is used. This is actually a bug in our modelling:
  2724. // output patterns should have register classes, not MVTs.
  2725. //
  2726. // In any case, to handle this, we just go through and disambiguate some
  2727. // arbitrary types to the result pattern's nodes.
  2728. if (!IterateInference && InferredAllPatternTypes &&
  2729. !InferredAllResultTypes)
  2730. IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
  2731. *Result);
  2732. } while (IterateInference);
  2733. // Verify that we inferred enough types that we can do something with the
  2734. // pattern and result. If these fire the user has to add type casts.
  2735. if (!InferredAllPatternTypes)
  2736. Pattern->error("Could not infer all types in pattern!");
  2737. if (!InferredAllResultTypes) {
  2738. Pattern->dump();
  2739. Result->error("Could not infer all types in pattern result!");
  2740. }
  2741. // Validate that the input pattern is correct.
  2742. std::map<std::string, TreePatternNode*> InstInputs;
  2743. std::map<std::string, TreePatternNode*> InstResults;
  2744. std::vector<Record*> InstImpResults;
  2745. for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
  2746. FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
  2747. InstInputs, InstResults,
  2748. InstImpResults);
  2749. // Promote the xform function to be an explicit node if set.
  2750. TreePatternNode *DstPattern = Result->getOnlyTree();
  2751. std::vector<TreePatternNode*> ResultNodeOperands;
  2752. for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
  2753. TreePatternNode *OpNode = DstPattern->getChild(ii);
  2754. if (Record *Xform = OpNode->getTransformFn()) {
  2755. OpNode->setTransformFn(0);
  2756. std::vector<TreePatternNode*> Children;
  2757. Children.push_back(OpNode);
  2758. OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
  2759. }
  2760. ResultNodeOperands.push_back(OpNode);
  2761. }
  2762. DstPattern = Result->getOnlyTree();
  2763. if (!DstPattern->isLeaf())
  2764. DstPattern = new TreePatternNode(DstPattern->getOperator(),
  2765. ResultNodeOperands,
  2766. DstPattern->getNumTypes());
  2767. for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
  2768. DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
  2769. TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
  2770. Temp.InferAllTypes();
  2771. AddPatternToMatch(Pattern,
  2772. PatternToMatch(CurPattern,
  2773. CurPattern->getValueAsListInit("Predicates"),
  2774. Pattern->getTree(0),
  2775. Temp.getOnlyTree(), InstImpResults,
  2776. CurPattern->getValueAsInt("AddedComplexity"),
  2777. CurPattern->getID()));
  2778. }
  2779. }
  2780. /// CombineChildVariants - Given a bunch of permutations of each child of the
  2781. /// 'operator' node, put them together in all possible ways.
  2782. static void CombineChildVariants(TreePatternNode *Orig,
  2783. const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
  2784. std::vector<TreePatternNode*> &OutVariants,
  2785. CodeGenDAGPatterns &CDP,
  2786. const MultipleUseVarSet &DepVars) {
  2787. // Make sure that each operand has at least one variant to choose from.
  2788. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  2789. if (ChildVariants[i].empty())
  2790. return;
  2791. // The end result is an all-pairs construction of the resultant pattern.
  2792. std::vector<unsigned> Idxs;
  2793. Idxs.resize(ChildVariants.size());
  2794. bool NotDone;
  2795. do {
  2796. #ifndef NDEBUG
  2797. DEBUG(if (!Idxs.empty()) {
  2798. errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
  2799. for (unsigned i = 0; i < Idxs.size(); ++i) {
  2800. errs() << Idxs[i] << " ";
  2801. }
  2802. errs() << "]\n";
  2803. });
  2804. #endif
  2805. // Create the variant and add it to the output list.
  2806. std::vector<TreePatternNode*> NewChildren;
  2807. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  2808. NewChildren.push_back(ChildVariants[i][Idxs[i]]);
  2809. TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
  2810. Orig->getNumTypes());
  2811. // Copy over properties.
  2812. R->setName(Orig->getName());
  2813. R->setPredicateFns(Orig->getPredicateFns());
  2814. R->setTransformFn(Orig->getTransformFn());
  2815. for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
  2816. R->setType(i, Orig->getExtType(i));
  2817. // If this pattern cannot match, do not include it as a variant.
  2818. std::string ErrString;
  2819. if (!R->canPatternMatch(ErrString, CDP)) {
  2820. delete R;
  2821. } else {
  2822. bool AlreadyExists = false;
  2823. // Scan to see if this pattern has already been emitted. We can get
  2824. // duplication due to things like commuting:
  2825. // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
  2826. // which are the same pattern. Ignore the dups.
  2827. for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
  2828. if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
  2829. AlreadyExists = true;
  2830. break;
  2831. }
  2832. if (AlreadyExists)
  2833. delete R;
  2834. else
  2835. OutVariants.push_back(R);
  2836. }
  2837. // Increment indices to the next permutation by incrementing the
  2838. // indicies from last index backward, e.g., generate the sequence
  2839. // [0, 0], [0, 1], [1, 0], [1, 1].
  2840. int IdxsIdx;
  2841. for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
  2842. if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
  2843. Idxs[IdxsIdx] = 0;
  2844. else
  2845. break;
  2846. }
  2847. NotDone = (IdxsIdx >= 0);
  2848. } while (NotDone);
  2849. }
  2850. /// CombineChildVariants - A helper function for binary operators.
  2851. ///
  2852. static void CombineChildVariants(TreePatternNode *Orig,
  2853. const std::vector<TreePatternNode*> &LHS,
  2854. const std::vector<TreePatternNode*> &RHS,
  2855. std::vector<TreePatternNode*> &OutVariants,
  2856. CodeGenDAGPatterns &CDP,
  2857. const MultipleUseVarSet &DepVars) {
  2858. std::vector<std::vector<TreePatternNode*> > ChildVariants;
  2859. ChildVariants.push_back(LHS);
  2860. ChildVariants.push_back(RHS);
  2861. CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
  2862. }
  2863. static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
  2864. std::vector<TreePatternNode *> &Children) {
  2865. assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
  2866. Record *Operator = N->getOperator();
  2867. // Only permit raw nodes.
  2868. if (!N->getName().empty() || !N->getPredicateFns().empty() ||
  2869. N->getTransformFn()) {
  2870. Children.push_back(N);
  2871. return;
  2872. }
  2873. if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
  2874. Children.push_back(N->getChild(0));
  2875. else
  2876. GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
  2877. if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
  2878. Children.push_back(N->getChild(1));
  2879. else
  2880. GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
  2881. }
  2882. /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
  2883. /// the (potentially recursive) pattern by using algebraic laws.
  2884. ///
  2885. static void GenerateVariantsOf(TreePatternNode *N,
  2886. std::vector<TreePatternNode*> &OutVariants,
  2887. CodeGenDAGPatterns &CDP,
  2888. const MultipleUseVarSet &DepVars) {
  2889. // We cannot permute leaves.
  2890. if (N->isLeaf()) {
  2891. OutVariants.push_back(N);
  2892. return;
  2893. }
  2894. // Look up interesting info about the node.
  2895. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
  2896. // If this node is associative, re-associate.
  2897. if (NodeInfo.hasProperty(SDNPAssociative)) {
  2898. // Re-associate by pulling together all of the linked operators
  2899. std::vector<TreePatternNode*> MaximalChildren;
  2900. GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
  2901. // Only handle child sizes of 3. Otherwise we'll end up trying too many
  2902. // permutations.
  2903. if (MaximalChildren.size() == 3) {
  2904. // Find the variants of all of our maximal children.
  2905. std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
  2906. GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
  2907. GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
  2908. GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
  2909. // There are only two ways we can permute the tree:
  2910. // (A op B) op C and A op (B op C)
  2911. // Within these forms, we can also permute A/B/C.
  2912. // Generate legal pair permutations of A/B/C.
  2913. std::vector<TreePatternNode*> ABVariants;
  2914. std::vector<TreePatternNode*> BAVariants;
  2915. std::vector<TreePatternNode*> ACVariants;
  2916. std::vector<TreePatternNode*> CAVariants;
  2917. std::vector<TreePatternNode*> BCVariants;
  2918. std::vector<TreePatternNode*> CBVariants;
  2919. CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
  2920. CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
  2921. CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
  2922. CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
  2923. CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
  2924. CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
  2925. // Combine those into the result: (x op x) op x
  2926. CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
  2927. CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
  2928. CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
  2929. CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
  2930. CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
  2931. CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
  2932. // Combine those into the result: x op (x op x)
  2933. CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
  2934. CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
  2935. CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
  2936. CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
  2937. CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
  2938. CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
  2939. return;
  2940. }
  2941. }
  2942. // Compute permutations of all children.
  2943. std::vector<std::vector<TreePatternNode*> > ChildVariants;
  2944. ChildVariants.resize(N->getNumChildren());
  2945. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2946. GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
  2947. // Build all permutations based on how the children were formed.
  2948. CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
  2949. // If this node is commutative, consider the commuted order.
  2950. bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
  2951. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  2952. assert((N->getNumChildren()==2 || isCommIntrinsic) &&
  2953. "Commutative but doesn't have 2 children!");
  2954. // Don't count children which are actually register references.
  2955. unsigned NC = 0;
  2956. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  2957. TreePatternNode *Child = N->getChild(i);
  2958. if (Child->isLeaf())
  2959. if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
  2960. Record *RR = DI->getDef();
  2961. if (RR->isSubClassOf("Register"))
  2962. continue;
  2963. }
  2964. NC++;
  2965. }
  2966. // Consider the commuted order.
  2967. if (isCommIntrinsic) {
  2968. // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
  2969. // operands are the commutative operands, and there might be more operands
  2970. // after those.
  2971. assert(NC >= 3 &&
  2972. "Commutative intrinsic should have at least 3 childrean!");
  2973. std::vector<std::vector<TreePatternNode*> > Variants;
  2974. Variants.push_back(ChildVariants[0]); // Intrinsic id.
  2975. Variants.push_back(ChildVariants[2]);
  2976. Variants.push_back(ChildVariants[1]);
  2977. for (unsigned i = 3; i != NC; ++i)
  2978. Variants.push_back(ChildVariants[i]);
  2979. CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
  2980. } else if (NC == 2)
  2981. CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
  2982. OutVariants, CDP, DepVars);
  2983. }
  2984. }
  2985. // GenerateVariants - Generate variants. For example, commutative patterns can
  2986. // match multiple ways. Add them to PatternsToMatch as well.
  2987. void CodeGenDAGPatterns::GenerateVariants() {
  2988. DEBUG(errs() << "Generating instruction variants.\n");
  2989. // Loop over all of the patterns we've collected, checking to see if we can
  2990. // generate variants of the instruction, through the exploitation of
  2991. // identities. This permits the target to provide aggressive matching without
  2992. // the .td file having to contain tons of variants of instructions.
  2993. //
  2994. // Note that this loop adds new patterns to the PatternsToMatch list, but we
  2995. // intentionally do not reconsider these. Any variants of added patterns have
  2996. // already been added.
  2997. //
  2998. for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
  2999. MultipleUseVarSet DepVars;
  3000. std::vector<TreePatternNode*> Variants;
  3001. FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
  3002. DEBUG(errs() << "Dependent/multiply used variables: ");
  3003. DEBUG(DumpDepVars(DepVars));
  3004. DEBUG(errs() << "\n");
  3005. GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
  3006. DepVars);
  3007. assert(!Variants.empty() && "Must create at least original variant!");
  3008. Variants.erase(Variants.begin()); // Remove the original pattern.
  3009. if (Variants.empty()) // No variants for this pattern.
  3010. continue;
  3011. DEBUG(errs() << "FOUND VARIANTS OF: ";
  3012. PatternsToMatch[i].getSrcPattern()->dump();
  3013. errs() << "\n");
  3014. for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
  3015. TreePatternNode *Variant = Variants[v];
  3016. DEBUG(errs() << " VAR#" << v << ": ";
  3017. Variant->dump();
  3018. errs() << "\n");
  3019. // Scan to see if an instruction or explicit pattern already matches this.
  3020. bool AlreadyExists = false;
  3021. for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
  3022. // Skip if the top level predicates do not match.
  3023. if (PatternsToMatch[i].getPredicates() !=
  3024. PatternsToMatch[p].getPredicates())
  3025. continue;
  3026. // Check to see if this variant already exists.
  3027. if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
  3028. DepVars)) {
  3029. DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
  3030. AlreadyExists = true;
  3031. break;
  3032. }
  3033. }
  3034. // If we already have it, ignore the variant.
  3035. if (AlreadyExists) continue;
  3036. // Otherwise, add it to the list of patterns we have.
  3037. PatternsToMatch.
  3038. push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
  3039. PatternsToMatch[i].getPredicates(),
  3040. Variant, PatternsToMatch[i].getDstPattern(),
  3041. PatternsToMatch[i].getDstRegs(),
  3042. PatternsToMatch[i].getAddedComplexity(),
  3043. Record::getNewUID()));
  3044. }
  3045. DEBUG(errs() << "\n");
  3046. }
  3047. }