Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1 | //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===// |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 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 | // |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 10 | // This file implements the CodeGenDAGPatterns class, which is used to read and |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 11 | // represent the patterns present in a .td file for instructions. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Chris Lattner | 93c7e41 | 2008-01-05 23:37:52 +0000 | [diff] [blame] | 15 | #include "CodeGenDAGPatterns.h" |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 16 | #include "Record.h" |
| 17 | #include "llvm/ADT/StringExtras.h" |
| 18 | #include "llvm/Support/Debug.h" |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 19 | #include "llvm/Support/Streams.h" |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 20 | #include <set> |
| 21 | using namespace llvm; |
| 22 | |
| 23 | //===----------------------------------------------------------------------===// |
| 24 | // Helpers for working with extended types. |
| 25 | |
| 26 | /// FilterVTs - Filter a list of VT's according to a predicate. |
| 27 | /// |
| 28 | template<typename T> |
| 29 | static std::vector<MVT::ValueType> |
| 30 | FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) { |
| 31 | std::vector<MVT::ValueType> Result; |
| 32 | for (unsigned i = 0, e = InVTs.size(); i != e; ++i) |
| 33 | if (Filter(InVTs[i])) |
| 34 | Result.push_back(InVTs[i]); |
| 35 | return Result; |
| 36 | } |
| 37 | |
| 38 | template<typename T> |
| 39 | static std::vector<unsigned char> |
| 40 | FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) { |
| 41 | std::vector<unsigned char> Result; |
| 42 | for (unsigned i = 0, e = InVTs.size(); i != e; ++i) |
| 43 | if (Filter((MVT::ValueType)InVTs[i])) |
| 44 | Result.push_back(InVTs[i]); |
| 45 | return Result; |
| 46 | } |
| 47 | |
| 48 | static std::vector<unsigned char> |
| 49 | ConvertVTs(const std::vector<MVT::ValueType> &InVTs) { |
| 50 | std::vector<unsigned char> Result; |
| 51 | for (unsigned i = 0, e = InVTs.size(); i != e; ++i) |
| 52 | Result.push_back(InVTs[i]); |
| 53 | return Result; |
| 54 | } |
| 55 | |
| 56 | static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS, |
| 57 | const std::vector<unsigned char> &RHS) { |
| 58 | if (LHS.size() > RHS.size()) return false; |
| 59 | for (unsigned i = 0, e = LHS.size(); i != e; ++i) |
| 60 | if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end()) |
| 61 | return false; |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | /// isExtIntegerVT - Return true if the specified extended value type vector |
| 66 | /// contains isInt or an integer value type. |
| 67 | namespace llvm { |
| 68 | namespace MVT { |
| 69 | bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) { |
| 70 | assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!"); |
| 71 | return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty()); |
| 72 | } |
| 73 | |
| 74 | /// isExtFloatingPointVT - Return true if the specified extended value type |
| 75 | /// vector contains isFP or a FP value type. |
| 76 | bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) { |
| 77 | assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!"); |
| 78 | return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty()); |
| 79 | } |
| 80 | } // end namespace MVT. |
| 81 | } // end namespace llvm. |
| 82 | |
| 83 | //===----------------------------------------------------------------------===// |
| 84 | // SDTypeConstraint implementation |
| 85 | // |
| 86 | |
| 87 | SDTypeConstraint::SDTypeConstraint(Record *R) { |
| 88 | OperandNo = R->getValueAsInt("OperandNum"); |
| 89 | |
| 90 | if (R->isSubClassOf("SDTCisVT")) { |
| 91 | ConstraintType = SDTCisVT; |
| 92 | x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT")); |
| 93 | } else if (R->isSubClassOf("SDTCisPtrTy")) { |
| 94 | ConstraintType = SDTCisPtrTy; |
| 95 | } else if (R->isSubClassOf("SDTCisInt")) { |
| 96 | ConstraintType = SDTCisInt; |
| 97 | } else if (R->isSubClassOf("SDTCisFP")) { |
| 98 | ConstraintType = SDTCisFP; |
| 99 | } else if (R->isSubClassOf("SDTCisSameAs")) { |
| 100 | ConstraintType = SDTCisSameAs; |
| 101 | x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum"); |
| 102 | } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) { |
| 103 | ConstraintType = SDTCisVTSmallerThanOp; |
| 104 | x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = |
| 105 | R->getValueAsInt("OtherOperandNum"); |
| 106 | } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) { |
| 107 | ConstraintType = SDTCisOpSmallerThanOp; |
| 108 | x.SDTCisOpSmallerThanOp_Info.BigOperandNum = |
| 109 | R->getValueAsInt("BigOperandNum"); |
| 110 | } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) { |
| 111 | ConstraintType = SDTCisIntVectorOfSameSize; |
| 112 | x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum = |
| 113 | R->getValueAsInt("OtherOpNum"); |
| 114 | } else { |
| 115 | cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n"; |
| 116 | exit(1); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// getOperandNum - Return the node corresponding to operand #OpNo in tree |
| 121 | /// N, which has NumResults results. |
| 122 | TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo, |
| 123 | TreePatternNode *N, |
| 124 | unsigned NumResults) const { |
| 125 | assert(NumResults <= 1 && |
| 126 | "We only work with nodes with zero or one result so far!"); |
| 127 | |
| 128 | if (OpNo >= (NumResults + N->getNumChildren())) { |
| 129 | cerr << "Invalid operand number " << OpNo << " "; |
| 130 | N->dump(); |
| 131 | cerr << '\n'; |
| 132 | exit(1); |
| 133 | } |
| 134 | |
| 135 | if (OpNo < NumResults) |
| 136 | return N; // FIXME: need value # |
| 137 | else |
| 138 | return N->getChild(OpNo-NumResults); |
| 139 | } |
| 140 | |
| 141 | /// ApplyTypeConstraint - Given a node in a pattern, apply this type |
| 142 | /// constraint to the nodes operands. This returns true if it makes a |
| 143 | /// change, false otherwise. If a type contradiction is found, throw an |
| 144 | /// exception. |
| 145 | bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N, |
| 146 | const SDNodeInfo &NodeInfo, |
| 147 | TreePattern &TP) const { |
| 148 | unsigned NumResults = NodeInfo.getNumResults(); |
| 149 | assert(NumResults <= 1 && |
| 150 | "We only work with nodes with zero or one result so far!"); |
| 151 | |
| 152 | // Check that the number of operands is sane. Negative operands -> varargs. |
| 153 | if (NodeInfo.getNumOperands() >= 0) { |
| 154 | if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands()) |
| 155 | TP.error(N->getOperator()->getName() + " node requires exactly " + |
| 156 | itostr(NodeInfo.getNumOperands()) + " operands!"); |
| 157 | } |
| 158 | |
| 159 | const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo(); |
| 160 | |
| 161 | TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults); |
| 162 | |
| 163 | switch (ConstraintType) { |
| 164 | default: assert(0 && "Unknown constraint type!"); |
| 165 | case SDTCisVT: |
| 166 | // Operand must be a particular type. |
| 167 | return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP); |
| 168 | case SDTCisPtrTy: { |
| 169 | // Operand must be same as target pointer type. |
| 170 | return NodeToApply->UpdateNodeType(MVT::iPTR, TP); |
| 171 | } |
| 172 | case SDTCisInt: { |
| 173 | // If there is only one integer type supported, this must be it. |
| 174 | std::vector<MVT::ValueType> IntVTs = |
| 175 | FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger); |
| 176 | |
| 177 | // If we found exactly one supported integer type, apply it. |
| 178 | if (IntVTs.size() == 1) |
| 179 | return NodeToApply->UpdateNodeType(IntVTs[0], TP); |
| 180 | return NodeToApply->UpdateNodeType(MVT::isInt, TP); |
| 181 | } |
| 182 | case SDTCisFP: { |
| 183 | // If there is only one FP type supported, this must be it. |
| 184 | std::vector<MVT::ValueType> FPVTs = |
| 185 | FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint); |
| 186 | |
| 187 | // If we found exactly one supported FP type, apply it. |
| 188 | if (FPVTs.size() == 1) |
| 189 | return NodeToApply->UpdateNodeType(FPVTs[0], TP); |
| 190 | return NodeToApply->UpdateNodeType(MVT::isFP, TP); |
| 191 | } |
| 192 | case SDTCisSameAs: { |
| 193 | TreePatternNode *OtherNode = |
| 194 | getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults); |
| 195 | return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) | |
| 196 | OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP); |
| 197 | } |
| 198 | case SDTCisVTSmallerThanOp: { |
| 199 | // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must |
| 200 | // have an integer type that is smaller than the VT. |
| 201 | if (!NodeToApply->isLeaf() || |
| 202 | !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) || |
| 203 | !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef() |
| 204 | ->isSubClassOf("ValueType")) |
| 205 | TP.error(N->getOperator()->getName() + " expects a VT operand!"); |
| 206 | MVT::ValueType VT = |
| 207 | getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()); |
| 208 | if (!MVT::isInteger(VT)) |
| 209 | TP.error(N->getOperator()->getName() + " VT operand must be integer!"); |
| 210 | |
| 211 | TreePatternNode *OtherNode = |
| 212 | getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults); |
| 213 | |
| 214 | // It must be integer. |
| 215 | bool MadeChange = false; |
| 216 | MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP); |
| 217 | |
| 218 | // This code only handles nodes that have one type set. Assert here so |
| 219 | // that we can change this if we ever need to deal with multiple value |
| 220 | // types at this point. |
| 221 | assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!"); |
| 222 | if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT) |
| 223 | OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error. |
| 224 | return false; |
| 225 | } |
| 226 | case SDTCisOpSmallerThanOp: { |
| 227 | TreePatternNode *BigOperand = |
| 228 | getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults); |
| 229 | |
| 230 | // Both operands must be integer or FP, but we don't care which. |
| 231 | bool MadeChange = false; |
| 232 | |
| 233 | // This code does not currently handle nodes which have multiple types, |
| 234 | // where some types are integer, and some are fp. Assert that this is not |
| 235 | // the case. |
| 236 | assert(!(MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) && |
| 237 | MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) && |
| 238 | !(MVT::isExtIntegerInVTs(BigOperand->getExtTypes()) && |
| 239 | MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) && |
| 240 | "SDTCisOpSmallerThanOp does not handle mixed int/fp types!"); |
| 241 | if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) |
| 242 | MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP); |
| 243 | else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) |
| 244 | MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP); |
| 245 | if (MVT::isExtIntegerInVTs(BigOperand->getExtTypes())) |
| 246 | MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP); |
| 247 | else if (MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) |
| 248 | MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP); |
| 249 | |
| 250 | std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes(); |
| 251 | |
| 252 | if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) { |
| 253 | VTs = FilterVTs(VTs, MVT::isInteger); |
| 254 | } else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) { |
| 255 | VTs = FilterVTs(VTs, MVT::isFloatingPoint); |
| 256 | } else { |
| 257 | VTs.clear(); |
| 258 | } |
| 259 | |
| 260 | switch (VTs.size()) { |
| 261 | default: // Too many VT's to pick from. |
| 262 | case 0: break; // No info yet. |
| 263 | case 1: |
| 264 | // Only one VT of this flavor. Cannot ever satisify the constraints. |
| 265 | return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw |
| 266 | case 2: |
| 267 | // If we have exactly two possible types, the little operand must be the |
| 268 | // small one, the big operand should be the big one. Common with |
| 269 | // float/double for example. |
| 270 | assert(VTs[0] < VTs[1] && "Should be sorted!"); |
| 271 | MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP); |
| 272 | MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP); |
| 273 | break; |
| 274 | } |
| 275 | return MadeChange; |
| 276 | } |
| 277 | case SDTCisIntVectorOfSameSize: { |
| 278 | TreePatternNode *OtherOperand = |
| 279 | getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum, |
| 280 | N, NumResults); |
| 281 | if (OtherOperand->hasTypeSet()) { |
| 282 | if (!MVT::isVector(OtherOperand->getTypeNum(0))) |
| 283 | TP.error(N->getOperator()->getName() + " VT operand must be a vector!"); |
| 284 | MVT::ValueType IVT = OtherOperand->getTypeNum(0); |
| 285 | IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT)); |
| 286 | return NodeToApply->UpdateNodeType(IVT, TP); |
| 287 | } |
| 288 | return false; |
| 289 | } |
| 290 | } |
| 291 | return false; |
| 292 | } |
| 293 | |
| 294 | //===----------------------------------------------------------------------===// |
| 295 | // SDNodeInfo implementation |
| 296 | // |
| 297 | SDNodeInfo::SDNodeInfo(Record *R) : Def(R) { |
| 298 | EnumName = R->getValueAsString("Opcode"); |
| 299 | SDClassName = R->getValueAsString("SDClass"); |
| 300 | Record *TypeProfile = R->getValueAsDef("TypeProfile"); |
| 301 | NumResults = TypeProfile->getValueAsInt("NumResults"); |
| 302 | NumOperands = TypeProfile->getValueAsInt("NumOperands"); |
| 303 | |
| 304 | // Parse the properties. |
| 305 | Properties = 0; |
| 306 | std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties"); |
| 307 | for (unsigned i = 0, e = PropList.size(); i != e; ++i) { |
| 308 | if (PropList[i]->getName() == "SDNPCommutative") { |
| 309 | Properties |= 1 << SDNPCommutative; |
| 310 | } else if (PropList[i]->getName() == "SDNPAssociative") { |
| 311 | Properties |= 1 << SDNPAssociative; |
| 312 | } else if (PropList[i]->getName() == "SDNPHasChain") { |
| 313 | Properties |= 1 << SDNPHasChain; |
| 314 | } else if (PropList[i]->getName() == "SDNPOutFlag") { |
| 315 | Properties |= 1 << SDNPOutFlag; |
| 316 | } else if (PropList[i]->getName() == "SDNPInFlag") { |
| 317 | Properties |= 1 << SDNPInFlag; |
| 318 | } else if (PropList[i]->getName() == "SDNPOptInFlag") { |
| 319 | Properties |= 1 << SDNPOptInFlag; |
| 320 | } else { |
| 321 | cerr << "Unknown SD Node property '" << PropList[i]->getName() |
| 322 | << "' on node '" << R->getName() << "'!\n"; |
| 323 | exit(1); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | |
| 328 | // Parse the type constraints. |
| 329 | std::vector<Record*> ConstraintList = |
| 330 | TypeProfile->getValueAsListOfDefs("Constraints"); |
| 331 | TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end()); |
| 332 | } |
| 333 | |
| 334 | //===----------------------------------------------------------------------===// |
| 335 | // TreePatternNode implementation |
| 336 | // |
| 337 | |
| 338 | TreePatternNode::~TreePatternNode() { |
| 339 | #if 0 // FIXME: implement refcounted tree nodes! |
| 340 | for (unsigned i = 0, e = getNumChildren(); i != e; ++i) |
| 341 | delete getChild(i); |
| 342 | #endif |
| 343 | } |
| 344 | |
| 345 | /// UpdateNodeType - Set the node type of N to VT if VT contains |
| 346 | /// information. If N already contains a conflicting type, then throw an |
| 347 | /// exception. This returns true if any information was updated. |
| 348 | /// |
| 349 | bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs, |
| 350 | TreePattern &TP) { |
| 351 | assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!"); |
| 352 | |
| 353 | if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs)) |
| 354 | return false; |
| 355 | if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) { |
| 356 | setTypes(ExtVTs); |
| 357 | return true; |
| 358 | } |
| 359 | |
| 360 | if (getExtTypeNum(0) == MVT::iPTR) { |
| 361 | if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt) |
| 362 | return false; |
| 363 | if (MVT::isExtIntegerInVTs(ExtVTs)) { |
| 364 | std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger); |
| 365 | if (FVTs.size()) { |
| 366 | setTypes(ExtVTs); |
| 367 | return true; |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | if (ExtVTs[0] == MVT::isInt && MVT::isExtIntegerInVTs(getExtTypes())) { |
| 373 | assert(hasTypeSet() && "should be handled above!"); |
| 374 | std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger); |
| 375 | if (getExtTypes() == FVTs) |
| 376 | return false; |
| 377 | setTypes(FVTs); |
| 378 | return true; |
| 379 | } |
| 380 | if (ExtVTs[0] == MVT::iPTR && MVT::isExtIntegerInVTs(getExtTypes())) { |
| 381 | //assert(hasTypeSet() && "should be handled above!"); |
| 382 | std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger); |
| 383 | if (getExtTypes() == FVTs) |
| 384 | return false; |
| 385 | if (FVTs.size()) { |
| 386 | setTypes(FVTs); |
| 387 | return true; |
| 388 | } |
| 389 | } |
| 390 | if (ExtVTs[0] == MVT::isFP && MVT::isExtFloatingPointInVTs(getExtTypes())) { |
| 391 | assert(hasTypeSet() && "should be handled above!"); |
| 392 | std::vector<unsigned char> FVTs = |
| 393 | FilterEVTs(getExtTypes(), MVT::isFloatingPoint); |
| 394 | if (getExtTypes() == FVTs) |
| 395 | return false; |
| 396 | setTypes(FVTs); |
| 397 | return true; |
| 398 | } |
| 399 | |
| 400 | // If we know this is an int or fp type, and we are told it is a specific one, |
| 401 | // take the advice. |
| 402 | // |
| 403 | // Similarly, we should probably set the type here to the intersection of |
| 404 | // {isInt|isFP} and ExtVTs |
| 405 | if ((getExtTypeNum(0) == MVT::isInt && MVT::isExtIntegerInVTs(ExtVTs)) || |
| 406 | (getExtTypeNum(0) == MVT::isFP && MVT::isExtFloatingPointInVTs(ExtVTs))){ |
| 407 | setTypes(ExtVTs); |
| 408 | return true; |
| 409 | } |
| 410 | if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) { |
| 411 | setTypes(ExtVTs); |
| 412 | return true; |
| 413 | } |
| 414 | |
| 415 | if (isLeaf()) { |
| 416 | dump(); |
| 417 | cerr << " "; |
| 418 | TP.error("Type inference contradiction found in node!"); |
| 419 | } else { |
| 420 | TP.error("Type inference contradiction found in node " + |
| 421 | getOperator()->getName() + "!"); |
| 422 | } |
| 423 | return true; // unreachable |
| 424 | } |
| 425 | |
| 426 | |
| 427 | void TreePatternNode::print(std::ostream &OS) const { |
| 428 | if (isLeaf()) { |
| 429 | OS << *getLeafValue(); |
| 430 | } else { |
| 431 | OS << "(" << getOperator()->getName(); |
| 432 | } |
| 433 | |
| 434 | // FIXME: At some point we should handle printing all the value types for |
| 435 | // nodes that are multiply typed. |
| 436 | switch (getExtTypeNum(0)) { |
| 437 | case MVT::Other: OS << ":Other"; break; |
| 438 | case MVT::isInt: OS << ":isInt"; break; |
| 439 | case MVT::isFP : OS << ":isFP"; break; |
| 440 | case MVT::isUnknown: ; /*OS << ":?";*/ break; |
| 441 | case MVT::iPTR: OS << ":iPTR"; break; |
| 442 | default: { |
| 443 | std::string VTName = llvm::getName(getTypeNum(0)); |
| 444 | // Strip off MVT:: prefix if present. |
| 445 | if (VTName.substr(0,5) == "MVT::") |
| 446 | VTName = VTName.substr(5); |
| 447 | OS << ":" << VTName; |
| 448 | break; |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | if (!isLeaf()) { |
| 453 | if (getNumChildren() != 0) { |
| 454 | OS << " "; |
| 455 | getChild(0)->print(OS); |
| 456 | for (unsigned i = 1, e = getNumChildren(); i != e; ++i) { |
| 457 | OS << ", "; |
| 458 | getChild(i)->print(OS); |
| 459 | } |
| 460 | } |
| 461 | OS << ")"; |
| 462 | } |
| 463 | |
| 464 | if (!PredicateFn.empty()) |
| 465 | OS << "<<P:" << PredicateFn << ">>"; |
| 466 | if (TransformFn) |
| 467 | OS << "<<X:" << TransformFn->getName() << ">>"; |
| 468 | if (!getName().empty()) |
| 469 | OS << ":$" << getName(); |
| 470 | |
| 471 | } |
| 472 | void TreePatternNode::dump() const { |
| 473 | print(*cerr.stream()); |
| 474 | } |
| 475 | |
| 476 | /// isIsomorphicTo - Return true if this node is recursively isomorphic to |
| 477 | /// the specified node. For this comparison, all of the state of the node |
| 478 | /// is considered, except for the assigned name. Nodes with differing names |
| 479 | /// that are otherwise identical are considered isomorphic. |
| 480 | bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const { |
| 481 | if (N == this) return true; |
| 482 | if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() || |
| 483 | getPredicateFn() != N->getPredicateFn() || |
| 484 | getTransformFn() != N->getTransformFn()) |
| 485 | return false; |
| 486 | |
| 487 | if (isLeaf()) { |
| 488 | if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) |
| 489 | if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) |
| 490 | return DI->getDef() == NDI->getDef(); |
| 491 | return getLeafValue() == N->getLeafValue(); |
| 492 | } |
| 493 | |
| 494 | if (N->getOperator() != getOperator() || |
| 495 | N->getNumChildren() != getNumChildren()) return false; |
| 496 | for (unsigned i = 0, e = getNumChildren(); i != e; ++i) |
| 497 | if (!getChild(i)->isIsomorphicTo(N->getChild(i))) |
| 498 | return false; |
| 499 | return true; |
| 500 | } |
| 501 | |
| 502 | /// clone - Make a copy of this tree and all of its children. |
| 503 | /// |
| 504 | TreePatternNode *TreePatternNode::clone() const { |
| 505 | TreePatternNode *New; |
| 506 | if (isLeaf()) { |
| 507 | New = new TreePatternNode(getLeafValue()); |
| 508 | } else { |
| 509 | std::vector<TreePatternNode*> CChildren; |
| 510 | CChildren.reserve(Children.size()); |
| 511 | for (unsigned i = 0, e = getNumChildren(); i != e; ++i) |
| 512 | CChildren.push_back(getChild(i)->clone()); |
| 513 | New = new TreePatternNode(getOperator(), CChildren); |
| 514 | } |
| 515 | New->setName(getName()); |
| 516 | New->setTypes(getExtTypes()); |
| 517 | New->setPredicateFn(getPredicateFn()); |
| 518 | New->setTransformFn(getTransformFn()); |
| 519 | return New; |
| 520 | } |
| 521 | |
| 522 | /// SubstituteFormalArguments - Replace the formal arguments in this tree |
| 523 | /// with actual values specified by ArgMap. |
| 524 | void TreePatternNode:: |
| 525 | SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) { |
| 526 | if (isLeaf()) return; |
| 527 | |
| 528 | for (unsigned i = 0, e = getNumChildren(); i != e; ++i) { |
| 529 | TreePatternNode *Child = getChild(i); |
| 530 | if (Child->isLeaf()) { |
| 531 | Init *Val = Child->getLeafValue(); |
| 532 | if (dynamic_cast<DefInit*>(Val) && |
| 533 | static_cast<DefInit*>(Val)->getDef()->getName() == "node") { |
| 534 | // We found a use of a formal argument, replace it with its value. |
| 535 | Child = ArgMap[Child->getName()]; |
| 536 | assert(Child && "Couldn't find formal argument!"); |
| 537 | setChild(i, Child); |
| 538 | } |
| 539 | } else { |
| 540 | getChild(i)->SubstituteFormalArguments(ArgMap); |
| 541 | } |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | |
| 546 | /// InlinePatternFragments - If this pattern refers to any pattern |
| 547 | /// fragments, inline them into place, giving us a pattern without any |
| 548 | /// PatFrag references. |
| 549 | TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) { |
| 550 | if (isLeaf()) return this; // nothing to do. |
| 551 | Record *Op = getOperator(); |
| 552 | |
| 553 | if (!Op->isSubClassOf("PatFrag")) { |
| 554 | // Just recursively inline children nodes. |
| 555 | for (unsigned i = 0, e = getNumChildren(); i != e; ++i) |
| 556 | setChild(i, getChild(i)->InlinePatternFragments(TP)); |
| 557 | return this; |
| 558 | } |
| 559 | |
| 560 | // Otherwise, we found a reference to a fragment. First, look up its |
| 561 | // TreePattern record. |
| 562 | TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op); |
| 563 | |
| 564 | // Verify that we are passing the right number of operands. |
| 565 | if (Frag->getNumArgs() != Children.size()) |
| 566 | TP.error("'" + Op->getName() + "' fragment requires " + |
| 567 | utostr(Frag->getNumArgs()) + " operands!"); |
| 568 | |
| 569 | TreePatternNode *FragTree = Frag->getOnlyTree()->clone(); |
| 570 | |
| 571 | // Resolve formal arguments to their actual value. |
| 572 | if (Frag->getNumArgs()) { |
| 573 | // Compute the map of formal to actual arguments. |
| 574 | std::map<std::string, TreePatternNode*> ArgMap; |
| 575 | for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) |
| 576 | ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP); |
| 577 | |
| 578 | FragTree->SubstituteFormalArguments(ArgMap); |
| 579 | } |
| 580 | |
| 581 | FragTree->setName(getName()); |
| 582 | FragTree->UpdateNodeType(getExtTypes(), TP); |
| 583 | |
| 584 | // Get a new copy of this fragment to stitch into here. |
| 585 | //delete this; // FIXME: implement refcounting! |
| 586 | return FragTree; |
| 587 | } |
| 588 | |
| 589 | /// getImplicitType - Check to see if the specified record has an implicit |
| 590 | /// type which should be applied to it. This infer the type of register |
| 591 | /// references from the register file information, for example. |
| 592 | /// |
| 593 | static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters, |
| 594 | TreePattern &TP) { |
| 595 | // Some common return values |
| 596 | std::vector<unsigned char> Unknown(1, MVT::isUnknown); |
| 597 | std::vector<unsigned char> Other(1, MVT::Other); |
| 598 | |
| 599 | // Check to see if this is a register or a register class... |
| 600 | if (R->isSubClassOf("RegisterClass")) { |
| 601 | if (NotRegisters) |
| 602 | return Unknown; |
| 603 | const CodeGenRegisterClass &RC = |
| 604 | TP.getDAGPatterns().getTargetInfo().getRegisterClass(R); |
| 605 | return ConvertVTs(RC.getValueTypes()); |
| 606 | } else if (R->isSubClassOf("PatFrag")) { |
| 607 | // Pattern fragment types will be resolved when they are inlined. |
| 608 | return Unknown; |
| 609 | } else if (R->isSubClassOf("Register")) { |
| 610 | if (NotRegisters) |
| 611 | return Unknown; |
| 612 | const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); |
| 613 | return T.getRegisterVTs(R); |
| 614 | } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) { |
| 615 | // Using a VTSDNode or CondCodeSDNode. |
| 616 | return Other; |
| 617 | } else if (R->isSubClassOf("ComplexPattern")) { |
| 618 | if (NotRegisters) |
| 619 | return Unknown; |
| 620 | std::vector<unsigned char> |
| 621 | ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType()); |
| 622 | return ComplexPat; |
| 623 | } else if (R->getName() == "ptr_rc") { |
| 624 | Other[0] = MVT::iPTR; |
| 625 | return Other; |
| 626 | } else if (R->getName() == "node" || R->getName() == "srcvalue" || |
| 627 | R->getName() == "zero_reg") { |
| 628 | // Placeholder. |
| 629 | return Unknown; |
| 630 | } |
| 631 | |
| 632 | TP.error("Unknown node flavor used in pattern: " + R->getName()); |
| 633 | return Other; |
| 634 | } |
| 635 | |
| 636 | /// ApplyTypeConstraints - Apply all of the type constraints relevent to |
| 637 | /// this node and its children in the tree. This returns true if it makes a |
| 638 | /// change, false otherwise. If a type contradiction is found, throw an |
| 639 | /// exception. |
| 640 | bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) { |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 641 | CodeGenDAGPatterns &CDP = TP.getDAGPatterns(); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 642 | if (isLeaf()) { |
| 643 | if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) { |
| 644 | // If it's a regclass or something else known, include the type. |
| 645 | return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP); |
| 646 | } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) { |
| 647 | // Int inits are always integers. :) |
| 648 | bool MadeChange = UpdateNodeType(MVT::isInt, TP); |
| 649 | |
| 650 | if (hasTypeSet()) { |
| 651 | // At some point, it may make sense for this tree pattern to have |
| 652 | // multiple types. Assert here that it does not, so we revisit this |
| 653 | // code when appropriate. |
| 654 | assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!"); |
| 655 | MVT::ValueType VT = getTypeNum(0); |
| 656 | for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i) |
| 657 | assert(getTypeNum(i) == VT && "TreePattern has too many types!"); |
| 658 | |
| 659 | VT = getTypeNum(0); |
| 660 | if (VT != MVT::iPTR) { |
| 661 | unsigned Size = MVT::getSizeInBits(VT); |
| 662 | // Make sure that the value is representable for this type. |
| 663 | if (Size < 32) { |
| 664 | int Val = (II->getValue() << (32-Size)) >> (32-Size); |
| 665 | if (Val != II->getValue()) |
| 666 | TP.error("Sign-extended integer value '" + itostr(II->getValue())+ |
| 667 | "' is out of range for type '" + |
| 668 | getEnumName(getTypeNum(0)) + "'!"); |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | return MadeChange; |
| 674 | } |
| 675 | return false; |
| 676 | } |
| 677 | |
| 678 | // special handling for set, which isn't really an SDNode. |
| 679 | if (getOperator()->getName() == "set") { |
| 680 | assert (getNumChildren() >= 2 && "Missing RHS of a set?"); |
| 681 | unsigned NC = getNumChildren(); |
| 682 | bool MadeChange = false; |
| 683 | for (unsigned i = 0; i < NC-1; ++i) { |
| 684 | MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters); |
| 685 | MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters); |
| 686 | |
| 687 | // Types of operands must match. |
| 688 | MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(), |
| 689 | TP); |
| 690 | MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(), |
| 691 | TP); |
| 692 | MadeChange |= UpdateNodeType(MVT::isVoid, TP); |
| 693 | } |
| 694 | return MadeChange; |
| 695 | } else if (getOperator()->getName() == "implicit" || |
| 696 | getOperator()->getName() == "parallel") { |
| 697 | bool MadeChange = false; |
| 698 | for (unsigned i = 0; i < getNumChildren(); ++i) |
| 699 | MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters); |
| 700 | MadeChange |= UpdateNodeType(MVT::isVoid, TP); |
| 701 | return MadeChange; |
| 702 | } else if (getOperator() == CDP.get_intrinsic_void_sdnode() || |
| 703 | getOperator() == CDP.get_intrinsic_w_chain_sdnode() || |
| 704 | getOperator() == CDP.get_intrinsic_wo_chain_sdnode()) { |
| 705 | unsigned IID = |
| 706 | dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue(); |
| 707 | const CodeGenIntrinsic &Int = CDP.getIntrinsicInfo(IID); |
| 708 | bool MadeChange = false; |
| 709 | |
| 710 | // Apply the result type to the node. |
| 711 | MadeChange = UpdateNodeType(Int.ArgVTs[0], TP); |
| 712 | |
| 713 | if (getNumChildren() != Int.ArgVTs.size()) |
| 714 | TP.error("Intrinsic '" + Int.Name + "' expects " + |
| 715 | utostr(Int.ArgVTs.size()-1) + " operands, not " + |
| 716 | utostr(getNumChildren()-1) + " operands!"); |
| 717 | |
| 718 | // Apply type info to the intrinsic ID. |
| 719 | MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP); |
| 720 | |
| 721 | for (unsigned i = 1, e = getNumChildren(); i != e; ++i) { |
| 722 | MVT::ValueType OpVT = Int.ArgVTs[i]; |
| 723 | MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP); |
| 724 | MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); |
| 725 | } |
| 726 | return MadeChange; |
| 727 | } else if (getOperator()->isSubClassOf("SDNode")) { |
| 728 | const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator()); |
| 729 | |
| 730 | bool MadeChange = NI.ApplyTypeConstraints(this, TP); |
| 731 | for (unsigned i = 0, e = getNumChildren(); i != e; ++i) |
| 732 | MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); |
| 733 | // Branch, etc. do not produce results and top-level forms in instr pattern |
| 734 | // must have void types. |
| 735 | if (NI.getNumResults() == 0) |
| 736 | MadeChange |= UpdateNodeType(MVT::isVoid, TP); |
| 737 | |
| 738 | // If this is a vector_shuffle operation, apply types to the build_vector |
| 739 | // operation. The types of the integers don't matter, but this ensures they |
| 740 | // won't get checked. |
| 741 | if (getOperator()->getName() == "vector_shuffle" && |
| 742 | getChild(2)->getOperator()->getName() == "build_vector") { |
| 743 | TreePatternNode *BV = getChild(2); |
| 744 | const std::vector<MVT::ValueType> &LegalVTs |
| 745 | = CDP.getTargetInfo().getLegalValueTypes(); |
| 746 | MVT::ValueType LegalIntVT = MVT::Other; |
| 747 | for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i) |
| 748 | if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) { |
| 749 | LegalIntVT = LegalVTs[i]; |
| 750 | break; |
| 751 | } |
| 752 | assert(LegalIntVT != MVT::Other && "No legal integer VT?"); |
| 753 | |
| 754 | for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i) |
| 755 | MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP); |
| 756 | } |
| 757 | return MadeChange; |
| 758 | } else if (getOperator()->isSubClassOf("Instruction")) { |
| 759 | const DAGInstruction &Inst = CDP.getInstruction(getOperator()); |
| 760 | bool MadeChange = false; |
| 761 | unsigned NumResults = Inst.getNumResults(); |
| 762 | |
| 763 | assert(NumResults <= 1 && |
| 764 | "Only supports zero or one result instrs!"); |
| 765 | |
| 766 | CodeGenInstruction &InstInfo = |
| 767 | CDP.getTargetInfo().getInstruction(getOperator()->getName()); |
| 768 | // Apply the result type to the node |
| 769 | if (NumResults == 0 || InstInfo.NumDefs == 0) { |
| 770 | MadeChange = UpdateNodeType(MVT::isVoid, TP); |
| 771 | } else { |
| 772 | Record *ResultNode = Inst.getResult(0); |
| 773 | |
| 774 | if (ResultNode->getName() == "ptr_rc") { |
| 775 | std::vector<unsigned char> VT; |
| 776 | VT.push_back(MVT::iPTR); |
| 777 | MadeChange = UpdateNodeType(VT, TP); |
| 778 | } else { |
| 779 | assert(ResultNode->isSubClassOf("RegisterClass") && |
| 780 | "Operands should be register classes!"); |
| 781 | |
| 782 | const CodeGenRegisterClass &RC = |
| 783 | CDP.getTargetInfo().getRegisterClass(ResultNode); |
| 784 | MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP); |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | unsigned ChildNo = 0; |
| 789 | for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) { |
| 790 | Record *OperandNode = Inst.getOperand(i); |
| 791 | |
| 792 | // If the instruction expects a predicate or optional def operand, we |
| 793 | // codegen this by setting the operand to it's default value if it has a |
| 794 | // non-empty DefaultOps field. |
| 795 | if ((OperandNode->isSubClassOf("PredicateOperand") || |
| 796 | OperandNode->isSubClassOf("OptionalDefOperand")) && |
| 797 | !CDP.getDefaultOperand(OperandNode).DefaultOps.empty()) |
| 798 | continue; |
| 799 | |
| 800 | // Verify that we didn't run out of provided operands. |
| 801 | if (ChildNo >= getNumChildren()) |
| 802 | TP.error("Instruction '" + getOperator()->getName() + |
| 803 | "' expects more operands than were provided."); |
| 804 | |
| 805 | MVT::ValueType VT; |
| 806 | TreePatternNode *Child = getChild(ChildNo++); |
| 807 | if (OperandNode->isSubClassOf("RegisterClass")) { |
| 808 | const CodeGenRegisterClass &RC = |
| 809 | CDP.getTargetInfo().getRegisterClass(OperandNode); |
| 810 | MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP); |
| 811 | } else if (OperandNode->isSubClassOf("Operand")) { |
| 812 | VT = getValueType(OperandNode->getValueAsDef("Type")); |
| 813 | MadeChange |= Child->UpdateNodeType(VT, TP); |
| 814 | } else if (OperandNode->getName() == "ptr_rc") { |
| 815 | MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP); |
| 816 | } else { |
| 817 | assert(0 && "Unknown operand type!"); |
| 818 | abort(); |
| 819 | } |
| 820 | MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters); |
| 821 | } |
| 822 | |
| 823 | if (ChildNo != getNumChildren()) |
| 824 | TP.error("Instruction '" + getOperator()->getName() + |
| 825 | "' was provided too many operands!"); |
| 826 | |
| 827 | return MadeChange; |
| 828 | } else { |
| 829 | assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!"); |
| 830 | |
| 831 | // Node transforms always take one operand. |
| 832 | if (getNumChildren() != 1) |
| 833 | TP.error("Node transform '" + getOperator()->getName() + |
| 834 | "' requires one operand!"); |
| 835 | |
| 836 | // If either the output or input of the xform does not have exact |
| 837 | // type info. We assume they must be the same. Otherwise, it is perfectly |
| 838 | // legal to transform from one type to a completely different type. |
| 839 | if (!hasTypeSet() || !getChild(0)->hasTypeSet()) { |
| 840 | bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP); |
| 841 | MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP); |
| 842 | return MadeChange; |
| 843 | } |
| 844 | return false; |
| 845 | } |
| 846 | } |
| 847 | |
| 848 | /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the |
| 849 | /// RHS of a commutative operation, not the on LHS. |
| 850 | static bool OnlyOnRHSOfCommutative(TreePatternNode *N) { |
| 851 | if (!N->isLeaf() && N->getOperator()->getName() == "imm") |
| 852 | return true; |
| 853 | if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue())) |
| 854 | return true; |
| 855 | return false; |
| 856 | } |
| 857 | |
| 858 | |
| 859 | /// canPatternMatch - If it is impossible for this pattern to match on this |
| 860 | /// target, fill in Reason and return false. Otherwise, return true. This is |
| 861 | /// used as a santity check for .td files (to prevent people from writing stuff |
| 862 | /// that can never possibly work), and to prevent the pattern permuter from |
| 863 | /// generating stuff that is useless. |
| 864 | bool TreePatternNode::canPatternMatch(std::string &Reason, |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 865 | CodeGenDAGPatterns &CDP){ |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 866 | if (isLeaf()) return true; |
| 867 | |
| 868 | for (unsigned i = 0, e = getNumChildren(); i != e; ++i) |
| 869 | if (!getChild(i)->canPatternMatch(Reason, CDP)) |
| 870 | return false; |
| 871 | |
| 872 | // If this is an intrinsic, handle cases that would make it not match. For |
| 873 | // example, if an operand is required to be an immediate. |
| 874 | if (getOperator()->isSubClassOf("Intrinsic")) { |
| 875 | // TODO: |
| 876 | return true; |
| 877 | } |
| 878 | |
| 879 | // If this node is a commutative operator, check that the LHS isn't an |
| 880 | // immediate. |
| 881 | const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator()); |
| 882 | if (NodeInfo.hasProperty(SDNPCommutative)) { |
| 883 | // Scan all of the operands of the node and make sure that only the last one |
| 884 | // is a constant node, unless the RHS also is. |
| 885 | if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) { |
| 886 | for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) |
| 887 | if (OnlyOnRHSOfCommutative(getChild(i))) { |
| 888 | Reason="Immediate value must be on the RHS of commutative operators!"; |
| 889 | return false; |
| 890 | } |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | return true; |
| 895 | } |
| 896 | |
| 897 | //===----------------------------------------------------------------------===// |
| 898 | // TreePattern implementation |
| 899 | // |
| 900 | |
| 901 | TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput, |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 902 | CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){ |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 903 | isInputPattern = isInput; |
| 904 | for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i) |
| 905 | Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i))); |
| 906 | } |
| 907 | |
| 908 | TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput, |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 909 | CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){ |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 910 | isInputPattern = isInput; |
| 911 | Trees.push_back(ParseTreePattern(Pat)); |
| 912 | } |
| 913 | |
| 914 | TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput, |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 915 | CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){ |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 916 | isInputPattern = isInput; |
| 917 | Trees.push_back(Pat); |
| 918 | } |
| 919 | |
| 920 | |
| 921 | |
| 922 | void TreePattern::error(const std::string &Msg) const { |
| 923 | dump(); |
| 924 | throw "In " + TheRecord->getName() + ": " + Msg; |
| 925 | } |
| 926 | |
| 927 | TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) { |
| 928 | DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator()); |
| 929 | if (!OpDef) error("Pattern has unexpected operator type!"); |
| 930 | Record *Operator = OpDef->getDef(); |
| 931 | |
| 932 | if (Operator->isSubClassOf("ValueType")) { |
| 933 | // If the operator is a ValueType, then this must be "type cast" of a leaf |
| 934 | // node. |
| 935 | if (Dag->getNumArgs() != 1) |
| 936 | error("Type cast only takes one operand!"); |
| 937 | |
| 938 | Init *Arg = Dag->getArg(0); |
| 939 | TreePatternNode *New; |
| 940 | if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) { |
| 941 | Record *R = DI->getDef(); |
| 942 | if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) { |
| 943 | Dag->setArg(0, new DagInit(DI, |
| 944 | std::vector<std::pair<Init*, std::string> >())); |
| 945 | return ParseTreePattern(Dag); |
| 946 | } |
| 947 | New = new TreePatternNode(DI); |
| 948 | } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) { |
| 949 | New = ParseTreePattern(DI); |
| 950 | } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) { |
| 951 | New = new TreePatternNode(II); |
| 952 | if (!Dag->getArgName(0).empty()) |
| 953 | error("Constant int argument should not have a name!"); |
| 954 | } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) { |
| 955 | // Turn this into an IntInit. |
| 956 | Init *II = BI->convertInitializerTo(new IntRecTy()); |
| 957 | if (II == 0 || !dynamic_cast<IntInit*>(II)) |
| 958 | error("Bits value must be constants!"); |
| 959 | |
| 960 | New = new TreePatternNode(dynamic_cast<IntInit*>(II)); |
| 961 | if (!Dag->getArgName(0).empty()) |
| 962 | error("Constant int argument should not have a name!"); |
| 963 | } else { |
| 964 | Arg->dump(); |
| 965 | error("Unknown leaf value for tree pattern!"); |
| 966 | return 0; |
| 967 | } |
| 968 | |
| 969 | // Apply the type cast. |
| 970 | New->UpdateNodeType(getValueType(Operator), *this); |
| 971 | New->setName(Dag->getArgName(0)); |
| 972 | return New; |
| 973 | } |
| 974 | |
| 975 | // Verify that this is something that makes sense for an operator. |
| 976 | if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") && |
| 977 | !Operator->isSubClassOf("Instruction") && |
| 978 | !Operator->isSubClassOf("SDNodeXForm") && |
| 979 | !Operator->isSubClassOf("Intrinsic") && |
| 980 | Operator->getName() != "set" && |
| 981 | Operator->getName() != "implicit" && |
| 982 | Operator->getName() != "parallel") |
| 983 | error("Unrecognized node '" + Operator->getName() + "'!"); |
| 984 | |
| 985 | // Check to see if this is something that is illegal in an input pattern. |
| 986 | if (isInputPattern && (Operator->isSubClassOf("Instruction") || |
| 987 | Operator->isSubClassOf("SDNodeXForm"))) |
| 988 | error("Cannot use '" + Operator->getName() + "' in an input pattern!"); |
| 989 | |
| 990 | std::vector<TreePatternNode*> Children; |
| 991 | |
| 992 | for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) { |
| 993 | Init *Arg = Dag->getArg(i); |
| 994 | if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) { |
| 995 | Children.push_back(ParseTreePattern(DI)); |
| 996 | if (Children.back()->getName().empty()) |
| 997 | Children.back()->setName(Dag->getArgName(i)); |
| 998 | } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) { |
| 999 | Record *R = DefI->getDef(); |
| 1000 | // Direct reference to a leaf DagNode or PatFrag? Turn it into a |
| 1001 | // TreePatternNode if its own. |
| 1002 | if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) { |
| 1003 | Dag->setArg(i, new DagInit(DefI, |
| 1004 | std::vector<std::pair<Init*, std::string> >())); |
| 1005 | --i; // Revisit this node... |
| 1006 | } else { |
| 1007 | TreePatternNode *Node = new TreePatternNode(DefI); |
| 1008 | Node->setName(Dag->getArgName(i)); |
| 1009 | Children.push_back(Node); |
| 1010 | |
| 1011 | // Input argument? |
| 1012 | if (R->getName() == "node") { |
| 1013 | if (Dag->getArgName(i).empty()) |
| 1014 | error("'node' argument requires a name to match with operand list"); |
| 1015 | Args.push_back(Dag->getArgName(i)); |
| 1016 | } |
| 1017 | } |
| 1018 | } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) { |
| 1019 | TreePatternNode *Node = new TreePatternNode(II); |
| 1020 | if (!Dag->getArgName(i).empty()) |
| 1021 | error("Constant int argument should not have a name!"); |
| 1022 | Children.push_back(Node); |
| 1023 | } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) { |
| 1024 | // Turn this into an IntInit. |
| 1025 | Init *II = BI->convertInitializerTo(new IntRecTy()); |
| 1026 | if (II == 0 || !dynamic_cast<IntInit*>(II)) |
| 1027 | error("Bits value must be constants!"); |
| 1028 | |
| 1029 | TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II)); |
| 1030 | if (!Dag->getArgName(i).empty()) |
| 1031 | error("Constant int argument should not have a name!"); |
| 1032 | Children.push_back(Node); |
| 1033 | } else { |
| 1034 | cerr << '"'; |
| 1035 | Arg->dump(); |
| 1036 | cerr << "\": "; |
| 1037 | error("Unknown leaf value for tree pattern!"); |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | // If the operator is an intrinsic, then this is just syntactic sugar for for |
| 1042 | // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and |
| 1043 | // convert the intrinsic name to a number. |
| 1044 | if (Operator->isSubClassOf("Intrinsic")) { |
| 1045 | const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator); |
| 1046 | unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1; |
| 1047 | |
| 1048 | // If this intrinsic returns void, it must have side-effects and thus a |
| 1049 | // chain. |
| 1050 | if (Int.ArgVTs[0] == MVT::isVoid) { |
| 1051 | Operator = getDAGPatterns().get_intrinsic_void_sdnode(); |
| 1052 | } else if (Int.ModRef != CodeGenIntrinsic::NoMem) { |
| 1053 | // Has side-effects, requires chain. |
| 1054 | Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode(); |
| 1055 | } else { |
| 1056 | // Otherwise, no chain. |
| 1057 | Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode(); |
| 1058 | } |
| 1059 | |
| 1060 | TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID)); |
| 1061 | Children.insert(Children.begin(), IIDNode); |
| 1062 | } |
| 1063 | |
| 1064 | return new TreePatternNode(Operator, Children); |
| 1065 | } |
| 1066 | |
| 1067 | /// InferAllTypes - Infer/propagate as many types throughout the expression |
| 1068 | /// patterns as possible. Return true if all types are infered, false |
| 1069 | /// otherwise. Throw an exception if a type contradiction is found. |
| 1070 | bool TreePattern::InferAllTypes() { |
| 1071 | bool MadeChange = true; |
| 1072 | while (MadeChange) { |
| 1073 | MadeChange = false; |
| 1074 | for (unsigned i = 0, e = Trees.size(); i != e; ++i) |
| 1075 | MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false); |
| 1076 | } |
| 1077 | |
| 1078 | bool HasUnresolvedTypes = false; |
| 1079 | for (unsigned i = 0, e = Trees.size(); i != e; ++i) |
| 1080 | HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType(); |
| 1081 | return !HasUnresolvedTypes; |
| 1082 | } |
| 1083 | |
| 1084 | void TreePattern::print(std::ostream &OS) const { |
| 1085 | OS << getRecord()->getName(); |
| 1086 | if (!Args.empty()) { |
| 1087 | OS << "(" << Args[0]; |
| 1088 | for (unsigned i = 1, e = Args.size(); i != e; ++i) |
| 1089 | OS << ", " << Args[i]; |
| 1090 | OS << ")"; |
| 1091 | } |
| 1092 | OS << ": "; |
| 1093 | |
| 1094 | if (Trees.size() > 1) |
| 1095 | OS << "[\n"; |
| 1096 | for (unsigned i = 0, e = Trees.size(); i != e; ++i) { |
| 1097 | OS << "\t"; |
| 1098 | Trees[i]->print(OS); |
| 1099 | OS << "\n"; |
| 1100 | } |
| 1101 | |
| 1102 | if (Trees.size() > 1) |
| 1103 | OS << "]\n"; |
| 1104 | } |
| 1105 | |
| 1106 | void TreePattern::dump() const { print(*cerr.stream()); } |
| 1107 | |
| 1108 | //===----------------------------------------------------------------------===// |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1109 | // CodeGenDAGPatterns implementation |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1110 | // |
| 1111 | |
| 1112 | // FIXME: REMOVE OSTREAM ARGUMENT |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1113 | CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1114 | Intrinsics = LoadIntrinsics(Records); |
| 1115 | ParseNodeInfo(); |
Chris Lattner | 443e3f9 | 2008-01-05 22:54:53 +0000 | [diff] [blame] | 1116 | ParseNodeTransforms(); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1117 | ParseComplexPatterns(); |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1118 | ParsePatternFragments(); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1119 | ParseDefaultOperands(); |
| 1120 | ParseInstructions(); |
| 1121 | ParsePatterns(); |
| 1122 | |
| 1123 | // Generate variants. For example, commutative patterns can match |
| 1124 | // multiple ways. Add them to PatternsToMatch as well. |
| 1125 | GenerateVariants(); |
| 1126 | } |
| 1127 | |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1128 | CodeGenDAGPatterns::~CodeGenDAGPatterns() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1129 | for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(), |
| 1130 | E = PatternFragments.end(); I != E; ++I) |
| 1131 | delete I->second; |
| 1132 | } |
| 1133 | |
| 1134 | |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1135 | Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1136 | Record *N = Records.getDef(Name); |
| 1137 | if (!N || !N->isSubClassOf("SDNode")) { |
| 1138 | cerr << "Error getting SDNode '" << Name << "'!\n"; |
| 1139 | exit(1); |
| 1140 | } |
| 1141 | return N; |
| 1142 | } |
| 1143 | |
| 1144 | // Parse all of the SDNode definitions for the target, populating SDNodes. |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1145 | void CodeGenDAGPatterns::ParseNodeInfo() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1146 | std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode"); |
| 1147 | while (!Nodes.empty()) { |
| 1148 | SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back())); |
| 1149 | Nodes.pop_back(); |
| 1150 | } |
| 1151 | |
| 1152 | // Get the buildin intrinsic nodes. |
| 1153 | intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void"); |
| 1154 | intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain"); |
| 1155 | intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain"); |
| 1156 | } |
| 1157 | |
| 1158 | /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms |
| 1159 | /// map, and emit them to the file as functions. |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1160 | void CodeGenDAGPatterns::ParseNodeTransforms() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1161 | std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm"); |
| 1162 | while (!Xforms.empty()) { |
| 1163 | Record *XFormNode = Xforms.back(); |
| 1164 | Record *SDNode = XFormNode->getValueAsDef("Opcode"); |
| 1165 | std::string Code = XFormNode->getValueAsCode("XFormFunction"); |
Chris Lattner | 443e3f9 | 2008-01-05 22:54:53 +0000 | [diff] [blame] | 1166 | SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code))); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1167 | |
| 1168 | Xforms.pop_back(); |
| 1169 | } |
| 1170 | } |
| 1171 | |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1172 | void CodeGenDAGPatterns::ParseComplexPatterns() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1173 | std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern"); |
| 1174 | while (!AMs.empty()) { |
| 1175 | ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back())); |
| 1176 | AMs.pop_back(); |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | |
| 1181 | /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td |
| 1182 | /// file, building up the PatternFragments map. After we've collected them all, |
| 1183 | /// inline fragments together as necessary, so that there are no references left |
| 1184 | /// inside a pattern fragment to a pattern fragment. |
| 1185 | /// |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1186 | void CodeGenDAGPatterns::ParsePatternFragments() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1187 | std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag"); |
| 1188 | |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1189 | // First step, parse all of the fragments. |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1190 | for (unsigned i = 0, e = Fragments.size(); i != e; ++i) { |
| 1191 | DagInit *Tree = Fragments[i]->getValueAsDag("Fragment"); |
| 1192 | TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this); |
| 1193 | PatternFragments[Fragments[i]] = P; |
| 1194 | |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1195 | // Validate the argument list, converting it to set, to discard duplicates. |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1196 | std::vector<std::string> &Args = P->getArgList(); |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1197 | std::set<std::string> OperandsSet(Args.begin(), Args.end()); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1198 | |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1199 | if (OperandsSet.count("")) |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1200 | P->error("Cannot have unnamed 'node' values in pattern fragment!"); |
| 1201 | |
| 1202 | // Parse the operands list. |
| 1203 | DagInit *OpsList = Fragments[i]->getValueAsDag("Operands"); |
| 1204 | DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator()); |
| 1205 | // Special cases: ops == outs == ins. Different names are used to |
| 1206 | // improve readibility. |
| 1207 | if (!OpsOp || |
| 1208 | (OpsOp->getDef()->getName() != "ops" && |
| 1209 | OpsOp->getDef()->getName() != "outs" && |
| 1210 | OpsOp->getDef()->getName() != "ins")) |
| 1211 | P->error("Operands list should start with '(ops ... '!"); |
| 1212 | |
| 1213 | // Copy over the arguments. |
| 1214 | Args.clear(); |
| 1215 | for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) { |
| 1216 | if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) || |
| 1217 | static_cast<DefInit*>(OpsList->getArg(j))-> |
| 1218 | getDef()->getName() != "node") |
| 1219 | P->error("Operands list should all be 'node' values."); |
| 1220 | if (OpsList->getArgName(j).empty()) |
| 1221 | P->error("Operands list should have names for each operand!"); |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1222 | if (!OperandsSet.count(OpsList->getArgName(j))) |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1223 | P->error("'" + OpsList->getArgName(j) + |
| 1224 | "' does not occur in pattern or was multiply specified!"); |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1225 | OperandsSet.erase(OpsList->getArgName(j)); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1226 | Args.push_back(OpsList->getArgName(j)); |
| 1227 | } |
| 1228 | |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1229 | if (!OperandsSet.empty()) |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1230 | P->error("Operands list does not contain an entry for operand '" + |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1231 | *OperandsSet.begin() + "'!"); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1232 | |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1233 | // If there is a code init for this fragment, keep track of the fact that |
| 1234 | // this fragment uses it. |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1235 | std::string Code = Fragments[i]->getValueAsCode("Predicate"); |
Chris Lattner | dc32f98 | 2008-01-05 22:43:57 +0000 | [diff] [blame] | 1236 | if (!Code.empty()) |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1237 | P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName()); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1238 | |
| 1239 | // If there is a node transformation corresponding to this, keep track of |
| 1240 | // it. |
| 1241 | Record *Transform = Fragments[i]->getValueAsDef("OperandTransform"); |
| 1242 | if (!getSDNodeTransform(Transform).second.empty()) // not noop xform? |
| 1243 | P->getOnlyTree()->setTransformFn(Transform); |
| 1244 | } |
| 1245 | |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1246 | // Now that we've parsed all of the tree fragments, do a closure on them so |
| 1247 | // that there are not references to PatFrags left inside of them. |
| 1248 | for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(), |
| 1249 | E = PatternFragments.end(); I != E; ++I) { |
| 1250 | TreePattern *ThePat = I->second; |
| 1251 | ThePat->InlinePatternFragments(); |
| 1252 | |
| 1253 | // Infer as many types as possible. Don't worry about it if we don't infer |
| 1254 | // all of them, some may depend on the inputs of the pattern. |
| 1255 | try { |
| 1256 | ThePat->InferAllTypes(); |
| 1257 | } catch (...) { |
| 1258 | // If this pattern fragment is not supported by this target (no types can |
| 1259 | // satisfy its constraints), just ignore it. If the bogus pattern is |
| 1260 | // actually used by instructions, the type consistency error will be |
| 1261 | // reported there. |
| 1262 | } |
| 1263 | |
| 1264 | // If debugging, print out the pattern fragment result. |
| 1265 | DEBUG(ThePat->dump()); |
| 1266 | } |
| 1267 | } |
| 1268 | |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1269 | void CodeGenDAGPatterns::ParseDefaultOperands() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1270 | std::vector<Record*> DefaultOps[2]; |
| 1271 | DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand"); |
| 1272 | DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand"); |
| 1273 | |
| 1274 | // Find some SDNode. |
| 1275 | assert(!SDNodes.empty() && "No SDNodes parsed?"); |
| 1276 | Init *SomeSDNode = new DefInit(SDNodes.begin()->first); |
| 1277 | |
| 1278 | for (unsigned iter = 0; iter != 2; ++iter) { |
| 1279 | for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) { |
| 1280 | DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps"); |
| 1281 | |
| 1282 | // Clone the DefaultInfo dag node, changing the operator from 'ops' to |
| 1283 | // SomeSDnode so that we can parse this. |
| 1284 | std::vector<std::pair<Init*, std::string> > Ops; |
| 1285 | for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op) |
| 1286 | Ops.push_back(std::make_pair(DefaultInfo->getArg(op), |
| 1287 | DefaultInfo->getArgName(op))); |
| 1288 | DagInit *DI = new DagInit(SomeSDNode, Ops); |
| 1289 | |
| 1290 | // Create a TreePattern to parse this. |
| 1291 | TreePattern P(DefaultOps[iter][i], DI, false, *this); |
| 1292 | assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!"); |
| 1293 | |
| 1294 | // Copy the operands over into a DAGDefaultOperand. |
| 1295 | DAGDefaultOperand DefaultOpInfo; |
| 1296 | |
| 1297 | TreePatternNode *T = P.getTree(0); |
| 1298 | for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) { |
| 1299 | TreePatternNode *TPN = T->getChild(op); |
| 1300 | while (TPN->ApplyTypeConstraints(P, false)) |
| 1301 | /* Resolve all types */; |
| 1302 | |
| 1303 | if (TPN->ContainsUnresolvedType()) |
| 1304 | if (iter == 0) |
| 1305 | throw "Value #" + utostr(i) + " of PredicateOperand '" + |
| 1306 | DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!"; |
| 1307 | else |
| 1308 | throw "Value #" + utostr(i) + " of OptionalDefOperand '" + |
| 1309 | DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!"; |
| 1310 | |
| 1311 | DefaultOpInfo.DefaultOps.push_back(TPN); |
| 1312 | } |
| 1313 | |
| 1314 | // Insert it into the DefaultOperands map so we can find it later. |
| 1315 | DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo; |
| 1316 | } |
| 1317 | } |
| 1318 | } |
| 1319 | |
| 1320 | /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an |
| 1321 | /// instruction input. Return true if this is a real use. |
| 1322 | static bool HandleUse(TreePattern *I, TreePatternNode *Pat, |
| 1323 | std::map<std::string, TreePatternNode*> &InstInputs, |
| 1324 | std::vector<Record*> &InstImpInputs) { |
| 1325 | // No name -> not interesting. |
| 1326 | if (Pat->getName().empty()) { |
| 1327 | if (Pat->isLeaf()) { |
| 1328 | DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue()); |
| 1329 | if (DI && DI->getDef()->isSubClassOf("RegisterClass")) |
| 1330 | I->error("Input " + DI->getDef()->getName() + " must be named!"); |
| 1331 | else if (DI && DI->getDef()->isSubClassOf("Register")) |
| 1332 | InstImpInputs.push_back(DI->getDef()); |
| 1333 | ; |
| 1334 | } |
| 1335 | return false; |
| 1336 | } |
| 1337 | |
| 1338 | Record *Rec; |
| 1339 | if (Pat->isLeaf()) { |
| 1340 | DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue()); |
| 1341 | if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!"); |
| 1342 | Rec = DI->getDef(); |
| 1343 | } else { |
| 1344 | assert(Pat->getNumChildren() == 0 && "can't be a use with children!"); |
| 1345 | Rec = Pat->getOperator(); |
| 1346 | } |
| 1347 | |
| 1348 | // SRCVALUE nodes are ignored. |
| 1349 | if (Rec->getName() == "srcvalue") |
| 1350 | return false; |
| 1351 | |
| 1352 | TreePatternNode *&Slot = InstInputs[Pat->getName()]; |
| 1353 | if (!Slot) { |
| 1354 | Slot = Pat; |
| 1355 | } else { |
| 1356 | Record *SlotRec; |
| 1357 | if (Slot->isLeaf()) { |
| 1358 | SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef(); |
| 1359 | } else { |
| 1360 | assert(Slot->getNumChildren() == 0 && "can't be a use with children!"); |
| 1361 | SlotRec = Slot->getOperator(); |
| 1362 | } |
| 1363 | |
| 1364 | // Ensure that the inputs agree if we've already seen this input. |
| 1365 | if (Rec != SlotRec) |
| 1366 | I->error("All $" + Pat->getName() + " inputs must agree with each other"); |
| 1367 | if (Slot->getExtTypes() != Pat->getExtTypes()) |
| 1368 | I->error("All $" + Pat->getName() + " inputs must agree with each other"); |
| 1369 | } |
| 1370 | return true; |
| 1371 | } |
| 1372 | |
| 1373 | /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is |
| 1374 | /// part of "I", the instruction), computing the set of inputs and outputs of |
| 1375 | /// the pattern. Report errors if we see anything naughty. |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1376 | void CodeGenDAGPatterns:: |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1377 | FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat, |
| 1378 | std::map<std::string, TreePatternNode*> &InstInputs, |
| 1379 | std::map<std::string, TreePatternNode*>&InstResults, |
| 1380 | std::vector<Record*> &InstImpInputs, |
| 1381 | std::vector<Record*> &InstImpResults) { |
| 1382 | if (Pat->isLeaf()) { |
| 1383 | bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs); |
| 1384 | if (!isUse && Pat->getTransformFn()) |
| 1385 | I->error("Cannot specify a transform function for a non-input value!"); |
| 1386 | return; |
| 1387 | } else if (Pat->getOperator()->getName() == "implicit") { |
| 1388 | for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) { |
| 1389 | TreePatternNode *Dest = Pat->getChild(i); |
| 1390 | if (!Dest->isLeaf()) |
| 1391 | I->error("implicitly defined value should be a register!"); |
| 1392 | |
| 1393 | DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue()); |
| 1394 | if (!Val || !Val->getDef()->isSubClassOf("Register")) |
| 1395 | I->error("implicitly defined value should be a register!"); |
| 1396 | InstImpResults.push_back(Val->getDef()); |
| 1397 | } |
| 1398 | return; |
| 1399 | } else if (Pat->getOperator()->getName() != "set") { |
| 1400 | // If this is not a set, verify that the children nodes are not void typed, |
| 1401 | // and recurse. |
| 1402 | for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) { |
| 1403 | if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid) |
| 1404 | I->error("Cannot have void nodes inside of patterns!"); |
| 1405 | FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults, |
| 1406 | InstImpInputs, InstImpResults); |
| 1407 | } |
| 1408 | |
| 1409 | // If this is a non-leaf node with no children, treat it basically as if |
| 1410 | // it were a leaf. This handles nodes like (imm). |
| 1411 | bool isUse = false; |
| 1412 | if (Pat->getNumChildren() == 0) |
| 1413 | isUse = HandleUse(I, Pat, InstInputs, InstImpInputs); |
| 1414 | |
| 1415 | if (!isUse && Pat->getTransformFn()) |
| 1416 | I->error("Cannot specify a transform function for a non-input value!"); |
| 1417 | return; |
| 1418 | } |
| 1419 | |
| 1420 | // Otherwise, this is a set, validate and collect instruction results. |
| 1421 | if (Pat->getNumChildren() == 0) |
| 1422 | I->error("set requires operands!"); |
| 1423 | |
| 1424 | if (Pat->getTransformFn()) |
| 1425 | I->error("Cannot specify a transform function on a set node!"); |
| 1426 | |
| 1427 | // Check the set destinations. |
| 1428 | unsigned NumDests = Pat->getNumChildren()-1; |
| 1429 | for (unsigned i = 0; i != NumDests; ++i) { |
| 1430 | TreePatternNode *Dest = Pat->getChild(i); |
| 1431 | if (!Dest->isLeaf()) |
| 1432 | I->error("set destination should be a register!"); |
| 1433 | |
| 1434 | DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue()); |
| 1435 | if (!Val) |
| 1436 | I->error("set destination should be a register!"); |
| 1437 | |
| 1438 | if (Val->getDef()->isSubClassOf("RegisterClass") || |
| 1439 | Val->getDef()->getName() == "ptr_rc") { |
| 1440 | if (Dest->getName().empty()) |
| 1441 | I->error("set destination must have a name!"); |
| 1442 | if (InstResults.count(Dest->getName())) |
| 1443 | I->error("cannot set '" + Dest->getName() +"' multiple times"); |
| 1444 | InstResults[Dest->getName()] = Dest; |
| 1445 | } else if (Val->getDef()->isSubClassOf("Register")) { |
| 1446 | InstImpResults.push_back(Val->getDef()); |
| 1447 | } else { |
| 1448 | I->error("set destination should be a register!"); |
| 1449 | } |
| 1450 | } |
| 1451 | |
| 1452 | // Verify and collect info from the computation. |
| 1453 | FindPatternInputsAndOutputs(I, Pat->getChild(NumDests), |
| 1454 | InstInputs, InstResults, |
| 1455 | InstImpInputs, InstImpResults); |
| 1456 | } |
| 1457 | |
| 1458 | /// ParseInstructions - Parse all of the instructions, inlining and resolving |
| 1459 | /// any fragments involved. This populates the Instructions list with fully |
| 1460 | /// resolved instructions. |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1461 | void CodeGenDAGPatterns::ParseInstructions() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1462 | std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction"); |
| 1463 | |
| 1464 | for (unsigned i = 0, e = Instrs.size(); i != e; ++i) { |
| 1465 | ListInit *LI = 0; |
| 1466 | |
| 1467 | if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern"))) |
| 1468 | LI = Instrs[i]->getValueAsListInit("Pattern"); |
| 1469 | |
| 1470 | // If there is no pattern, only collect minimal information about the |
| 1471 | // instruction for its operand list. We have to assume that there is one |
| 1472 | // result, as we have no detailed info. |
| 1473 | if (!LI || LI->getSize() == 0) { |
| 1474 | std::vector<Record*> Results; |
| 1475 | std::vector<Record*> Operands; |
| 1476 | |
| 1477 | CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName()); |
| 1478 | |
| 1479 | if (InstInfo.OperandList.size() != 0) { |
| 1480 | if (InstInfo.NumDefs == 0) { |
| 1481 | // These produce no results |
| 1482 | for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j) |
| 1483 | Operands.push_back(InstInfo.OperandList[j].Rec); |
| 1484 | } else { |
| 1485 | // Assume the first operand is the result. |
| 1486 | Results.push_back(InstInfo.OperandList[0].Rec); |
| 1487 | |
| 1488 | // The rest are inputs. |
| 1489 | for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j) |
| 1490 | Operands.push_back(InstInfo.OperandList[j].Rec); |
| 1491 | } |
| 1492 | } |
| 1493 | |
| 1494 | // Create and insert the instruction. |
| 1495 | std::vector<Record*> ImpResults; |
| 1496 | std::vector<Record*> ImpOperands; |
| 1497 | Instructions.insert(std::make_pair(Instrs[i], |
| 1498 | DAGInstruction(0, Results, Operands, ImpResults, |
| 1499 | ImpOperands))); |
| 1500 | continue; // no pattern. |
| 1501 | } |
| 1502 | |
| 1503 | // Parse the instruction. |
| 1504 | TreePattern *I = new TreePattern(Instrs[i], LI, true, *this); |
| 1505 | // Inline pattern fragments into it. |
| 1506 | I->InlinePatternFragments(); |
| 1507 | |
| 1508 | // Infer as many types as possible. If we cannot infer all of them, we can |
| 1509 | // never do anything with this instruction pattern: report it to the user. |
| 1510 | if (!I->InferAllTypes()) |
| 1511 | I->error("Could not infer all types in pattern!"); |
| 1512 | |
| 1513 | // InstInputs - Keep track of all of the inputs of the instruction, along |
| 1514 | // with the record they are declared as. |
| 1515 | std::map<std::string, TreePatternNode*> InstInputs; |
| 1516 | |
| 1517 | // InstResults - Keep track of all the virtual registers that are 'set' |
| 1518 | // in the instruction, including what reg class they are. |
| 1519 | std::map<std::string, TreePatternNode*> InstResults; |
| 1520 | |
| 1521 | std::vector<Record*> InstImpInputs; |
| 1522 | std::vector<Record*> InstImpResults; |
| 1523 | |
| 1524 | // Verify that the top-level forms in the instruction are of void type, and |
| 1525 | // fill in the InstResults map. |
| 1526 | for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) { |
| 1527 | TreePatternNode *Pat = I->getTree(j); |
| 1528 | if (Pat->getExtTypeNum(0) != MVT::isVoid) |
| 1529 | I->error("Top-level forms in instruction pattern should have" |
| 1530 | " void types"); |
| 1531 | |
| 1532 | // Find inputs and outputs, and verify the structure of the uses/defs. |
| 1533 | FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults, |
| 1534 | InstImpInputs, InstImpResults); |
| 1535 | } |
| 1536 | |
| 1537 | // Now that we have inputs and outputs of the pattern, inspect the operands |
| 1538 | // list for the instruction. This determines the order that operands are |
| 1539 | // added to the machine instruction the node corresponds to. |
| 1540 | unsigned NumResults = InstResults.size(); |
| 1541 | |
| 1542 | // Parse the operands list from the (ops) list, validating it. |
| 1543 | assert(I->getArgList().empty() && "Args list should still be empty here!"); |
| 1544 | CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName()); |
| 1545 | |
| 1546 | // Check that all of the results occur first in the list. |
| 1547 | std::vector<Record*> Results; |
| 1548 | TreePatternNode *Res0Node = NULL; |
| 1549 | for (unsigned i = 0; i != NumResults; ++i) { |
| 1550 | if (i == CGI.OperandList.size()) |
| 1551 | I->error("'" + InstResults.begin()->first + |
| 1552 | "' set but does not appear in operand list!"); |
| 1553 | const std::string &OpName = CGI.OperandList[i].Name; |
| 1554 | |
| 1555 | // Check that it exists in InstResults. |
| 1556 | TreePatternNode *RNode = InstResults[OpName]; |
| 1557 | if (RNode == 0) |
| 1558 | I->error("Operand $" + OpName + " does not exist in operand list!"); |
| 1559 | |
| 1560 | if (i == 0) |
| 1561 | Res0Node = RNode; |
| 1562 | Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef(); |
| 1563 | if (R == 0) |
| 1564 | I->error("Operand $" + OpName + " should be a set destination: all " |
| 1565 | "outputs must occur before inputs in operand list!"); |
| 1566 | |
| 1567 | if (CGI.OperandList[i].Rec != R) |
| 1568 | I->error("Operand $" + OpName + " class mismatch!"); |
| 1569 | |
| 1570 | // Remember the return type. |
| 1571 | Results.push_back(CGI.OperandList[i].Rec); |
| 1572 | |
| 1573 | // Okay, this one checks out. |
| 1574 | InstResults.erase(OpName); |
| 1575 | } |
| 1576 | |
| 1577 | // Loop over the inputs next. Make a copy of InstInputs so we can destroy |
| 1578 | // the copy while we're checking the inputs. |
| 1579 | std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs); |
| 1580 | |
| 1581 | std::vector<TreePatternNode*> ResultNodeOperands; |
| 1582 | std::vector<Record*> Operands; |
| 1583 | for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) { |
| 1584 | CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i]; |
| 1585 | const std::string &OpName = Op.Name; |
| 1586 | if (OpName.empty()) |
| 1587 | I->error("Operand #" + utostr(i) + " in operands list has no name!"); |
| 1588 | |
| 1589 | if (!InstInputsCheck.count(OpName)) { |
| 1590 | // If this is an predicate operand or optional def operand with an |
| 1591 | // DefaultOps set filled in, we can ignore this. When we codegen it, |
| 1592 | // we will do so as always executed. |
| 1593 | if (Op.Rec->isSubClassOf("PredicateOperand") || |
| 1594 | Op.Rec->isSubClassOf("OptionalDefOperand")) { |
| 1595 | // Does it have a non-empty DefaultOps field? If so, ignore this |
| 1596 | // operand. |
| 1597 | if (!getDefaultOperand(Op.Rec).DefaultOps.empty()) |
| 1598 | continue; |
| 1599 | } |
| 1600 | I->error("Operand $" + OpName + |
| 1601 | " does not appear in the instruction pattern"); |
| 1602 | } |
| 1603 | TreePatternNode *InVal = InstInputsCheck[OpName]; |
| 1604 | InstInputsCheck.erase(OpName); // It occurred, remove from map. |
| 1605 | |
| 1606 | if (InVal->isLeaf() && |
| 1607 | dynamic_cast<DefInit*>(InVal->getLeafValue())) { |
| 1608 | Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef(); |
| 1609 | if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern")) |
| 1610 | I->error("Operand $" + OpName + "'s register class disagrees" |
| 1611 | " between the operand and pattern"); |
| 1612 | } |
| 1613 | Operands.push_back(Op.Rec); |
| 1614 | |
| 1615 | // Construct the result for the dest-pattern operand list. |
| 1616 | TreePatternNode *OpNode = InVal->clone(); |
| 1617 | |
| 1618 | // No predicate is useful on the result. |
| 1619 | OpNode->setPredicateFn(""); |
| 1620 | |
| 1621 | // Promote the xform function to be an explicit node if set. |
| 1622 | if (Record *Xform = OpNode->getTransformFn()) { |
| 1623 | OpNode->setTransformFn(0); |
| 1624 | std::vector<TreePatternNode*> Children; |
| 1625 | Children.push_back(OpNode); |
| 1626 | OpNode = new TreePatternNode(Xform, Children); |
| 1627 | } |
| 1628 | |
| 1629 | ResultNodeOperands.push_back(OpNode); |
| 1630 | } |
| 1631 | |
| 1632 | if (!InstInputsCheck.empty()) |
| 1633 | I->error("Input operand $" + InstInputsCheck.begin()->first + |
| 1634 | " occurs in pattern but not in operands list!"); |
| 1635 | |
| 1636 | TreePatternNode *ResultPattern = |
| 1637 | new TreePatternNode(I->getRecord(), ResultNodeOperands); |
| 1638 | // Copy fully inferred output node type to instruction result pattern. |
| 1639 | if (NumResults > 0) |
| 1640 | ResultPattern->setTypes(Res0Node->getExtTypes()); |
| 1641 | |
| 1642 | // Create and insert the instruction. |
| 1643 | // FIXME: InstImpResults and InstImpInputs should not be part of |
| 1644 | // DAGInstruction. |
| 1645 | DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs); |
| 1646 | Instructions.insert(std::make_pair(I->getRecord(), TheInst)); |
| 1647 | |
| 1648 | // Use a temporary tree pattern to infer all types and make sure that the |
| 1649 | // constructed result is correct. This depends on the instruction already |
| 1650 | // being inserted into the Instructions map. |
| 1651 | TreePattern Temp(I->getRecord(), ResultPattern, false, *this); |
| 1652 | Temp.InferAllTypes(); |
| 1653 | |
| 1654 | DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second; |
| 1655 | TheInsertedInst.setResultPattern(Temp.getOnlyTree()); |
| 1656 | |
| 1657 | DEBUG(I->dump()); |
| 1658 | } |
| 1659 | |
| 1660 | // If we can, convert the instructions to be patterns that are matched! |
| 1661 | for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(), |
| 1662 | E = Instructions.end(); II != E; ++II) { |
| 1663 | DAGInstruction &TheInst = II->second; |
Chris Lattner | f1ab4f1 | 2008-01-06 01:52:22 +0000 | [diff] [blame] | 1664 | const TreePattern *I = TheInst.getPattern(); |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1665 | if (I == 0) continue; // No pattern. |
| 1666 | |
| 1667 | // FIXME: Assume only the first tree is the pattern. The others are clobber |
| 1668 | // nodes. |
| 1669 | TreePatternNode *Pattern = I->getTree(0); |
| 1670 | TreePatternNode *SrcPattern; |
| 1671 | if (Pattern->getOperator()->getName() == "set") { |
| 1672 | SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone(); |
| 1673 | } else{ |
| 1674 | // Not a set (store or something?) |
| 1675 | SrcPattern = Pattern; |
| 1676 | } |
| 1677 | |
| 1678 | std::string Reason; |
| 1679 | if (!SrcPattern->canPatternMatch(Reason, *this)) |
| 1680 | I->error("Instruction can never match: " + Reason); |
| 1681 | |
| 1682 | Record *Instr = II->first; |
| 1683 | TreePatternNode *DstPattern = TheInst.getResultPattern(); |
| 1684 | PatternsToMatch. |
| 1685 | push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"), |
| 1686 | SrcPattern, DstPattern, TheInst.getImpResults(), |
| 1687 | Instr->getValueAsInt("AddedComplexity"))); |
| 1688 | } |
| 1689 | } |
| 1690 | |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1691 | void CodeGenDAGPatterns::ParsePatterns() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1692 | std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern"); |
| 1693 | |
| 1694 | for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { |
| 1695 | DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch"); |
| 1696 | DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator()); |
| 1697 | Record *Operator = OpDef->getDef(); |
| 1698 | TreePattern *Pattern; |
| 1699 | if (Operator->getName() != "parallel") |
| 1700 | Pattern = new TreePattern(Patterns[i], Tree, true, *this); |
| 1701 | else { |
| 1702 | std::vector<Init*> Values; |
| 1703 | for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) |
| 1704 | Values.push_back(Tree->getArg(j)); |
| 1705 | ListInit *LI = new ListInit(Values); |
| 1706 | Pattern = new TreePattern(Patterns[i], LI, true, *this); |
| 1707 | } |
| 1708 | |
| 1709 | // Inline pattern fragments into it. |
| 1710 | Pattern->InlinePatternFragments(); |
| 1711 | |
| 1712 | ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs"); |
| 1713 | if (LI->getSize() == 0) continue; // no pattern. |
| 1714 | |
| 1715 | // Parse the instruction. |
| 1716 | TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this); |
| 1717 | |
| 1718 | // Inline pattern fragments into it. |
| 1719 | Result->InlinePatternFragments(); |
| 1720 | |
| 1721 | if (Result->getNumTrees() != 1) |
| 1722 | Result->error("Cannot handle instructions producing instructions " |
| 1723 | "with temporaries yet!"); |
| 1724 | |
| 1725 | bool IterateInference; |
| 1726 | bool InferredAllPatternTypes, InferredAllResultTypes; |
| 1727 | do { |
| 1728 | // Infer as many types as possible. If we cannot infer all of them, we |
| 1729 | // can never do anything with this pattern: report it to the user. |
| 1730 | InferredAllPatternTypes = Pattern->InferAllTypes(); |
| 1731 | |
| 1732 | // Infer as many types as possible. If we cannot infer all of them, we |
| 1733 | // can never do anything with this pattern: report it to the user. |
| 1734 | InferredAllResultTypes = Result->InferAllTypes(); |
| 1735 | |
| 1736 | // Apply the type of the result to the source pattern. This helps us |
| 1737 | // resolve cases where the input type is known to be a pointer type (which |
| 1738 | // is considered resolved), but the result knows it needs to be 32- or |
| 1739 | // 64-bits. Infer the other way for good measure. |
| 1740 | IterateInference = Pattern->getTree(0)-> |
| 1741 | UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result); |
| 1742 | IterateInference |= Result->getTree(0)-> |
| 1743 | UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result); |
| 1744 | } while (IterateInference); |
| 1745 | |
| 1746 | // Verify that we inferred enough types that we can do something with the |
| 1747 | // pattern and result. If these fire the user has to add type casts. |
| 1748 | if (!InferredAllPatternTypes) |
| 1749 | Pattern->error("Could not infer all types in pattern!"); |
| 1750 | if (!InferredAllResultTypes) |
| 1751 | Result->error("Could not infer all types in pattern result!"); |
| 1752 | |
| 1753 | // Validate that the input pattern is correct. |
| 1754 | std::map<std::string, TreePatternNode*> InstInputs; |
| 1755 | std::map<std::string, TreePatternNode*> InstResults; |
| 1756 | std::vector<Record*> InstImpInputs; |
| 1757 | std::vector<Record*> InstImpResults; |
| 1758 | for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j) |
| 1759 | FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j), |
| 1760 | InstInputs, InstResults, |
| 1761 | InstImpInputs, InstImpResults); |
| 1762 | |
| 1763 | // Promote the xform function to be an explicit node if set. |
| 1764 | TreePatternNode *DstPattern = Result->getOnlyTree(); |
| 1765 | std::vector<TreePatternNode*> ResultNodeOperands; |
| 1766 | for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) { |
| 1767 | TreePatternNode *OpNode = DstPattern->getChild(ii); |
| 1768 | if (Record *Xform = OpNode->getTransformFn()) { |
| 1769 | OpNode->setTransformFn(0); |
| 1770 | std::vector<TreePatternNode*> Children; |
| 1771 | Children.push_back(OpNode); |
| 1772 | OpNode = new TreePatternNode(Xform, Children); |
| 1773 | } |
| 1774 | ResultNodeOperands.push_back(OpNode); |
| 1775 | } |
| 1776 | DstPattern = Result->getOnlyTree(); |
| 1777 | if (!DstPattern->isLeaf()) |
| 1778 | DstPattern = new TreePatternNode(DstPattern->getOperator(), |
| 1779 | ResultNodeOperands); |
| 1780 | DstPattern->setTypes(Result->getOnlyTree()->getExtTypes()); |
| 1781 | TreePattern Temp(Result->getRecord(), DstPattern, false, *this); |
| 1782 | Temp.InferAllTypes(); |
| 1783 | |
| 1784 | std::string Reason; |
| 1785 | if (!Pattern->getTree(0)->canPatternMatch(Reason, *this)) |
| 1786 | Pattern->error("Pattern can never match: " + Reason); |
| 1787 | |
| 1788 | PatternsToMatch. |
| 1789 | push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"), |
| 1790 | Pattern->getTree(0), |
| 1791 | Temp.getOnlyTree(), InstImpResults, |
| 1792 | Patterns[i]->getValueAsInt("AddedComplexity"))); |
| 1793 | } |
| 1794 | } |
| 1795 | |
| 1796 | /// CombineChildVariants - Given a bunch of permutations of each child of the |
| 1797 | /// 'operator' node, put them together in all possible ways. |
| 1798 | static void CombineChildVariants(TreePatternNode *Orig, |
| 1799 | const std::vector<std::vector<TreePatternNode*> > &ChildVariants, |
| 1800 | std::vector<TreePatternNode*> &OutVariants, |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1801 | CodeGenDAGPatterns &CDP) { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1802 | // Make sure that each operand has at least one variant to choose from. |
| 1803 | for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i) |
| 1804 | if (ChildVariants[i].empty()) |
| 1805 | return; |
| 1806 | |
| 1807 | // The end result is an all-pairs construction of the resultant pattern. |
| 1808 | std::vector<unsigned> Idxs; |
| 1809 | Idxs.resize(ChildVariants.size()); |
| 1810 | bool NotDone = true; |
| 1811 | while (NotDone) { |
| 1812 | // Create the variant and add it to the output list. |
| 1813 | std::vector<TreePatternNode*> NewChildren; |
| 1814 | for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i) |
| 1815 | NewChildren.push_back(ChildVariants[i][Idxs[i]]); |
| 1816 | TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren); |
| 1817 | |
| 1818 | // Copy over properties. |
| 1819 | R->setName(Orig->getName()); |
| 1820 | R->setPredicateFn(Orig->getPredicateFn()); |
| 1821 | R->setTransformFn(Orig->getTransformFn()); |
| 1822 | R->setTypes(Orig->getExtTypes()); |
| 1823 | |
| 1824 | // If this pattern cannot every match, do not include it as a variant. |
| 1825 | std::string ErrString; |
| 1826 | if (!R->canPatternMatch(ErrString, CDP)) { |
| 1827 | delete R; |
| 1828 | } else { |
| 1829 | bool AlreadyExists = false; |
| 1830 | |
| 1831 | // Scan to see if this pattern has already been emitted. We can get |
| 1832 | // duplication due to things like commuting: |
| 1833 | // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a) |
| 1834 | // which are the same pattern. Ignore the dups. |
| 1835 | for (unsigned i = 0, e = OutVariants.size(); i != e; ++i) |
| 1836 | if (R->isIsomorphicTo(OutVariants[i])) { |
| 1837 | AlreadyExists = true; |
| 1838 | break; |
| 1839 | } |
| 1840 | |
| 1841 | if (AlreadyExists) |
| 1842 | delete R; |
| 1843 | else |
| 1844 | OutVariants.push_back(R); |
| 1845 | } |
| 1846 | |
| 1847 | // Increment indices to the next permutation. |
| 1848 | NotDone = false; |
| 1849 | // Look for something we can increment without causing a wrap-around. |
| 1850 | for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) { |
| 1851 | if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) { |
| 1852 | NotDone = true; // Found something to increment. |
| 1853 | break; |
| 1854 | } |
| 1855 | Idxs[IdxsIdx] = 0; |
| 1856 | } |
| 1857 | } |
| 1858 | } |
| 1859 | |
| 1860 | /// CombineChildVariants - A helper function for binary operators. |
| 1861 | /// |
| 1862 | static void CombineChildVariants(TreePatternNode *Orig, |
| 1863 | const std::vector<TreePatternNode*> &LHS, |
| 1864 | const std::vector<TreePatternNode*> &RHS, |
| 1865 | std::vector<TreePatternNode*> &OutVariants, |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1866 | CodeGenDAGPatterns &CDP) { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1867 | std::vector<std::vector<TreePatternNode*> > ChildVariants; |
| 1868 | ChildVariants.push_back(LHS); |
| 1869 | ChildVariants.push_back(RHS); |
| 1870 | CombineChildVariants(Orig, ChildVariants, OutVariants, CDP); |
| 1871 | } |
| 1872 | |
| 1873 | |
| 1874 | static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N, |
| 1875 | std::vector<TreePatternNode *> &Children) { |
| 1876 | assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!"); |
| 1877 | Record *Operator = N->getOperator(); |
| 1878 | |
| 1879 | // Only permit raw nodes. |
| 1880 | if (!N->getName().empty() || !N->getPredicateFn().empty() || |
| 1881 | N->getTransformFn()) { |
| 1882 | Children.push_back(N); |
| 1883 | return; |
| 1884 | } |
| 1885 | |
| 1886 | if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator) |
| 1887 | Children.push_back(N->getChild(0)); |
| 1888 | else |
| 1889 | GatherChildrenOfAssociativeOpcode(N->getChild(0), Children); |
| 1890 | |
| 1891 | if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator) |
| 1892 | Children.push_back(N->getChild(1)); |
| 1893 | else |
| 1894 | GatherChildrenOfAssociativeOpcode(N->getChild(1), Children); |
| 1895 | } |
| 1896 | |
| 1897 | /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of |
| 1898 | /// the (potentially recursive) pattern by using algebraic laws. |
| 1899 | /// |
| 1900 | static void GenerateVariantsOf(TreePatternNode *N, |
| 1901 | std::vector<TreePatternNode*> &OutVariants, |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1902 | CodeGenDAGPatterns &CDP) { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1903 | // We cannot permute leaves. |
| 1904 | if (N->isLeaf()) { |
| 1905 | OutVariants.push_back(N); |
| 1906 | return; |
| 1907 | } |
| 1908 | |
| 1909 | // Look up interesting info about the node. |
| 1910 | const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator()); |
| 1911 | |
| 1912 | // If this node is associative, reassociate. |
| 1913 | if (NodeInfo.hasProperty(SDNPAssociative)) { |
| 1914 | // Reassociate by pulling together all of the linked operators |
| 1915 | std::vector<TreePatternNode*> MaximalChildren; |
| 1916 | GatherChildrenOfAssociativeOpcode(N, MaximalChildren); |
| 1917 | |
| 1918 | // Only handle child sizes of 3. Otherwise we'll end up trying too many |
| 1919 | // permutations. |
| 1920 | if (MaximalChildren.size() == 3) { |
| 1921 | // Find the variants of all of our maximal children. |
| 1922 | std::vector<TreePatternNode*> AVariants, BVariants, CVariants; |
| 1923 | GenerateVariantsOf(MaximalChildren[0], AVariants, CDP); |
| 1924 | GenerateVariantsOf(MaximalChildren[1], BVariants, CDP); |
| 1925 | GenerateVariantsOf(MaximalChildren[2], CVariants, CDP); |
| 1926 | |
| 1927 | // There are only two ways we can permute the tree: |
| 1928 | // (A op B) op C and A op (B op C) |
| 1929 | // Within these forms, we can also permute A/B/C. |
| 1930 | |
| 1931 | // Generate legal pair permutations of A/B/C. |
| 1932 | std::vector<TreePatternNode*> ABVariants; |
| 1933 | std::vector<TreePatternNode*> BAVariants; |
| 1934 | std::vector<TreePatternNode*> ACVariants; |
| 1935 | std::vector<TreePatternNode*> CAVariants; |
| 1936 | std::vector<TreePatternNode*> BCVariants; |
| 1937 | std::vector<TreePatternNode*> CBVariants; |
| 1938 | CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP); |
| 1939 | CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP); |
| 1940 | CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP); |
| 1941 | CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP); |
| 1942 | CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP); |
| 1943 | CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP); |
| 1944 | |
| 1945 | // Combine those into the result: (x op x) op x |
| 1946 | CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP); |
| 1947 | CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP); |
| 1948 | CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP); |
| 1949 | CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP); |
| 1950 | CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP); |
| 1951 | CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP); |
| 1952 | |
| 1953 | // Combine those into the result: x op (x op x) |
| 1954 | CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP); |
| 1955 | CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP); |
| 1956 | CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP); |
| 1957 | CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP); |
| 1958 | CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP); |
| 1959 | CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP); |
| 1960 | return; |
| 1961 | } |
| 1962 | } |
| 1963 | |
| 1964 | // Compute permutations of all children. |
| 1965 | std::vector<std::vector<TreePatternNode*> > ChildVariants; |
| 1966 | ChildVariants.resize(N->getNumChildren()); |
| 1967 | for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) |
| 1968 | GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP); |
| 1969 | |
| 1970 | // Build all permutations based on how the children were formed. |
| 1971 | CombineChildVariants(N, ChildVariants, OutVariants, CDP); |
| 1972 | |
| 1973 | // If this node is commutative, consider the commuted order. |
| 1974 | if (NodeInfo.hasProperty(SDNPCommutative)) { |
| 1975 | assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!"); |
| 1976 | // Don't count children which are actually register references. |
| 1977 | unsigned NC = 0; |
| 1978 | for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { |
| 1979 | TreePatternNode *Child = N->getChild(i); |
| 1980 | if (Child->isLeaf()) |
| 1981 | if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) { |
| 1982 | Record *RR = DI->getDef(); |
| 1983 | if (RR->isSubClassOf("Register")) |
| 1984 | continue; |
| 1985 | } |
| 1986 | NC++; |
| 1987 | } |
| 1988 | // Consider the commuted order. |
| 1989 | if (NC == 2) |
| 1990 | CombineChildVariants(N, ChildVariants[1], ChildVariants[0], |
| 1991 | OutVariants, CDP); |
| 1992 | } |
| 1993 | } |
| 1994 | |
| 1995 | |
| 1996 | // GenerateVariants - Generate variants. For example, commutative patterns can |
| 1997 | // match multiple ways. Add them to PatternsToMatch as well. |
Chris Lattner | fe71893 | 2008-01-06 01:10:31 +0000 | [diff] [blame] | 1998 | void CodeGenDAGPatterns::GenerateVariants() { |
Chris Lattner | 6cefb77 | 2008-01-05 22:25:12 +0000 | [diff] [blame] | 1999 | DOUT << "Generating instruction variants.\n"; |
| 2000 | |
| 2001 | // Loop over all of the patterns we've collected, checking to see if we can |
| 2002 | // generate variants of the instruction, through the exploitation of |
| 2003 | // identities. This permits the target to provide agressive matching without |
| 2004 | // the .td file having to contain tons of variants of instructions. |
| 2005 | // |
| 2006 | // Note that this loop adds new patterns to the PatternsToMatch list, but we |
| 2007 | // intentionally do not reconsider these. Any variants of added patterns have |
| 2008 | // already been added. |
| 2009 | // |
| 2010 | for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) { |
| 2011 | std::vector<TreePatternNode*> Variants; |
| 2012 | GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this); |
| 2013 | |
| 2014 | assert(!Variants.empty() && "Must create at least original variant!"); |
| 2015 | Variants.erase(Variants.begin()); // Remove the original pattern. |
| 2016 | |
| 2017 | if (Variants.empty()) // No variants for this pattern. |
| 2018 | continue; |
| 2019 | |
| 2020 | DOUT << "FOUND VARIANTS OF: "; |
| 2021 | DEBUG(PatternsToMatch[i].getSrcPattern()->dump()); |
| 2022 | DOUT << "\n"; |
| 2023 | |
| 2024 | for (unsigned v = 0, e = Variants.size(); v != e; ++v) { |
| 2025 | TreePatternNode *Variant = Variants[v]; |
| 2026 | |
| 2027 | DOUT << " VAR#" << v << ": "; |
| 2028 | DEBUG(Variant->dump()); |
| 2029 | DOUT << "\n"; |
| 2030 | |
| 2031 | // Scan to see if an instruction or explicit pattern already matches this. |
| 2032 | bool AlreadyExists = false; |
| 2033 | for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) { |
| 2034 | // Check to see if this variant already exists. |
| 2035 | if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) { |
| 2036 | DOUT << " *** ALREADY EXISTS, ignoring variant.\n"; |
| 2037 | AlreadyExists = true; |
| 2038 | break; |
| 2039 | } |
| 2040 | } |
| 2041 | // If we already have it, ignore the variant. |
| 2042 | if (AlreadyExists) continue; |
| 2043 | |
| 2044 | // Otherwise, add it to the list of patterns we have. |
| 2045 | PatternsToMatch. |
| 2046 | push_back(PatternToMatch(PatternsToMatch[i].getPredicates(), |
| 2047 | Variant, PatternsToMatch[i].getDstPattern(), |
| 2048 | PatternsToMatch[i].getDstRegs(), |
| 2049 | PatternsToMatch[i].getAddedComplexity())); |
| 2050 | } |
| 2051 | |
| 2052 | DOUT << "\n"; |
| 2053 | } |
| 2054 | } |
| 2055 | |