~ubuntu-branches/ubuntu/wily/clamav/wily-proposed

« back to all changes in this revision

Viewing changes to libclamav/c++/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp

  • Committer: Package Import Robot
  • Author(s): Scott Kitterman, Sebastian Andrzej Siewior, Andreas Cadhalpun, Scott Kitterman, Javier Fernández-Sanguino
  • Date: 2015-01-28 00:25:13 UTC
  • mfrom: (0.48.14 sid)
  • Revision ID: package-import@ubuntu.com-20150128002513-lil2oi74cooy4lzr
Tags: 0.98.6+dfsg-1
[ Sebastian Andrzej Siewior ]
* update "fix-ssize_t-size_t-off_t-printf-modifier", include of misc.h was
  missing but was pulled in via the systemd patch.
* Don't leak return codes from libmspack to clamav API. (Closes: #774686).

[ Andreas Cadhalpun ]
* Add patch to avoid emitting incremental progress messages when not
  outputting to a terminal. (Closes: #767350)
* Update lintian-overrides for unused-file-paragraph-in-dep5-copyright.
* clamav-base.postinst: always chown /var/log/clamav and /var/lib/clamav
  to clamav:clamav, not only on fresh installations. (Closes: #775400)
* Adapt the clamav-daemon and clamav-freshclam logrotate scripts,
  so that they correctly work under systemd.
* Move the PidFile variable from the clamd/freshclam configuration files
  to the init scripts. This makes the init scripts more robust against
  misconfiguration and avoids error messages with systemd. (Closes: #767353)
* debian/copyright: drop files from Files-Excluded only present in github
  tarballs
* Drop Workaround-a-bug-in-libc-on-Hurd.patch, because hurd got fixed.
  (see #752237)
* debian/rules: Remove useless --with-system-tommath --without-included-ltdl
  configure options.

[ Scott Kitterman ]
* Stop stripping llvm when repacking the tarball as the system llvm on some
  releases is too old to use
* New upstream bugfix release
  - Library shared object revisions.
  - Includes a patch from Sebastian Andrzej Siewior making ClamAV pid files
    compatible with systemd.
  - Fix a heap out of bounds condition with crafted Yoda's crypter files.
    This issue was discovered by Felix Groebert of the Google Security Team.
  - Fix a heap out of bounds condition with crafted mew packer files. This
    issue was discovered by Felix Groebert of the Google Security Team.
  - Fix a heap out of bounds condition with crafted upx packer files. This
    issue was discovered by Kevin Szkudlapski of Quarkslab.
  - Fix a heap out of bounds condition with crafted upack packer files. This
    issue was discovered by Sebastian Andrzej Siewior. CVE-2014-9328.
  - Compensate a crash due to incorrect compiler optimization when handling
    crafted petite packer files. This issue was discovered by Sebastian
    Andrzej Siewior.
* Update lintian override for embedded zlib to match new so version

[ Javier Fernández-Sanguino ]
* Updated Spanish Debconf template translation (Closes: #773563)

Show diffs side-by-side

added added

removed removed

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