LegalizeTypes.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. // Propagate node ordering
  655. DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
  656. }
  657. void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
  658. assert(Result.getValueType() ==
  659. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  660. "Invalid type for softened float");
  661. AnalyzeNewValue(Result);
  662. SDValue &OpEntry = SoftenedFloats[Op];
  663. assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
  664. OpEntry = Result;
  665. // Propagate node ordering
  666. DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
  667. }
  668. void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
  669. // Note that in some cases vector operation operands may be greater than
  670. // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
  671. // a constant i8 operand.
  672. assert(Result.getValueType().getSizeInBits() >=
  673. Op.getValueType().getVectorElementType().getSizeInBits() &&
  674. "Invalid type for scalarized vector");
  675. AnalyzeNewValue(Result);
  676. SDValue &OpEntry = ScalarizedVectors[Op];
  677. assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
  678. OpEntry = Result;
  679. // Propagate node ordering
  680. DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
  681. }
  682. void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
  683. SDValue &Hi) {
  684. std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
  685. RemapValue(Entry.first);
  686. RemapValue(Entry.second);
  687. assert(Entry.first.getNode() && "Operand isn't expanded");
  688. Lo = Entry.first;
  689. Hi = Entry.second;
  690. }
  691. void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
  692. SDValue Hi) {
  693. assert(Lo.getValueType() ==
  694. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  695. Hi.getValueType() == Lo.getValueType() &&
  696. "Invalid type for expanded integer");
  697. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  698. AnalyzeNewValue(Lo);
  699. AnalyzeNewValue(Hi);
  700. // Remember that this is the result of the node.
  701. std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
  702. assert(Entry.first.getNode() == 0 && "Node already expanded");
  703. Entry.first = Lo;
  704. Entry.second = Hi;
  705. // Propagate ordering
  706. DAG.AssignOrdering(Lo.getNode(), DAG.GetOrdering(Op.getNode()));
  707. DAG.AssignOrdering(Hi.getNode(), DAG.GetOrdering(Op.getNode()));
  708. }
  709. void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
  710. SDValue &Hi) {
  711. std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
  712. RemapValue(Entry.first);
  713. RemapValue(Entry.second);
  714. assert(Entry.first.getNode() && "Operand isn't expanded");
  715. Lo = Entry.first;
  716. Hi = Entry.second;
  717. }
  718. void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
  719. SDValue Hi) {
  720. assert(Lo.getValueType() ==
  721. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  722. Hi.getValueType() == Lo.getValueType() &&
  723. "Invalid type for expanded float");
  724. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  725. AnalyzeNewValue(Lo);
  726. AnalyzeNewValue(Hi);
  727. // Remember that this is the result of the node.
  728. std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
  729. assert(Entry.first.getNode() == 0 && "Node already expanded");
  730. Entry.first = Lo;
  731. Entry.second = Hi;
  732. // Propagate ordering
  733. DAG.AssignOrdering(Lo.getNode(), DAG.GetOrdering(Op.getNode()));
  734. DAG.AssignOrdering(Hi.getNode(), DAG.GetOrdering(Op.getNode()));
  735. }
  736. void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
  737. SDValue &Hi) {
  738. std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
  739. RemapValue(Entry.first);
  740. RemapValue(Entry.second);
  741. assert(Entry.first.getNode() && "Operand isn't split");
  742. Lo = Entry.first;
  743. Hi = Entry.second;
  744. }
  745. void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
  746. SDValue Hi) {
  747. assert(Lo.getValueType().getVectorElementType() ==
  748. Op.getValueType().getVectorElementType() &&
  749. 2*Lo.getValueType().getVectorNumElements() ==
  750. Op.getValueType().getVectorNumElements() &&
  751. Hi.getValueType() == Lo.getValueType() &&
  752. "Invalid type for split vector");
  753. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  754. AnalyzeNewValue(Lo);
  755. AnalyzeNewValue(Hi);
  756. // Remember that this is the result of the node.
  757. std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
  758. assert(Entry.first.getNode() == 0 && "Node already split");
  759. Entry.first = Lo;
  760. Entry.second = Hi;
  761. // Propagate ordering
  762. DAG.AssignOrdering(Lo.getNode(), DAG.GetOrdering(Op.getNode()));
  763. DAG.AssignOrdering(Hi.getNode(), DAG.GetOrdering(Op.getNode()));
  764. }
  765. void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
  766. assert(Result.getValueType() ==
  767. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  768. "Invalid type for widened vector");
  769. AnalyzeNewValue(Result);
  770. SDValue &OpEntry = WidenedVectors[Op];
  771. assert(OpEntry.getNode() == 0 && "Node already widened!");
  772. OpEntry = Result;
  773. // Propagate node ordering
  774. DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
  775. }
  776. //===----------------------------------------------------------------------===//
  777. // Utilities.
  778. //===----------------------------------------------------------------------===//
  779. /// BitConvertToInteger - Convert to an integer of the same size.
  780. SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
  781. unsigned BitWidth = Op.getValueType().getSizeInBits();
  782. return DAG.getNode(ISD::BITCAST, SDLoc(Op),
  783. EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
  784. }
  785. /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
  786. /// same size.
  787. SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
  788. assert(Op.getValueType().isVector() && "Only applies to vectors!");
  789. unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
  790. EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
  791. unsigned NumElts = Op.getValueType().getVectorNumElements();
  792. return DAG.getNode(ISD::BITCAST, SDLoc(Op),
  793. EVT::getVectorVT(*DAG.getContext(), EltNVT, NumElts), Op);
  794. }
  795. SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
  796. EVT DestVT) {
  797. SDLoc dl(Op);;
  798. // Create the stack frame object. Make sure it is aligned for both
  799. // the source and destination types.
  800. SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
  801. // Emit a store to the stack slot.
  802. SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr,
  803. MachinePointerInfo(), false, false, 0);
  804. // Result is a load from the stack slot.
  805. return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo(),
  806. false, false, false, 0);
  807. }
  808. /// CustomLowerNode - Replace the node's results with custom code provided
  809. /// by the target and return "true", or do nothing and return "false".
  810. /// The last parameter is FALSE if we are dealing with a node with legal
  811. /// result types and illegal operand. The second parameter denotes the type of
  812. /// illegal OperandNo in that case.
  813. /// The last parameter being TRUE means we are dealing with a
  814. /// node with illegal result types. The second parameter denotes the type of
  815. /// illegal ResNo in that case.
  816. bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
  817. // See if the target wants to custom lower this node.
  818. if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
  819. return false;
  820. SmallVector<SDValue, 8> Results;
  821. if (LegalizeResult)
  822. TLI.ReplaceNodeResults(N, Results, DAG);
  823. else
  824. TLI.LowerOperationWrapper(N, Results, DAG);
  825. if (Results.empty())
  826. // The target didn't want to custom lower it after all.
  827. return false;
  828. // Make everything that once used N's values now use those in Results instead.
  829. assert(Results.size() == N->getNumValues() &&
  830. "Custom lowering returned the wrong number of results!");
  831. for (unsigned i = 0, e = Results.size(); i != e; ++i) {
  832. ReplaceValueWith(SDValue(N, i), Results[i]);
  833. // Propagate node ordering
  834. DAG.AssignOrdering(Results[i].getNode(), DAG.GetOrdering(N));
  835. }
  836. return true;
  837. }
  838. /// CustomWidenLowerNode - Widen the node's results with custom code provided
  839. /// by the target and return "true", or do nothing and return "false".
  840. bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
  841. // See if the target wants to custom lower this node.
  842. if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
  843. return false;
  844. SmallVector<SDValue, 8> Results;
  845. TLI.ReplaceNodeResults(N, Results, DAG);
  846. if (Results.empty())
  847. // The target didn't want to custom widen lower its result after all.
  848. return false;
  849. // Update the widening map.
  850. assert(Results.size() == N->getNumValues() &&
  851. "Custom lowering returned the wrong number of results!");
  852. for (unsigned i = 0, e = Results.size(); i != e; ++i)
  853. SetWidenedVector(SDValue(N, i), Results[i]);
  854. return true;
  855. }
  856. SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
  857. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
  858. if (i != ResNo)
  859. ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
  860. return SDValue(N->getOperand(ResNo));
  861. }
  862. /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
  863. /// which is split into two not necessarily identical pieces.
  864. void DAGTypeLegalizer::GetSplitDestVTs(EVT InVT, EVT &LoVT, EVT &HiVT) {
  865. // Currently all types are split in half.
  866. if (!InVT.isVector()) {
  867. LoVT = HiVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
  868. } else {
  869. unsigned NumElements = InVT.getVectorNumElements();
  870. assert(!(NumElements & 1) && "Splitting vector, but not in half!");
  871. LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
  872. InVT.getVectorElementType(), NumElements/2);
  873. }
  874. }
  875. /// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
  876. /// high parts of the given value.
  877. void DAGTypeLegalizer::GetPairElements(SDValue Pair,
  878. SDValue &Lo, SDValue &Hi) {
  879. SDLoc dl(Pair);;
  880. EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
  881. Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
  882. DAG.getIntPtrConstant(0));
  883. Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
  884. DAG.getIntPtrConstant(1));
  885. }
  886. SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, EVT EltVT,
  887. SDValue Index) {
  888. SDLoc dl(Index);;
  889. // Make sure the index type is big enough to compute in.
  890. if (Index.getValueType().bitsGT(TLI.getPointerTy()))
  891. Index = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Index);
  892. else
  893. Index = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Index);
  894. // Calculate the element offset and add it to the pointer.
  895. unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
  896. Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
  897. DAG.getConstant(EltSize, Index.getValueType()));
  898. return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
  899. }
  900. /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
  901. SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
  902. // Arbitrarily use dlHi for result SDLoc
  903. SDLoc dlHi(Hi);;
  904. SDLoc dlLo(Lo);;
  905. EVT LVT = Lo.getValueType();
  906. EVT HVT = Hi.getValueType();
  907. EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
  908. LVT.getSizeInBits() + HVT.getSizeInBits());
  909. Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
  910. Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
  911. Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
  912. DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy()));
  913. return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
  914. }
  915. /// LibCallify - Convert the node into a libcall with the same prototype.
  916. SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
  917. bool isSigned) {
  918. unsigned NumOps = N->getNumOperands();
  919. SDLoc dl(N);
  920. if (NumOps == 0) {
  921. return TLI.makeLibCall(DAG, LC, N->getValueType(0), 0, 0, isSigned, dl);
  922. } else if (NumOps == 1) {
  923. SDValue Op = N->getOperand(0);
  924. return TLI.makeLibCall(DAG, LC, N->getValueType(0), &Op, 1, isSigned, dl);
  925. } else if (NumOps == 2) {
  926. SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
  927. return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, 2, isSigned, dl);
  928. }
  929. SmallVector<SDValue, 8> Ops(NumOps);
  930. for (unsigned i = 0; i < NumOps; ++i)
  931. Ops[i] = N->getOperand(i);
  932. return TLI.makeLibCall(DAG, LC, N->getValueType(0),
  933. &Ops[0], NumOps, isSigned, dl);
  934. }
  935. // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
  936. // ExpandLibCall except that the first operand is the in-chain.
  937. std::pair<SDValue, SDValue>
  938. DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC,
  939. SDNode *Node,
  940. bool isSigned) {
  941. SDValue InChain = Node->getOperand(0);
  942. TargetLowering::ArgListTy Args;
  943. TargetLowering::ArgListEntry Entry;
  944. for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
  945. EVT ArgVT = Node->getOperand(i).getValueType();
  946. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  947. Entry.Node = Node->getOperand(i);
  948. Entry.Ty = ArgTy;
  949. Entry.isSExt = isSigned;
  950. Entry.isZExt = !isSigned;
  951. Args.push_back(Entry);
  952. }
  953. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  954. TLI.getPointerTy());
  955. Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
  956. TargetLowering::
  957. CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, false,
  958. 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
  959. /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
  960. Callee, Args, DAG, SDLoc(Node));
  961. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  962. return CallInfo;
  963. }
  964. /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
  965. /// of the given type. A target boolean is an integer value, not necessarily of
  966. /// type i1, the bits of which conform to getBooleanContents.
  967. SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT VT) {
  968. SDLoc dl(Bool);;
  969. ISD::NodeType ExtendCode =
  970. TargetLowering::getExtendForContent(TLI.getBooleanContents(VT.isVector()));
  971. return DAG.getNode(ExtendCode, dl, VT, Bool);
  972. }
  973. /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
  974. /// bits in Hi.
  975. void DAGTypeLegalizer::SplitInteger(SDValue Op,
  976. EVT LoVT, EVT HiVT,
  977. SDValue &Lo, SDValue &Hi) {
  978. SDLoc dl(Op);;
  979. assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
  980. Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
  981. Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
  982. Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
  983. DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy()));
  984. Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
  985. }
  986. /// SplitInteger - Return the lower and upper halves of Op's bits in a value
  987. /// type half the size of Op's.
  988. void DAGTypeLegalizer::SplitInteger(SDValue Op,
  989. SDValue &Lo, SDValue &Hi) {
  990. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(),
  991. Op.getValueType().getSizeInBits()/2);
  992. SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
  993. }
  994. //===----------------------------------------------------------------------===//
  995. // Entry Point
  996. //===----------------------------------------------------------------------===//
  997. /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
  998. /// only uses types natively supported by the target. Returns "true" if it made
  999. /// any changes.
  1000. ///
  1001. /// Note that this is an involved process that may invalidate pointers into
  1002. /// the graph.
  1003. bool SelectionDAG::LegalizeTypes() {
  1004. return DAGTypeLegalizer(*this).run();
  1005. }