LegalizeTypes.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the SelectionDAG::LegalizeTypes method. It transforms
  11. // an arbitrary well-formed SelectionDAG to only consist of legal types. This
  12. // is common code shared among the LegalizeTypes*.cpp files.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "LegalizeTypes.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/IR/CallingConv.h"
  18. #include "llvm/IR/DataLayout.h"
  19. #include "llvm/Support/CommandLine.h"
  20. #include "llvm/Support/ErrorHandling.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace llvm;
  23. static cl::opt<bool>
  24. EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
  25. /// PerformExpensiveChecks - Do extensive, expensive, sanity checking.
  26. void DAGTypeLegalizer::PerformExpensiveChecks() {
  27. // If a node is not processed, then none of its values should be mapped by any
  28. // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
  29. // If a node is processed, then each value with an illegal type must be mapped
  30. // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
  31. // Values with a legal type may be mapped by ReplacedValues, but not by any of
  32. // the other maps.
  33. // Note that these invariants may not hold momentarily when processing a node:
  34. // the node being processed may be put in a map before being marked Processed.
  35. // Note that it is possible to have nodes marked NewNode in the DAG. This can
  36. // occur in two ways. Firstly, a node may be created during legalization but
  37. // never passed to the legalization core. This is usually due to the implicit
  38. // folding that occurs when using the DAG.getNode operators. Secondly, a new
  39. // node may be passed to the legalization core, but when analyzed may morph
  40. // into a different node, leaving the original node as a NewNode in the DAG.
  41. // A node may morph if one of its operands changes during analysis. Whether
  42. // it actually morphs or not depends on whether, after updating its operands,
  43. // it is equivalent to an existing node: if so, it morphs into that existing
  44. // node (CSE). An operand can change during analysis if the operand is a new
  45. // node that morphs, or it is a processed value that was mapped to some other
  46. // value (as recorded in ReplacedValues) in which case the operand is turned
  47. // into that other value. If a node morphs then the node it morphed into will
  48. // be used instead of it for legalization, however the original node continues
  49. // to live on in the DAG.
  50. // The conclusion is that though there may be nodes marked NewNode in the DAG,
  51. // all uses of such nodes are also marked NewNode: the result is a fungus of
  52. // NewNodes growing on top of the useful nodes, and perhaps using them, but
  53. // not used by them.
  54. // If a value is mapped by ReplacedValues, then it must have no uses, except
  55. // by nodes marked NewNode (see above).
  56. // The final node obtained by mapping by ReplacedValues is not marked NewNode.
  57. // Note that ReplacedValues should be applied iteratively.
  58. // Note that the ReplacedValues map may also map deleted nodes (by iterating
  59. // over the DAG we never dereference deleted nodes). This means that it may
  60. // also map nodes marked NewNode if the deallocated memory was reallocated as
  61. // another node, and that new node was not seen by the LegalizeTypes machinery
  62. // (for example because it was created but not used). In general, we cannot
  63. // distinguish between new nodes and deleted nodes.
  64. SmallVector<SDNode*, 16> NewNodes;
  65. for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
  66. E = DAG.allnodes_end(); I != E; ++I) {
  67. // Remember nodes marked NewNode - they are subject to extra checking below.
  68. if (I->getNodeId() == NewNode)
  69. NewNodes.push_back(I);
  70. for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
  71. SDValue Res(I, i);
  72. bool Failed = false;
  73. unsigned Mapped = 0;
  74. if (ReplacedValues.find(Res) != ReplacedValues.end()) {
  75. Mapped |= 1;
  76. // Check that remapped values are only used by nodes marked NewNode.
  77. for (SDNode::use_iterator UI = I->use_begin(), UE = I->use_end();
  78. UI != UE; ++UI)
  79. if (UI.getUse().getResNo() == i)
  80. assert(UI->getNodeId() == NewNode &&
  81. "Remapped value has non-trivial use!");
  82. // Check that the final result of applying ReplacedValues is not
  83. // marked NewNode.
  84. SDValue NewVal = ReplacedValues[Res];
  85. DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
  86. while (I != ReplacedValues.end()) {
  87. NewVal = I->second;
  88. I = ReplacedValues.find(NewVal);
  89. }
  90. assert(NewVal.getNode()->getNodeId() != NewNode &&
  91. "ReplacedValues maps to a new node!");
  92. }
  93. if (PromotedIntegers.find(Res) != PromotedIntegers.end())
  94. Mapped |= 2;
  95. if (SoftenedFloats.find(Res) != SoftenedFloats.end())
  96. Mapped |= 4;
  97. if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
  98. Mapped |= 8;
  99. if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
  100. Mapped |= 16;
  101. if (ExpandedFloats.find(Res) != ExpandedFloats.end())
  102. Mapped |= 32;
  103. if (SplitVectors.find(Res) != SplitVectors.end())
  104. Mapped |= 64;
  105. if (WidenedVectors.find(Res) != WidenedVectors.end())
  106. Mapped |= 128;
  107. if (I->getNodeId() != Processed) {
  108. // Since we allow ReplacedValues to map deleted nodes, it may map nodes
  109. // marked NewNode too, since a deleted node may have been reallocated as
  110. // another node that has not been seen by the LegalizeTypes machinery.
  111. if ((I->getNodeId() == NewNode && Mapped > 1) ||
  112. (I->getNodeId() != NewNode && Mapped != 0)) {
  113. dbgs() << "Unprocessed value in a map!";
  114. Failed = true;
  115. }
  116. } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
  117. if (Mapped > 1) {
  118. dbgs() << "Value with legal type was transformed!";
  119. Failed = true;
  120. }
  121. } else {
  122. if (Mapped == 0) {
  123. dbgs() << "Processed value not in any map!";
  124. Failed = true;
  125. } else if (Mapped & (Mapped - 1)) {
  126. dbgs() << "Value in multiple maps!";
  127. Failed = true;
  128. }
  129. }
  130. if (Failed) {
  131. if (Mapped & 1)
  132. dbgs() << " ReplacedValues";
  133. if (Mapped & 2)
  134. dbgs() << " PromotedIntegers";
  135. if (Mapped & 4)
  136. dbgs() << " SoftenedFloats";
  137. if (Mapped & 8)
  138. dbgs() << " ScalarizedVectors";
  139. if (Mapped & 16)
  140. dbgs() << " ExpandedIntegers";
  141. if (Mapped & 32)
  142. dbgs() << " ExpandedFloats";
  143. if (Mapped & 64)
  144. dbgs() << " SplitVectors";
  145. if (Mapped & 128)
  146. dbgs() << " WidenedVectors";
  147. dbgs() << "\n";
  148. llvm_unreachable(0);
  149. }
  150. }
  151. }
  152. // Checked that NewNodes are only used by other NewNodes.
  153. for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
  154. SDNode *N = NewNodes[i];
  155. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  156. UI != UE; ++UI)
  157. assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
  158. }
  159. }
  160. /// run - This is the main entry point for the type legalizer. This does a
  161. /// top-down traversal of the dag, legalizing types as it goes. Returns "true"
  162. /// if it made any changes.
  163. bool DAGTypeLegalizer::run() {
  164. bool Changed = false;
  165. // Create a dummy node (which is not added to allnodes), that adds a reference
  166. // to the root node, preventing it from being deleted, and tracking any
  167. // changes of the root.
  168. HandleSDNode Dummy(DAG.getRoot());
  169. Dummy.setNodeId(Unanalyzed);
  170. // The root of the dag may dangle to deleted nodes until the type legalizer is
  171. // done. Set it to null to avoid confusion.
  172. DAG.setRoot(SDValue());
  173. // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
  174. // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
  175. // non-leaves.
  176. for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
  177. E = DAG.allnodes_end(); I != E; ++I) {
  178. if (I->getNumOperands() == 0) {
  179. I->setNodeId(ReadyToProcess);
  180. Worklist.push_back(I);
  181. } else {
  182. I->setNodeId(Unanalyzed);
  183. }
  184. }
  185. // Now that we have a set of nodes to process, handle them all.
  186. while (!Worklist.empty()) {
  187. #ifndef XDEBUG
  188. if (EnableExpensiveChecks)
  189. #endif
  190. PerformExpensiveChecks();
  191. SDNode *N = Worklist.back();
  192. Worklist.pop_back();
  193. assert(N->getNodeId() == ReadyToProcess &&
  194. "Node should be ready if on worklist!");
  195. if (IgnoreNodeResults(N))
  196. goto ScanOperands;
  197. // Scan the values produced by the node, checking to see if any result
  198. // types are illegal.
  199. for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
  200. EVT ResultVT = N->getValueType(i);
  201. switch (getTypeAction(ResultVT)) {
  202. case TargetLowering::TypeLegal:
  203. break;
  204. // The following calls must take care of *all* of the node's results,
  205. // not just the illegal result they were passed (this includes results
  206. // with a legal type). Results can be remapped using ReplaceValueWith,
  207. // or their promoted/expanded/etc values registered in PromotedIntegers,
  208. // ExpandedIntegers etc.
  209. case TargetLowering::TypePromoteInteger:
  210. PromoteIntegerResult(N, i);
  211. Changed = true;
  212. goto NodeDone;
  213. case TargetLowering::TypeExpandInteger:
  214. ExpandIntegerResult(N, i);
  215. Changed = true;
  216. goto NodeDone;
  217. case TargetLowering::TypeSoftenFloat:
  218. SoftenFloatResult(N, i);
  219. Changed = true;
  220. goto NodeDone;
  221. case TargetLowering::TypeExpandFloat:
  222. ExpandFloatResult(N, i);
  223. Changed = true;
  224. goto NodeDone;
  225. case TargetLowering::TypeScalarizeVector:
  226. ScalarizeVectorResult(N, i);
  227. Changed = true;
  228. goto NodeDone;
  229. case TargetLowering::TypeSplitVector:
  230. SplitVectorResult(N, i);
  231. Changed = true;
  232. goto NodeDone;
  233. case TargetLowering::TypeWidenVector:
  234. WidenVectorResult(N, i);
  235. Changed = true;
  236. goto NodeDone;
  237. }
  238. }
  239. ScanOperands:
  240. // Scan the operand list for the node, handling any nodes with operands that
  241. // are illegal.
  242. {
  243. unsigned NumOperands = N->getNumOperands();
  244. bool NeedsReanalyzing = false;
  245. unsigned i;
  246. for (i = 0; i != NumOperands; ++i) {
  247. if (IgnoreNodeResults(N->getOperand(i).getNode()))
  248. continue;
  249. EVT OpVT = N->getOperand(i).getValueType();
  250. switch (getTypeAction(OpVT)) {
  251. case TargetLowering::TypeLegal:
  252. continue;
  253. // The following calls must either replace all of the node's results
  254. // using ReplaceValueWith, and return "false"; or update the node's
  255. // operands in place, and return "true".
  256. case TargetLowering::TypePromoteInteger:
  257. NeedsReanalyzing = PromoteIntegerOperand(N, i);
  258. Changed = true;
  259. break;
  260. case TargetLowering::TypeExpandInteger:
  261. NeedsReanalyzing = ExpandIntegerOperand(N, i);
  262. Changed = true;
  263. break;
  264. case TargetLowering::TypeSoftenFloat:
  265. NeedsReanalyzing = SoftenFloatOperand(N, i);
  266. Changed = true;
  267. break;
  268. case TargetLowering::TypeExpandFloat:
  269. NeedsReanalyzing = ExpandFloatOperand(N, i);
  270. Changed = true;
  271. break;
  272. case TargetLowering::TypeScalarizeVector:
  273. NeedsReanalyzing = ScalarizeVectorOperand(N, i);
  274. Changed = true;
  275. break;
  276. case TargetLowering::TypeSplitVector:
  277. NeedsReanalyzing = SplitVectorOperand(N, i);
  278. Changed = true;
  279. break;
  280. case TargetLowering::TypeWidenVector:
  281. NeedsReanalyzing = WidenVectorOperand(N, i);
  282. Changed = true;
  283. break;
  284. }
  285. break;
  286. }
  287. // The sub-method updated N in place. Check to see if any operands are new,
  288. // and if so, mark them. If the node needs revisiting, don't add all users
  289. // to the worklist etc.
  290. if (NeedsReanalyzing) {
  291. assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
  292. N->setNodeId(NewNode);
  293. // Recompute the NodeId and correct processed operands, adding the node to
  294. // the worklist if ready.
  295. SDNode *M = AnalyzeNewNode(N);
  296. if (M == N)
  297. // The node didn't morph - nothing special to do, it will be revisited.
  298. continue;
  299. // The node morphed - this is equivalent to legalizing by replacing every
  300. // value of N with the corresponding value of M. So do that now.
  301. assert(N->getNumValues() == M->getNumValues() &&
  302. "Node morphing changed the number of results!");
  303. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
  304. // Replacing the value takes care of remapping the new value.
  305. ReplaceValueWith(SDValue(N, i), SDValue(M, i));
  306. assert(N->getNodeId() == NewNode && "Unexpected node state!");
  307. // The node continues to live on as part of the NewNode fungus that
  308. // grows on top of the useful nodes. Nothing more needs to be done
  309. // with it - move on to the next node.
  310. continue;
  311. }
  312. if (i == NumOperands) {
  313. DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG); dbgs() << "\n");
  314. }
  315. }
  316. NodeDone:
  317. // If we reach here, the node was processed, potentially creating new nodes.
  318. // Mark it as processed and add its users to the worklist as appropriate.
  319. assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
  320. N->setNodeId(Processed);
  321. for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
  322. UI != E; ++UI) {
  323. SDNode *User = *UI;
  324. int NodeId = User->getNodeId();
  325. // This node has two options: it can either be a new node or its Node ID
  326. // may be a count of the number of operands it has that are not ready.
  327. if (NodeId > 0) {
  328. User->setNodeId(NodeId-1);
  329. // If this was the last use it was waiting on, add it to the ready list.
  330. if (NodeId-1 == ReadyToProcess)
  331. Worklist.push_back(User);
  332. continue;
  333. }
  334. // If this is an unreachable new node, then ignore it. If it ever becomes
  335. // reachable by being used by a newly created node then it will be handled
  336. // by AnalyzeNewNode.
  337. if (NodeId == NewNode)
  338. continue;
  339. // Otherwise, this node is new: this is the first operand of it that
  340. // became ready. Its new NodeId is the number of operands it has minus 1
  341. // (as this node is now processed).
  342. assert(NodeId == Unanalyzed && "Unknown node ID!");
  343. User->setNodeId(User->getNumOperands() - 1);
  344. // If the node only has a single operand, it is now ready.
  345. if (User->getNumOperands() == 1)
  346. Worklist.push_back(User);
  347. }
  348. }
  349. #ifndef XDEBUG
  350. if (EnableExpensiveChecks)
  351. #endif
  352. PerformExpensiveChecks();
  353. // If the root changed (e.g. it was a dead load) update the root.
  354. DAG.setRoot(Dummy.getValue());
  355. // Remove dead nodes. This is important to do for cleanliness but also before
  356. // the checking loop below. Implicit folding by the DAG.getNode operators and
  357. // node morphing can cause unreachable nodes to be around with their flags set
  358. // to new.
  359. DAG.RemoveDeadNodes();
  360. // In a debug build, scan all the nodes to make sure we found them all. This
  361. // ensures that there are no cycles and that everything got processed.
  362. #ifndef NDEBUG
  363. for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
  364. E = DAG.allnodes_end(); I != E; ++I) {
  365. bool Failed = false;
  366. // Check that all result types are legal.
  367. if (!IgnoreNodeResults(I))
  368. for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
  369. if (!isTypeLegal(I->getValueType(i))) {
  370. dbgs() << "Result type " << i << " illegal!\n";
  371. Failed = true;
  372. }
  373. // Check that all operand types are legal.
  374. for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
  375. if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
  376. !isTypeLegal(I->getOperand(i).getValueType())) {
  377. dbgs() << "Operand type " << i << " illegal!\n";
  378. Failed = true;
  379. }
  380. if (I->getNodeId() != Processed) {
  381. if (I->getNodeId() == NewNode)
  382. dbgs() << "New node not analyzed?\n";
  383. else if (I->getNodeId() == Unanalyzed)
  384. dbgs() << "Unanalyzed node not noticed?\n";
  385. else if (I->getNodeId() > 0)
  386. dbgs() << "Operand not processed?\n";
  387. else if (I->getNodeId() == ReadyToProcess)
  388. dbgs() << "Not added to worklist?\n";
  389. Failed = true;
  390. }
  391. if (Failed) {
  392. I->dump(&DAG); dbgs() << "\n";
  393. llvm_unreachable(0);
  394. }
  395. }
  396. #endif
  397. return Changed;
  398. }
  399. /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
  400. /// new nodes. Correct any processed operands (this may change the node) and
  401. /// calculate the NodeId. If the node itself changes to a processed node, it
  402. /// is not remapped - the caller needs to take care of this.
  403. /// Returns the potentially changed node.
  404. SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
  405. // If this was an existing node that is already done, we're done.
  406. if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
  407. return N;
  408. // Remove any stale map entries.
  409. ExpungeNode(N);
  410. // Okay, we know that this node is new. Recursively walk all of its operands
  411. // to see if they are new also. The depth of this walk is bounded by the size
  412. // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
  413. // about revisiting of nodes.
  414. //
  415. // As we walk the operands, keep track of the number of nodes that are
  416. // processed. If non-zero, this will become the new nodeid of this node.
  417. // Operands may morph when they are analyzed. If so, the node will be
  418. // updated after all operands have been analyzed. Since this is rare,
  419. // the code tries to minimize overhead in the non-morphing case.
  420. SmallVector<SDValue, 8> NewOps;
  421. unsigned NumProcessed = 0;
  422. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  423. SDValue OrigOp = N->getOperand(i);
  424. SDValue Op = OrigOp;
  425. AnalyzeNewValue(Op); // Op may morph.
  426. if (Op.getNode()->getNodeId() == Processed)
  427. ++NumProcessed;
  428. if (!NewOps.empty()) {
  429. // Some previous operand changed. Add this one to the list.
  430. NewOps.push_back(Op);
  431. } else if (Op != OrigOp) {
  432. // This is the first operand to change - add all operands so far.
  433. NewOps.append(N->op_begin(), N->op_begin() + i);
  434. NewOps.push_back(Op);
  435. }
  436. }
  437. // Some operands changed - update the node.
  438. if (!NewOps.empty()) {
  439. SDNode *M = DAG.UpdateNodeOperands(N, &NewOps[0], NewOps.size());
  440. if (M != N) {
  441. // The node morphed into a different node. Normally for this to happen
  442. // the original node would have to be marked NewNode. However this can
  443. // in theory momentarily not be the case while ReplaceValueWith is doing
  444. // its stuff. Mark the original node NewNode to help sanity checking.
  445. N->setNodeId(NewNode);
  446. if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
  447. // It morphed into a previously analyzed node - nothing more to do.
  448. return M;
  449. // It morphed into a different new node. Do the equivalent of passing
  450. // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
  451. // to remap the operands, since they are the same as the operands we
  452. // remapped above.
  453. N = M;
  454. ExpungeNode(N);
  455. }
  456. }
  457. // Calculate the NodeId.
  458. N->setNodeId(N->getNumOperands() - NumProcessed);
  459. if (N->getNodeId() == ReadyToProcess)
  460. Worklist.push_back(N);
  461. return N;
  462. }
  463. /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
  464. /// If the node changes to a processed node, then remap it.
  465. void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
  466. Val.setNode(AnalyzeNewNode(Val.getNode()));
  467. if (Val.getNode()->getNodeId() == Processed)
  468. // We were passed a processed node, or it morphed into one - remap it.
  469. RemapValue(Val);
  470. }
  471. /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
  472. /// This can occur when a node is deleted then reallocated as a new node -
  473. /// the mapping in ReplacedValues applies to the deleted node, not the new
  474. /// one.
  475. /// The only map that can have a deleted node as a source is ReplacedValues.
  476. /// Other maps can have deleted nodes as targets, but since their looked-up
  477. /// values are always immediately remapped using RemapValue, resulting in a
  478. /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
  479. /// always performs correct mappings. In order to keep the mapping correct,
  480. /// ExpungeNode should be called on any new nodes *before* adding them as
  481. /// either source or target to ReplacedValues (which typically means calling
  482. /// Expunge when a new node is first seen, since it may no longer be marked
  483. /// NewNode by the time it is added to ReplacedValues).
  484. void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
  485. if (N->getNodeId() != NewNode)
  486. return;
  487. // If N is not remapped by ReplacedValues then there is nothing to do.
  488. unsigned i, e;
  489. for (i = 0, e = N->getNumValues(); i != e; ++i)
  490. if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
  491. break;
  492. if (i == e)
  493. return;
  494. // Remove N from all maps - this is expensive but rare.
  495. for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
  496. E = PromotedIntegers.end(); I != E; ++I) {
  497. assert(I->first.getNode() != N);
  498. RemapValue(I->second);
  499. }
  500. for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
  501. E = SoftenedFloats.end(); I != E; ++I) {
  502. assert(I->first.getNode() != N);
  503. RemapValue(I->second);
  504. }
  505. for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
  506. E = ScalarizedVectors.end(); I != E; ++I) {
  507. assert(I->first.getNode() != N);
  508. RemapValue(I->second);
  509. }
  510. for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
  511. E = WidenedVectors.end(); I != E; ++I) {
  512. assert(I->first.getNode() != N);
  513. RemapValue(I->second);
  514. }
  515. for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
  516. I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
  517. assert(I->first.getNode() != N);
  518. RemapValue(I->second.first);
  519. RemapValue(I->second.second);
  520. }
  521. for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
  522. I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
  523. assert(I->first.getNode() != N);
  524. RemapValue(I->second.first);
  525. RemapValue(I->second.second);
  526. }
  527. for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
  528. I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
  529. assert(I->first.getNode() != N);
  530. RemapValue(I->second.first);
  531. RemapValue(I->second.second);
  532. }
  533. for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
  534. E = ReplacedValues.end(); I != E; ++I)
  535. RemapValue(I->second);
  536. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
  537. ReplacedValues.erase(SDValue(N, i));
  538. }
  539. /// RemapValue - If the specified value was already legalized to another value,
  540. /// replace it by that value.
  541. void DAGTypeLegalizer::RemapValue(SDValue &N) {
  542. DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
  543. if (I != ReplacedValues.end()) {
  544. // Use path compression to speed up future lookups if values get multiply
  545. // replaced with other values.
  546. RemapValue(I->second);
  547. N = I->second;
  548. assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!");
  549. }
  550. }
  551. namespace {
  552. /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
  553. /// updates to nodes and recomputes their ready state.
  554. class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
  555. DAGTypeLegalizer &DTL;
  556. SmallSetVector<SDNode*, 16> &NodesToAnalyze;
  557. public:
  558. explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
  559. SmallSetVector<SDNode*, 16> &nta)
  560. : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
  561. DTL(dtl), NodesToAnalyze(nta) {}
  562. virtual void NodeDeleted(SDNode *N, SDNode *E) {
  563. assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
  564. N->getNodeId() != DAGTypeLegalizer::Processed &&
  565. "Invalid node ID for RAUW deletion!");
  566. // It is possible, though rare, for the deleted node N to occur as a
  567. // target in a map, so note the replacement N -> E in ReplacedValues.
  568. assert(E && "Node not replaced?");
  569. DTL.NoteDeletion(N, E);
  570. // In theory the deleted node could also have been scheduled for analysis.
  571. // So remove it from the set of nodes which will be analyzed.
  572. NodesToAnalyze.remove(N);
  573. // In general nothing needs to be done for E, since it didn't change but
  574. // only gained new uses. However N -> E was just added to ReplacedValues,
  575. // and the result of a ReplacedValues mapping is not allowed to be marked
  576. // NewNode. So if E is marked NewNode, then it needs to be analyzed.
  577. if (E->getNodeId() == DAGTypeLegalizer::NewNode)
  578. NodesToAnalyze.insert(E);
  579. }
  580. virtual void NodeUpdated(SDNode *N) {
  581. // Node updates can mean pretty much anything. It is possible that an
  582. // operand was set to something already processed (f.e.) in which case
  583. // this node could become ready. Recompute its flags.
  584. assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
  585. N->getNodeId() != DAGTypeLegalizer::Processed &&
  586. "Invalid node ID for RAUW deletion!");
  587. N->setNodeId(DAGTypeLegalizer::NewNode);
  588. NodesToAnalyze.insert(N);
  589. }
  590. };
  591. }
  592. /// ReplaceValueWith - The specified value was legalized to the specified other
  593. /// value. Update the DAG and NodeIds replacing any uses of From to use To
  594. /// instead.
  595. void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
  596. assert(From.getNode() != To.getNode() && "Potential legalization loop!");
  597. // If expansion produced new nodes, make sure they are properly marked.
  598. ExpungeNode(From.getNode());
  599. AnalyzeNewValue(To); // Expunges To.
  600. // Anything that used the old node should now use the new one. Note that this
  601. // can potentially cause recursive merging.
  602. SmallSetVector<SDNode*, 16> NodesToAnalyze;
  603. NodeUpdateListener NUL(*this, NodesToAnalyze);
  604. do {
  605. DAG.ReplaceAllUsesOfValueWith(From, To);
  606. // The old node may still be present in a map like ExpandedIntegers or
  607. // PromotedIntegers. Inform maps about the replacement.
  608. ReplacedValues[From] = To;
  609. // Process the list of nodes that need to be reanalyzed.
  610. while (!NodesToAnalyze.empty()) {
  611. SDNode *N = NodesToAnalyze.back();
  612. NodesToAnalyze.pop_back();
  613. if (N->getNodeId() != DAGTypeLegalizer::NewNode)
  614. // The node was analyzed while reanalyzing an earlier node - it is safe
  615. // to skip. Note that this is not a morphing node - otherwise it would
  616. // still be marked NewNode.
  617. continue;
  618. // Analyze the node's operands and recalculate the node ID.
  619. SDNode *M = AnalyzeNewNode(N);
  620. if (M != N) {
  621. // The node morphed into a different node. Make everyone use the new
  622. // node instead.
  623. assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
  624. assert(N->getNumValues() == M->getNumValues() &&
  625. "Node morphing changed the number of results!");
  626. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
  627. SDValue OldVal(N, i);
  628. SDValue NewVal(M, i);
  629. if (M->getNodeId() == Processed)
  630. RemapValue(NewVal);
  631. DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
  632. // OldVal may be a target of the ReplacedValues map which was marked
  633. // NewNode to force reanalysis because it was updated. Ensure that
  634. // anything that ReplacedValues mapped to OldVal will now be mapped
  635. // all the way to NewVal.
  636. ReplacedValues[OldVal] = NewVal;
  637. }
  638. // The original node continues to exist in the DAG, marked NewNode.
  639. }
  640. }
  641. // When recursively update nodes with new nodes, it is possible to have
  642. // new uses of From due to CSE. If this happens, replace the new uses of
  643. // From with To.
  644. } while (!From.use_empty());
  645. }
  646. void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
  647. assert(Result.getValueType() ==
  648. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  649. "Invalid type for promoted integer");
  650. AnalyzeNewValue(Result);
  651. SDValue &OpEntry = PromotedIntegers[Op];
  652. assert(OpEntry.getNode() == 0 && "Node is already promoted!");
  653. OpEntry = Result;
  654. }
  655. void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
  656. assert(Result.getValueType() ==
  657. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  658. "Invalid type for softened float");
  659. AnalyzeNewValue(Result);
  660. SDValue &OpEntry = SoftenedFloats[Op];
  661. assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
  662. OpEntry = Result;
  663. }
  664. void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
  665. // Note that in some cases vector operation operands may be greater than
  666. // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
  667. // a constant i8 operand.
  668. assert(Result.getValueType().getSizeInBits() >=
  669. Op.getValueType().getVectorElementType().getSizeInBits() &&
  670. "Invalid type for scalarized vector");
  671. AnalyzeNewValue(Result);
  672. SDValue &OpEntry = ScalarizedVectors[Op];
  673. assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
  674. OpEntry = Result;
  675. }
  676. void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
  677. SDValue &Hi) {
  678. std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
  679. RemapValue(Entry.first);
  680. RemapValue(Entry.second);
  681. assert(Entry.first.getNode() && "Operand isn't expanded");
  682. Lo = Entry.first;
  683. Hi = Entry.second;
  684. }
  685. void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
  686. SDValue Hi) {
  687. assert(Lo.getValueType() ==
  688. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  689. Hi.getValueType() == Lo.getValueType() &&
  690. "Invalid type for expanded integer");
  691. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  692. AnalyzeNewValue(Lo);
  693. AnalyzeNewValue(Hi);
  694. // Remember that this is the result of the node.
  695. std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
  696. assert(Entry.first.getNode() == 0 && "Node already expanded");
  697. Entry.first = Lo;
  698. Entry.second = Hi;
  699. }
  700. void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
  701. SDValue &Hi) {
  702. std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
  703. RemapValue(Entry.first);
  704. RemapValue(Entry.second);
  705. assert(Entry.first.getNode() && "Operand isn't expanded");
  706. Lo = Entry.first;
  707. Hi = Entry.second;
  708. }
  709. void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
  710. SDValue Hi) {
  711. assert(Lo.getValueType() ==
  712. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  713. Hi.getValueType() == Lo.getValueType() &&
  714. "Invalid type for expanded float");
  715. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  716. AnalyzeNewValue(Lo);
  717. AnalyzeNewValue(Hi);
  718. // Remember that this is the result of the node.
  719. std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
  720. assert(Entry.first.getNode() == 0 && "Node already expanded");
  721. Entry.first = Lo;
  722. Entry.second = Hi;
  723. }
  724. void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
  725. SDValue &Hi) {
  726. std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
  727. RemapValue(Entry.first);
  728. RemapValue(Entry.second);
  729. assert(Entry.first.getNode() && "Operand isn't split");
  730. Lo = Entry.first;
  731. Hi = Entry.second;
  732. }
  733. void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
  734. SDValue Hi) {
  735. assert(Lo.getValueType().getVectorElementType() ==
  736. Op.getValueType().getVectorElementType() &&
  737. 2*Lo.getValueType().getVectorNumElements() ==
  738. Op.getValueType().getVectorNumElements() &&
  739. Hi.getValueType() == Lo.getValueType() &&
  740. "Invalid type for split vector");
  741. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  742. AnalyzeNewValue(Lo);
  743. AnalyzeNewValue(Hi);
  744. // Remember that this is the result of the node.
  745. std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
  746. assert(Entry.first.getNode() == 0 && "Node already split");
  747. Entry.first = Lo;
  748. Entry.second = Hi;
  749. }
  750. void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
  751. assert(Result.getValueType() ==
  752. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  753. "Invalid type for widened vector");
  754. AnalyzeNewValue(Result);
  755. SDValue &OpEntry = WidenedVectors[Op];
  756. assert(OpEntry.getNode() == 0 && "Node already widened!");
  757. OpEntry = Result;
  758. }
  759. //===----------------------------------------------------------------------===//
  760. // Utilities.
  761. //===----------------------------------------------------------------------===//
  762. /// BitConvertToInteger - Convert to an integer of the same size.
  763. SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
  764. unsigned BitWidth = Op.getValueType().getSizeInBits();
  765. return DAG.getNode(ISD::BITCAST, SDLoc(Op),
  766. EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
  767. }
  768. /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
  769. /// same size.
  770. SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
  771. assert(Op.getValueType().isVector() && "Only applies to vectors!");
  772. unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
  773. EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
  774. unsigned NumElts = Op.getValueType().getVectorNumElements();
  775. return DAG.getNode(ISD::BITCAST, SDLoc(Op),
  776. EVT::getVectorVT(*DAG.getContext(), EltNVT, NumElts), Op);
  777. }
  778. SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
  779. EVT DestVT) {
  780. SDLoc dl(Op);
  781. // Create the stack frame object. Make sure it is aligned for both
  782. // the source and destination types.
  783. SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
  784. // Emit a store to the stack slot.
  785. SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr,
  786. MachinePointerInfo(), false, false, 0);
  787. // Result is a load from the stack slot.
  788. return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo(),
  789. false, false, false, 0);
  790. }
  791. /// CustomLowerNode - Replace the node's results with custom code provided
  792. /// by the target and return "true", or do nothing and return "false".
  793. /// The last parameter is FALSE if we are dealing with a node with legal
  794. /// result types and illegal operand. The second parameter denotes the type of
  795. /// illegal OperandNo in that case.
  796. /// The last parameter being TRUE means we are dealing with a
  797. /// node with illegal result types. The second parameter denotes the type of
  798. /// illegal ResNo in that case.
  799. bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
  800. // See if the target wants to custom lower this node.
  801. if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
  802. return false;
  803. SmallVector<SDValue, 8> Results;
  804. if (LegalizeResult)
  805. TLI.ReplaceNodeResults(N, Results, DAG);
  806. else
  807. TLI.LowerOperationWrapper(N, Results, DAG);
  808. if (Results.empty())
  809. // The target didn't want to custom lower it after all.
  810. return false;
  811. // Make everything that once used N's values now use those in Results instead.
  812. assert(Results.size() == N->getNumValues() &&
  813. "Custom lowering returned the wrong number of results!");
  814. for (unsigned i = 0, e = Results.size(); i != e; ++i) {
  815. ReplaceValueWith(SDValue(N, i), Results[i]);
  816. }
  817. return true;
  818. }
  819. /// CustomWidenLowerNode - Widen the node's results with custom code provided
  820. /// by the target and return "true", or do nothing and return "false".
  821. bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
  822. // See if the target wants to custom lower this node.
  823. if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
  824. return false;
  825. SmallVector<SDValue, 8> Results;
  826. TLI.ReplaceNodeResults(N, Results, DAG);
  827. if (Results.empty())
  828. // The target didn't want to custom widen lower its result after all.
  829. return false;
  830. // Update the widening map.
  831. assert(Results.size() == N->getNumValues() &&
  832. "Custom lowering returned the wrong number of results!");
  833. for (unsigned i = 0, e = Results.size(); i != e; ++i)
  834. SetWidenedVector(SDValue(N, i), Results[i]);
  835. return true;
  836. }
  837. SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
  838. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
  839. if (i != ResNo)
  840. ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
  841. return SDValue(N->getOperand(ResNo));
  842. }
  843. /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
  844. /// which is split into two not necessarily identical pieces.
  845. void DAGTypeLegalizer::GetSplitDestVTs(EVT InVT, EVT &LoVT, EVT &HiVT) {
  846. // Currently all types are split in half.
  847. if (!InVT.isVector()) {
  848. LoVT = HiVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
  849. } else {
  850. unsigned NumElements = InVT.getVectorNumElements();
  851. assert(!(NumElements & 1) && "Splitting vector, but not in half!");
  852. LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
  853. InVT.getVectorElementType(), NumElements/2);
  854. }
  855. }
  856. /// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
  857. /// high parts of the given value.
  858. void DAGTypeLegalizer::GetPairElements(SDValue Pair,
  859. SDValue &Lo, SDValue &Hi) {
  860. SDLoc dl(Pair);
  861. EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
  862. Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
  863. DAG.getIntPtrConstant(0));
  864. Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
  865. DAG.getIntPtrConstant(1));
  866. }
  867. SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, EVT EltVT,
  868. SDValue Index) {
  869. SDLoc dl(Index);
  870. // Make sure the index type is big enough to compute in.
  871. if (Index.getValueType().bitsGT(TLI.getPointerTy()))
  872. Index = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Index);
  873. else
  874. Index = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Index);
  875. // Calculate the element offset and add it to the pointer.
  876. unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
  877. Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
  878. DAG.getConstant(EltSize, Index.getValueType()));
  879. return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
  880. }
  881. /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
  882. SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
  883. // Arbitrarily use dlHi for result SDLoc
  884. SDLoc dlHi(Hi);
  885. SDLoc dlLo(Lo);
  886. EVT LVT = Lo.getValueType();
  887. EVT HVT = Hi.getValueType();
  888. EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
  889. LVT.getSizeInBits() + HVT.getSizeInBits());
  890. Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
  891. Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
  892. Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
  893. DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy()));
  894. return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
  895. }
  896. /// LibCallify - Convert the node into a libcall with the same prototype.
  897. SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
  898. bool isSigned) {
  899. unsigned NumOps = N->getNumOperands();
  900. SDLoc dl(N);
  901. if (NumOps == 0) {
  902. return TLI.makeLibCall(DAG, LC, N->getValueType(0), 0, 0, isSigned, dl);
  903. } else if (NumOps == 1) {
  904. SDValue Op = N->getOperand(0);
  905. return TLI.makeLibCall(DAG, LC, N->getValueType(0), &Op, 1, isSigned, dl);
  906. } else if (NumOps == 2) {
  907. SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
  908. return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, 2, isSigned, dl);
  909. }
  910. SmallVector<SDValue, 8> Ops(NumOps);
  911. for (unsigned i = 0; i < NumOps; ++i)
  912. Ops[i] = N->getOperand(i);
  913. return TLI.makeLibCall(DAG, LC, N->getValueType(0),
  914. &Ops[0], NumOps, isSigned, dl);
  915. }
  916. // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
  917. // ExpandLibCall except that the first operand is the in-chain.
  918. std::pair<SDValue, SDValue>
  919. DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC,
  920. SDNode *Node,
  921. bool isSigned) {
  922. SDValue InChain = Node->getOperand(0);
  923. TargetLowering::ArgListTy Args;
  924. TargetLowering::ArgListEntry Entry;
  925. for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
  926. EVT ArgVT = Node->getOperand(i).getValueType();
  927. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  928. Entry.Node = Node->getOperand(i);
  929. Entry.Ty = ArgTy;
  930. Entry.isSExt = isSigned;
  931. Entry.isZExt = !isSigned;
  932. Args.push_back(Entry);
  933. }
  934. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  935. TLI.getPointerTy());
  936. Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
  937. TargetLowering::
  938. CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, false,
  939. 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
  940. /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
  941. Callee, Args, DAG, SDLoc(Node));
  942. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  943. return CallInfo;
  944. }
  945. /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
  946. /// of the given type. A target boolean is an integer value, not necessarily of
  947. /// type i1, the bits of which conform to getBooleanContents.
  948. SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT VT) {
  949. SDLoc dl(Bool);
  950. ISD::NodeType ExtendCode =
  951. TargetLowering::getExtendForContent(TLI.getBooleanContents(VT.isVector()));
  952. return DAG.getNode(ExtendCode, dl, VT, Bool);
  953. }
  954. /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
  955. /// bits in Hi.
  956. void DAGTypeLegalizer::SplitInteger(SDValue Op,
  957. EVT LoVT, EVT HiVT,
  958. SDValue &Lo, SDValue &Hi) {
  959. SDLoc dl(Op);
  960. assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
  961. Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
  962. Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
  963. Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
  964. DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy()));
  965. Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
  966. }
  967. /// SplitInteger - Return the lower and upper halves of Op's bits in a value
  968. /// type half the size of Op's.
  969. void DAGTypeLegalizer::SplitInteger(SDValue Op,
  970. SDValue &Lo, SDValue &Hi) {
  971. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(),
  972. Op.getValueType().getSizeInBits()/2);
  973. SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
  974. }
  975. //===----------------------------------------------------------------------===//
  976. // Entry Point
  977. //===----------------------------------------------------------------------===//
  978. /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
  979. /// only uses types natively supported by the target. Returns "true" if it made
  980. /// any changes.
  981. ///
  982. /// Note that this is an involved process that may invalidate pointers into
  983. /// the graph.
  984. bool SelectionDAG::LegalizeTypes() {
  985. return DAGTypeLegalizer(*this).run();
  986. }