~louis/ubuntu/trusty/clamav/lp799623_fix_logrotate

« back to all changes in this revision

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

  • Committer: Bazaar Package Importer
  • Author(s): Scott Kitterman
  • Date: 2010-03-12 11:30:04 UTC
  • mfrom: (0.41.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20100312113004-b0fop4bkycszdd0z
Tags: 0.96~rc1+dfsg-0ubuntu1
* New upstream RC - FFE (LP: #537636):
  - Add OfficialDatabaseOnly option to clamav-base.postinst.in
  - Add LocalSocketGroup option to clamav-base.postinst.in
  - Add LocalSocketMode option to clamav-base.postinst.in
  - Add CrossFilesystems option to clamav-base.postinst.in
  - Add ClamukoScannerCount option to clamav-base.postinst.in
  - Add BytecodeSecurity opiton to clamav-base.postinst.in
  - Add DetectionStatsHostID option to clamav-freshclam.postinst.in
  - Add Bytecode option to clamav-freshclam.postinst.in
  - Add MilterSocketGroup option to clamav-milter.postinst.in
  - Add MilterSocketMode option to clamav-milter.postinst.in
  - Add ReportHostname option to clamav-milter.postinst.in
  - Bump libclamav SO version to 6.1.0 in libclamav6.install
  - Drop clamdmon from clamav.examples (no longer shipped by upstream)
  - Drop libclamav.a from libclamav-dev.install (not built by upstream)
  - Update SO version for lintian override for libclamav6
  - Add new Bytecode Testing Tool, usr/bin/clambc, to clamav.install
  - Add build-depends on python and python-setuptools for new test suite
  - Update debian/copyright for the embedded copy of llvm (using the system
    llvm is not currently feasible)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
//===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
 
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 implements the SelectionDAG class.
 
11
//
 
12
//===----------------------------------------------------------------------===//
 
13
 
 
14
#include "llvm/CodeGen/SelectionDAG.h"
 
15
#include "SDNodeOrdering.h"
 
16
#include "llvm/Constants.h"
 
17
#include "llvm/Analysis/ValueTracking.h"
 
18
#include "llvm/Function.h"
 
19
#include "llvm/GlobalAlias.h"
 
20
#include "llvm/GlobalVariable.h"
 
21
#include "llvm/Intrinsics.h"
 
22
#include "llvm/DerivedTypes.h"
 
23
#include "llvm/Assembly/Writer.h"
 
24
#include "llvm/CallingConv.h"
 
25
#include "llvm/CodeGen/MachineBasicBlock.h"
 
26
#include "llvm/CodeGen/MachineConstantPool.h"
 
27
#include "llvm/CodeGen/MachineFrameInfo.h"
 
28
#include "llvm/CodeGen/MachineModuleInfo.h"
 
29
#include "llvm/CodeGen/PseudoSourceValue.h"
 
30
#include "llvm/Target/TargetRegisterInfo.h"
 
31
#include "llvm/Target/TargetData.h"
 
32
#include "llvm/Target/TargetFrameInfo.h"
 
33
#include "llvm/Target/TargetLowering.h"
 
34
#include "llvm/Target/TargetOptions.h"
 
35
#include "llvm/Target/TargetInstrInfo.h"
 
36
#include "llvm/Target/TargetIntrinsicInfo.h"
 
37
#include "llvm/Target/TargetMachine.h"
 
38
#include "llvm/Support/CommandLine.h"
 
39
#include "llvm/Support/Debug.h"
 
40
#include "llvm/Support/ErrorHandling.h"
 
41
#include "llvm/Support/ManagedStatic.h"
 
42
#include "llvm/Support/MathExtras.h"
 
43
#include "llvm/Support/raw_ostream.h"
 
44
#include "llvm/System/Mutex.h"
 
45
#include "llvm/ADT/SetVector.h"
 
46
#include "llvm/ADT/SmallPtrSet.h"
 
47
#include "llvm/ADT/SmallSet.h"
 
48
#include "llvm/ADT/SmallVector.h"
 
49
#include "llvm/ADT/StringExtras.h"
 
50
#include <algorithm>
 
51
#include <cmath>
 
52
using namespace llvm;
 
53
 
 
54
/// makeVTList - Return an instance of the SDVTList struct initialized with the
 
55
/// specified members.
 
56
static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
 
57
  SDVTList Res = {VTs, NumVTs};
 
58
  return Res;
 
59
}
 
60
 
 
61
static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
 
62
  switch (VT.getSimpleVT().SimpleTy) {
 
63
  default: llvm_unreachable("Unknown FP format");
 
64
  case MVT::f32:     return &APFloat::IEEEsingle;
 
65
  case MVT::f64:     return &APFloat::IEEEdouble;
 
66
  case MVT::f80:     return &APFloat::x87DoubleExtended;
 
67
  case MVT::f128:    return &APFloat::IEEEquad;
 
68
  case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
 
69
  }
 
70
}
 
71
 
 
72
SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
 
73
 
 
74
//===----------------------------------------------------------------------===//
 
75
//                              ConstantFPSDNode Class
 
76
//===----------------------------------------------------------------------===//
 
77
 
 
78
/// isExactlyValue - We don't rely on operator== working on double values, as
 
79
/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
 
80
/// As such, this method can be used to do an exact bit-for-bit comparison of
 
81
/// two floating point values.
 
82
bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
 
83
  return getValueAPF().bitwiseIsEqual(V);
 
84
}
 
85
 
 
86
bool ConstantFPSDNode::isValueValidForType(EVT VT,
 
87
                                           const APFloat& Val) {
 
88
  assert(VT.isFloatingPoint() && "Can only convert between FP types");
 
89
 
 
90
  // PPC long double cannot be converted to any other type.
 
91
  if (VT == MVT::ppcf128 ||
 
92
      &Val.getSemantics() == &APFloat::PPCDoubleDouble)
 
93
    return false;
 
94
 
 
95
  // convert modifies in place, so make a copy.
 
96
  APFloat Val2 = APFloat(Val);
 
97
  bool losesInfo;
 
98
  (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
 
99
                      &losesInfo);
 
100
  return !losesInfo;
 
101
}
 
102
 
 
103
//===----------------------------------------------------------------------===//
 
104
//                              ISD Namespace
 
105
//===----------------------------------------------------------------------===//
 
106
 
 
107
/// isBuildVectorAllOnes - Return true if the specified node is a
 
108
/// BUILD_VECTOR where all of the elements are ~0 or undef.
 
109
bool ISD::isBuildVectorAllOnes(const SDNode *N) {
 
110
  // Look through a bit convert.
 
111
  if (N->getOpcode() == ISD::BIT_CONVERT)
 
112
    N = N->getOperand(0).getNode();
 
113
 
 
114
  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
 
115
 
 
116
  unsigned i = 0, e = N->getNumOperands();
 
117
 
 
118
  // Skip over all of the undef values.
 
119
  while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
 
120
    ++i;
 
121
 
 
122
  // Do not accept an all-undef vector.
 
123
  if (i == e) return false;
 
124
 
 
125
  // Do not accept build_vectors that aren't all constants or which have non-~0
 
126
  // elements.
 
127
  SDValue NotZero = N->getOperand(i);
 
128
  if (isa<ConstantSDNode>(NotZero)) {
 
129
    if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
 
130
      return false;
 
131
  } else if (isa<ConstantFPSDNode>(NotZero)) {
 
132
    if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
 
133
                bitcastToAPInt().isAllOnesValue())
 
134
      return false;
 
135
  } else
 
136
    return false;
 
137
 
 
138
  // Okay, we have at least one ~0 value, check to see if the rest match or are
 
139
  // undefs.
 
140
  for (++i; i != e; ++i)
 
141
    if (N->getOperand(i) != NotZero &&
 
142
        N->getOperand(i).getOpcode() != ISD::UNDEF)
 
143
      return false;
 
144
  return true;
 
145
}
 
146
 
 
147
 
 
148
/// isBuildVectorAllZeros - Return true if the specified node is a
 
149
/// BUILD_VECTOR where all of the elements are 0 or undef.
 
150
bool ISD::isBuildVectorAllZeros(const SDNode *N) {
 
151
  // Look through a bit convert.
 
152
  if (N->getOpcode() == ISD::BIT_CONVERT)
 
153
    N = N->getOperand(0).getNode();
 
154
 
 
155
  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
 
156
 
 
157
  unsigned i = 0, e = N->getNumOperands();
 
158
 
 
159
  // Skip over all of the undef values.
 
160
  while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
 
161
    ++i;
 
162
 
 
163
  // Do not accept an all-undef vector.
 
164
  if (i == e) return false;
 
165
 
 
166
  // Do not accept build_vectors that aren't all constants or which have non-0
 
167
  // elements.
 
168
  SDValue Zero = N->getOperand(i);
 
169
  if (isa<ConstantSDNode>(Zero)) {
 
170
    if (!cast<ConstantSDNode>(Zero)->isNullValue())
 
171
      return false;
 
172
  } else if (isa<ConstantFPSDNode>(Zero)) {
 
173
    if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
 
174
      return false;
 
175
  } else
 
176
    return false;
 
177
 
 
178
  // Okay, we have at least one 0 value, check to see if the rest match or are
 
179
  // undefs.
 
180
  for (++i; i != e; ++i)
 
181
    if (N->getOperand(i) != Zero &&
 
182
        N->getOperand(i).getOpcode() != ISD::UNDEF)
 
183
      return false;
 
184
  return true;
 
185
}
 
186
 
 
187
/// isScalarToVector - Return true if the specified node is a
 
188
/// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
 
189
/// element is not an undef.
 
190
bool ISD::isScalarToVector(const SDNode *N) {
 
191
  if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
 
192
    return true;
 
193
 
 
194
  if (N->getOpcode() != ISD::BUILD_VECTOR)
 
195
    return false;
 
196
  if (N->getOperand(0).getOpcode() == ISD::UNDEF)
 
197
    return false;
 
198
  unsigned NumElems = N->getNumOperands();
 
199
  for (unsigned i = 1; i < NumElems; ++i) {
 
200
    SDValue V = N->getOperand(i);
 
201
    if (V.getOpcode() != ISD::UNDEF)
 
202
      return false;
 
203
  }
 
204
  return true;
 
205
}
 
206
 
 
207
/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
 
208
/// when given the operation for (X op Y).
 
209
ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
 
210
  // To perform this operation, we just need to swap the L and G bits of the
 
211
  // operation.
 
212
  unsigned OldL = (Operation >> 2) & 1;
 
213
  unsigned OldG = (Operation >> 1) & 1;
 
214
  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
 
215
                       (OldL << 1) |       // New G bit
 
216
                       (OldG << 2));       // New L bit.
 
217
}
 
218
 
 
219
/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
 
220
/// 'op' is a valid SetCC operation.
 
221
ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
 
222
  unsigned Operation = Op;
 
223
  if (isInteger)
 
224
    Operation ^= 7;   // Flip L, G, E bits, but not U.
 
225
  else
 
226
    Operation ^= 15;  // Flip all of the condition bits.
 
227
 
 
228
  if (Operation > ISD::SETTRUE2)
 
229
    Operation &= ~8;  // Don't let N and U bits get set.
 
230
 
 
231
  return ISD::CondCode(Operation);
 
232
}
 
233
 
 
234
 
 
235
/// isSignedOp - For an integer comparison, return 1 if the comparison is a
 
236
/// signed operation and 2 if the result is an unsigned comparison.  Return zero
 
237
/// if the operation does not depend on the sign of the input (setne and seteq).
 
238
static int isSignedOp(ISD::CondCode Opcode) {
 
239
  switch (Opcode) {
 
240
  default: llvm_unreachable("Illegal integer setcc operation!");
 
241
  case ISD::SETEQ:
 
242
  case ISD::SETNE: return 0;
 
243
  case ISD::SETLT:
 
244
  case ISD::SETLE:
 
245
  case ISD::SETGT:
 
246
  case ISD::SETGE: return 1;
 
247
  case ISD::SETULT:
 
248
  case ISD::SETULE:
 
249
  case ISD::SETUGT:
 
250
  case ISD::SETUGE: return 2;
 
251
  }
 
252
}
 
253
 
 
254
/// getSetCCOrOperation - Return the result of a logical OR between different
 
255
/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
 
256
/// returns SETCC_INVALID if it is not possible to represent the resultant
 
257
/// comparison.
 
258
ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
 
259
                                       bool isInteger) {
 
260
  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
 
261
    // Cannot fold a signed integer setcc with an unsigned integer setcc.
 
262
    return ISD::SETCC_INVALID;
 
263
 
 
264
  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
 
265
 
 
266
  // If the N and U bits get set then the resultant comparison DOES suddenly
 
267
  // care about orderedness, and is true when ordered.
 
268
  if (Op > ISD::SETTRUE2)
 
269
    Op &= ~16;     // Clear the U bit if the N bit is set.
 
270
 
 
271
  // Canonicalize illegal integer setcc's.
 
272
  if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
 
273
    Op = ISD::SETNE;
 
274
 
 
275
  return ISD::CondCode(Op);
 
276
}
 
277
 
 
278
/// getSetCCAndOperation - Return the result of a logical AND between different
 
279
/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
 
280
/// function returns zero if it is not possible to represent the resultant
 
281
/// comparison.
 
282
ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
 
283
                                        bool isInteger) {
 
284
  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
 
285
    // Cannot fold a signed setcc with an unsigned setcc.
 
286
    return ISD::SETCC_INVALID;
 
287
 
 
288
  // Combine all of the condition bits.
 
289
  ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
 
290
 
 
291
  // Canonicalize illegal integer setcc's.
 
292
  if (isInteger) {
 
293
    switch (Result) {
 
294
    default: break;
 
295
    case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
 
296
    case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
 
297
    case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
 
298
    case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
 
299
    case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
 
300
    }
 
301
  }
 
302
 
 
303
  return Result;
 
304
}
 
305
 
 
306
const TargetMachine &SelectionDAG::getTarget() const {
 
307
  return MF->getTarget();
 
308
}
 
309
 
 
310
//===----------------------------------------------------------------------===//
 
311
//                           SDNode Profile Support
 
312
//===----------------------------------------------------------------------===//
 
313
 
 
314
/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
 
315
///
 
316
static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
 
317
  ID.AddInteger(OpC);
 
318
}
 
319
 
 
320
/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
 
321
/// solely with their pointer.
 
322
static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
 
323
  ID.AddPointer(VTList.VTs);
 
324
}
 
325
 
 
326
/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
 
327
///
 
328
static void AddNodeIDOperands(FoldingSetNodeID &ID,
 
329
                              const SDValue *Ops, unsigned NumOps) {
 
330
  for (; NumOps; --NumOps, ++Ops) {
 
331
    ID.AddPointer(Ops->getNode());
 
332
    ID.AddInteger(Ops->getResNo());
 
333
  }
 
334
}
 
335
 
 
336
/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
 
337
///
 
338
static void AddNodeIDOperands(FoldingSetNodeID &ID,
 
339
                              const SDUse *Ops, unsigned NumOps) {
 
340
  for (; NumOps; --NumOps, ++Ops) {
 
341
    ID.AddPointer(Ops->getNode());
 
342
    ID.AddInteger(Ops->getResNo());
 
343
  }
 
344
}
 
345
 
 
346
static void AddNodeIDNode(FoldingSetNodeID &ID,
 
347
                          unsigned short OpC, SDVTList VTList,
 
348
                          const SDValue *OpList, unsigned N) {
 
349
  AddNodeIDOpcode(ID, OpC);
 
350
  AddNodeIDValueTypes(ID, VTList);
 
351
  AddNodeIDOperands(ID, OpList, N);
 
352
}
 
353
 
 
354
/// AddNodeIDCustom - If this is an SDNode with special info, add this info to
 
355
/// the NodeID data.
 
356
static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
 
357
  switch (N->getOpcode()) {
 
358
  case ISD::TargetExternalSymbol:
 
359
  case ISD::ExternalSymbol:
 
360
    llvm_unreachable("Should only be used on nodes with operands");
 
361
  default: break;  // Normal nodes don't need extra info.
 
362
  case ISD::TargetConstant:
 
363
  case ISD::Constant:
 
364
    ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
 
365
    break;
 
366
  case ISD::TargetConstantFP:
 
367
  case ISD::ConstantFP: {
 
368
    ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
 
369
    break;
 
370
  }
 
371
  case ISD::TargetGlobalAddress:
 
372
  case ISD::GlobalAddress:
 
373
  case ISD::TargetGlobalTLSAddress:
 
374
  case ISD::GlobalTLSAddress: {
 
375
    const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
 
376
    ID.AddPointer(GA->getGlobal());
 
377
    ID.AddInteger(GA->getOffset());
 
378
    ID.AddInteger(GA->getTargetFlags());
 
379
    break;
 
380
  }
 
381
  case ISD::BasicBlock:
 
382
    ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
 
383
    break;
 
384
  case ISD::Register:
 
385
    ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
 
386
    break;
 
387
 
 
388
  case ISD::SRCVALUE:
 
389
    ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
 
390
    break;
 
391
  case ISD::FrameIndex:
 
392
  case ISD::TargetFrameIndex:
 
393
    ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
 
394
    break;
 
395
  case ISD::JumpTable:
 
396
  case ISD::TargetJumpTable:
 
397
    ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
 
398
    ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
 
399
    break;
 
400
  case ISD::ConstantPool:
 
401
  case ISD::TargetConstantPool: {
 
402
    const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
 
403
    ID.AddInteger(CP->getAlignment());
 
404
    ID.AddInteger(CP->getOffset());
 
405
    if (CP->isMachineConstantPoolEntry())
 
406
      CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
 
407
    else
 
408
      ID.AddPointer(CP->getConstVal());
 
409
    ID.AddInteger(CP->getTargetFlags());
 
410
    break;
 
411
  }
 
412
  case ISD::LOAD: {
 
413
    const LoadSDNode *LD = cast<LoadSDNode>(N);
 
414
    ID.AddInteger(LD->getMemoryVT().getRawBits());
 
415
    ID.AddInteger(LD->getRawSubclassData());
 
416
    break;
 
417
  }
 
418
  case ISD::STORE: {
 
419
    const StoreSDNode *ST = cast<StoreSDNode>(N);
 
420
    ID.AddInteger(ST->getMemoryVT().getRawBits());
 
421
    ID.AddInteger(ST->getRawSubclassData());
 
422
    break;
 
423
  }
 
424
  case ISD::ATOMIC_CMP_SWAP:
 
425
  case ISD::ATOMIC_SWAP:
 
426
  case ISD::ATOMIC_LOAD_ADD:
 
427
  case ISD::ATOMIC_LOAD_SUB:
 
428
  case ISD::ATOMIC_LOAD_AND:
 
429
  case ISD::ATOMIC_LOAD_OR:
 
430
  case ISD::ATOMIC_LOAD_XOR:
 
431
  case ISD::ATOMIC_LOAD_NAND:
 
432
  case ISD::ATOMIC_LOAD_MIN:
 
433
  case ISD::ATOMIC_LOAD_MAX:
 
434
  case ISD::ATOMIC_LOAD_UMIN:
 
435
  case ISD::ATOMIC_LOAD_UMAX: {
 
436
    const AtomicSDNode *AT = cast<AtomicSDNode>(N);
 
437
    ID.AddInteger(AT->getMemoryVT().getRawBits());
 
438
    ID.AddInteger(AT->getRawSubclassData());
 
439
    break;
 
440
  }
 
441
  case ISD::VECTOR_SHUFFLE: {
 
442
    const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
 
443
    for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
 
444
         i != e; ++i)
 
445
      ID.AddInteger(SVN->getMaskElt(i));
 
446
    break;
 
447
  }
 
448
  case ISD::TargetBlockAddress:
 
449
  case ISD::BlockAddress: {
 
450
    ID.AddPointer(cast<BlockAddressSDNode>(N)->getBlockAddress());
 
451
    ID.AddInteger(cast<BlockAddressSDNode>(N)->getTargetFlags());
 
452
    break;
 
453
  }
 
454
  } // end switch (N->getOpcode())
 
455
}
 
456
 
 
457
/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
 
458
/// data.
 
459
static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
 
460
  AddNodeIDOpcode(ID, N->getOpcode());
 
461
  // Add the return value info.
 
462
  AddNodeIDValueTypes(ID, N->getVTList());
 
463
  // Add the operand info.
 
464
  AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
 
465
 
 
466
  // Handle SDNode leafs with special info.
 
467
  AddNodeIDCustom(ID, N);
 
468
}
 
469
 
 
470
/// encodeMemSDNodeFlags - Generic routine for computing a value for use in
 
471
/// the CSE map that carries volatility, temporalness, indexing mode, and
 
472
/// extension/truncation information.
 
473
///
 
474
static inline unsigned
 
475
encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
 
476
                     bool isNonTemporal) {
 
477
  assert((ConvType & 3) == ConvType &&
 
478
         "ConvType may not require more than 2 bits!");
 
479
  assert((AM & 7) == AM &&
 
480
         "AM may not require more than 3 bits!");
 
481
  return ConvType |
 
482
         (AM << 2) |
 
483
         (isVolatile << 5) |
 
484
         (isNonTemporal << 6);
 
485
}
 
486
 
 
487
//===----------------------------------------------------------------------===//
 
488
//                              SelectionDAG Class
 
489
//===----------------------------------------------------------------------===//
 
490
 
 
491
/// doNotCSE - Return true if CSE should not be performed for this node.
 
492
static bool doNotCSE(SDNode *N) {
 
493
  if (N->getValueType(0) == MVT::Flag)
 
494
    return true; // Never CSE anything that produces a flag.
 
495
 
 
496
  switch (N->getOpcode()) {
 
497
  default: break;
 
498
  case ISD::HANDLENODE:
 
499
  case ISD::EH_LABEL:
 
500
    return true;   // Never CSE these nodes.
 
501
  }
 
502
 
 
503
  // Check that remaining values produced are not flags.
 
504
  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
 
505
    if (N->getValueType(i) == MVT::Flag)
 
506
      return true; // Never CSE anything that produces a flag.
 
507
 
 
508
  return false;
 
509
}
 
510
 
 
511
/// RemoveDeadNodes - This method deletes all unreachable nodes in the
 
512
/// SelectionDAG.
 
513
void SelectionDAG::RemoveDeadNodes() {
 
514
  // Create a dummy node (which is not added to allnodes), that adds a reference
 
515
  // to the root node, preventing it from being deleted.
 
516
  HandleSDNode Dummy(getRoot());
 
517
 
 
518
  SmallVector<SDNode*, 128> DeadNodes;
 
519
 
 
520
  // Add all obviously-dead nodes to the DeadNodes worklist.
 
521
  for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
 
522
    if (I->use_empty())
 
523
      DeadNodes.push_back(I);
 
524
 
 
525
  RemoveDeadNodes(DeadNodes);
 
526
 
 
527
  // If the root changed (e.g. it was a dead load, update the root).
 
528
  setRoot(Dummy.getValue());
 
529
}
 
530
 
 
531
/// RemoveDeadNodes - This method deletes the unreachable nodes in the
 
532
/// given list, and any nodes that become unreachable as a result.
 
533
void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
 
534
                                   DAGUpdateListener *UpdateListener) {
 
535
 
 
536
  // Process the worklist, deleting the nodes and adding their uses to the
 
537
  // worklist.
 
538
  while (!DeadNodes.empty()) {
 
539
    SDNode *N = DeadNodes.pop_back_val();
 
540
 
 
541
    if (UpdateListener)
 
542
      UpdateListener->NodeDeleted(N, 0);
 
543
 
 
544
    // Take the node out of the appropriate CSE map.
 
545
    RemoveNodeFromCSEMaps(N);
 
546
 
 
547
    // Next, brutally remove the operand list.  This is safe to do, as there are
 
548
    // no cycles in the graph.
 
549
    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
 
550
      SDUse &Use = *I++;
 
551
      SDNode *Operand = Use.getNode();
 
552
      Use.set(SDValue());
 
553
 
 
554
      // Now that we removed this operand, see if there are no uses of it left.
 
555
      if (Operand->use_empty())
 
556
        DeadNodes.push_back(Operand);
 
557
    }
 
558
 
 
559
    DeallocateNode(N);
 
560
  }
 
561
}
 
562
 
 
563
void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
 
564
  SmallVector<SDNode*, 16> DeadNodes(1, N);
 
565
  RemoveDeadNodes(DeadNodes, UpdateListener);
 
566
}
 
567
 
 
568
void SelectionDAG::DeleteNode(SDNode *N) {
 
569
  // First take this out of the appropriate CSE map.
 
570
  RemoveNodeFromCSEMaps(N);
 
571
 
 
572
  // Finally, remove uses due to operands of this node, remove from the
 
573
  // AllNodes list, and delete the node.
 
574
  DeleteNodeNotInCSEMaps(N);
 
575
}
 
576
 
 
577
void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
 
578
  assert(N != AllNodes.begin() && "Cannot delete the entry node!");
 
579
  assert(N->use_empty() && "Cannot delete a node that is not dead!");
 
580
 
 
581
  // Drop all of the operands and decrement used node's use counts.
 
582
  N->DropOperands();
 
583
 
 
584
  DeallocateNode(N);
 
585
}
 
586
 
 
587
void SelectionDAG::DeallocateNode(SDNode *N) {
 
588
  if (N->OperandsNeedDelete)
 
589
    delete[] N->OperandList;
 
590
 
 
591
  // Set the opcode to DELETED_NODE to help catch bugs when node
 
592
  // memory is reallocated.
 
593
  N->NodeType = ISD::DELETED_NODE;
 
594
 
 
595
  NodeAllocator.Deallocate(AllNodes.remove(N));
 
596
 
 
597
  // Remove the ordering of this node.
 
598
  Ordering->remove(N);
 
599
}
 
600
 
 
601
/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
 
602
/// correspond to it.  This is useful when we're about to delete or repurpose
 
603
/// the node.  We don't want future request for structurally identical nodes
 
604
/// to return N anymore.
 
605
bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
 
606
  bool Erased = false;
 
607
  switch (N->getOpcode()) {
 
608
  case ISD::EntryToken:
 
609
    llvm_unreachable("EntryToken should not be in CSEMaps!");
 
610
    return false;
 
611
  case ISD::HANDLENODE: return false;  // noop.
 
612
  case ISD::CONDCODE:
 
613
    assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
 
614
           "Cond code doesn't exist!");
 
615
    Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
 
616
    CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
 
617
    break;
 
618
  case ISD::ExternalSymbol:
 
619
    Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
 
620
    break;
 
621
  case ISD::TargetExternalSymbol: {
 
622
    ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
 
623
    Erased = TargetExternalSymbols.erase(
 
624
               std::pair<std::string,unsigned char>(ESN->getSymbol(),
 
625
                                                    ESN->getTargetFlags()));
 
626
    break;
 
627
  }
 
628
  case ISD::VALUETYPE: {
 
629
    EVT VT = cast<VTSDNode>(N)->getVT();
 
630
    if (VT.isExtended()) {
 
631
      Erased = ExtendedValueTypeNodes.erase(VT);
 
632
    } else {
 
633
      Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
 
634
      ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
 
635
    }
 
636
    break;
 
637
  }
 
638
  default:
 
639
    // Remove it from the CSE Map.
 
640
    Erased = CSEMap.RemoveNode(N);
 
641
    break;
 
642
  }
 
643
#ifndef NDEBUG
 
644
  // Verify that the node was actually in one of the CSE maps, unless it has a
 
645
  // flag result (which cannot be CSE'd) or is one of the special cases that are
 
646
  // not subject to CSE.
 
647
  if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
 
648
      !N->isMachineOpcode() && !doNotCSE(N)) {
 
649
    N->dump(this);
 
650
    dbgs() << "\n";
 
651
    llvm_unreachable("Node is not in map!");
 
652
  }
 
653
#endif
 
654
  return Erased;
 
655
}
 
656
 
 
657
/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
 
658
/// maps and modified in place. Add it back to the CSE maps, unless an identical
 
659
/// node already exists, in which case transfer all its users to the existing
 
660
/// node. This transfer can potentially trigger recursive merging.
 
661
///
 
662
void
 
663
SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
 
664
                                       DAGUpdateListener *UpdateListener) {
 
665
  // For node types that aren't CSE'd, just act as if no identical node
 
666
  // already exists.
 
667
  if (!doNotCSE(N)) {
 
668
    SDNode *Existing = CSEMap.GetOrInsertNode(N);
 
669
    if (Existing != N) {
 
670
      // If there was already an existing matching node, use ReplaceAllUsesWith
 
671
      // to replace the dead one with the existing one.  This can cause
 
672
      // recursive merging of other unrelated nodes down the line.
 
673
      ReplaceAllUsesWith(N, Existing, UpdateListener);
 
674
 
 
675
      // N is now dead.  Inform the listener if it exists and delete it.
 
676
      if (UpdateListener)
 
677
        UpdateListener->NodeDeleted(N, Existing);
 
678
      DeleteNodeNotInCSEMaps(N);
 
679
      return;
 
680
    }
 
681
  }
 
682
 
 
683
  // If the node doesn't already exist, we updated it.  Inform a listener if
 
684
  // it exists.
 
685
  if (UpdateListener)
 
686
    UpdateListener->NodeUpdated(N);
 
687
}
 
688
 
 
689
/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
 
690
/// were replaced with those specified.  If this node is never memoized,
 
691
/// return null, otherwise return a pointer to the slot it would take.  If a
 
692
/// node already exists with these operands, the slot will be non-null.
 
693
SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
 
694
                                           void *&InsertPos) {
 
695
  if (doNotCSE(N))
 
696
    return 0;
 
697
 
 
698
  SDValue Ops[] = { Op };
 
699
  FoldingSetNodeID ID;
 
700
  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
 
701
  AddNodeIDCustom(ID, N);
 
702
  SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
 
703
  return Node;
 
704
}
 
705
 
 
706
/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
 
707
/// were replaced with those specified.  If this node is never memoized,
 
708
/// return null, otherwise return a pointer to the slot it would take.  If a
 
709
/// node already exists with these operands, the slot will be non-null.
 
710
SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
 
711
                                           SDValue Op1, SDValue Op2,
 
712
                                           void *&InsertPos) {
 
713
  if (doNotCSE(N))
 
714
    return 0;
 
715
 
 
716
  SDValue Ops[] = { Op1, Op2 };
 
717
  FoldingSetNodeID ID;
 
718
  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
 
719
  AddNodeIDCustom(ID, N);
 
720
  SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
 
721
  return Node;
 
722
}
 
723
 
 
724
 
 
725
/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
 
726
/// were replaced with those specified.  If this node is never memoized,
 
727
/// return null, otherwise return a pointer to the slot it would take.  If a
 
728
/// node already exists with these operands, the slot will be non-null.
 
729
SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
 
730
                                           const SDValue *Ops,unsigned NumOps,
 
731
                                           void *&InsertPos) {
 
732
  if (doNotCSE(N))
 
733
    return 0;
 
734
 
 
735
  FoldingSetNodeID ID;
 
736
  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
 
737
  AddNodeIDCustom(ID, N);
 
738
  SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
 
739
  return Node;
 
740
}
 
741
 
 
742
/// VerifyNode - Sanity check the given node.  Aborts if it is invalid.
 
743
void SelectionDAG::VerifyNode(SDNode *N) {
 
744
  switch (N->getOpcode()) {
 
745
  default:
 
746
    break;
 
747
  case ISD::BUILD_PAIR: {
 
748
    EVT VT = N->getValueType(0);
 
749
    assert(N->getNumValues() == 1 && "Too many results!");
 
750
    assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
 
751
           "Wrong return type!");
 
752
    assert(N->getNumOperands() == 2 && "Wrong number of operands!");
 
753
    assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
 
754
           "Mismatched operand types!");
 
755
    assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
 
756
           "Wrong operand type!");
 
757
    assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
 
758
           "Wrong return type size");
 
759
    break;
 
760
  }
 
761
  case ISD::BUILD_VECTOR: {
 
762
    assert(N->getNumValues() == 1 && "Too many results!");
 
763
    assert(N->getValueType(0).isVector() && "Wrong return type!");
 
764
    assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
 
765
           "Wrong number of operands!");
 
766
    EVT EltVT = N->getValueType(0).getVectorElementType();
 
767
    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
 
768
      assert((I->getValueType() == EltVT ||
 
769
             (EltVT.isInteger() && I->getValueType().isInteger() &&
 
770
              EltVT.bitsLE(I->getValueType()))) &&
 
771
            "Wrong operand type!");
 
772
    break;
 
773
  }
 
774
  }
 
775
}
 
776
 
 
777
/// getEVTAlignment - Compute the default alignment value for the
 
778
/// given type.
 
779
///
 
780
unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
 
781
  const Type *Ty = VT == MVT::iPTR ?
 
782
                   PointerType::get(Type::getInt8Ty(*getContext()), 0) :
 
783
                   VT.getTypeForEVT(*getContext());
 
784
 
 
785
  return TLI.getTargetData()->getABITypeAlignment(Ty);
 
786
}
 
787
 
 
788
// EntryNode could meaningfully have debug info if we can find it...
 
789
SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
 
790
  : TLI(tli), FLI(fli), DW(0),
 
791
    EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
 
792
              getVTList(MVT::Other)),
 
793
    Root(getEntryNode()), Ordering(0) {
 
794
  AllNodes.push_back(&EntryNode);
 
795
  Ordering = new SDNodeOrdering();
 
796
}
 
797
 
 
798
void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
 
799
                        DwarfWriter *dw) {
 
800
  MF = &mf;
 
801
  MMI = mmi;
 
802
  DW = dw;
 
803
  Context = &mf.getFunction()->getContext();
 
804
}
 
805
 
 
806
SelectionDAG::~SelectionDAG() {
 
807
  allnodes_clear();
 
808
  delete Ordering;
 
809
}
 
810
 
 
811
void SelectionDAG::allnodes_clear() {
 
812
  assert(&*AllNodes.begin() == &EntryNode);
 
813
  AllNodes.remove(AllNodes.begin());
 
814
  while (!AllNodes.empty())
 
815
    DeallocateNode(AllNodes.begin());
 
816
}
 
817
 
 
818
void SelectionDAG::clear() {
 
819
  allnodes_clear();
 
820
  OperandAllocator.Reset();
 
821
  CSEMap.clear();
 
822
 
 
823
  ExtendedValueTypeNodes.clear();
 
824
  ExternalSymbols.clear();
 
825
  TargetExternalSymbols.clear();
 
826
  std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
 
827
            static_cast<CondCodeSDNode*>(0));
 
828
  std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
 
829
            static_cast<SDNode*>(0));
 
830
 
 
831
  EntryNode.UseList = 0;
 
832
  AllNodes.push_back(&EntryNode);
 
833
  Root = getEntryNode();
 
834
  delete Ordering;
 
835
  Ordering = new SDNodeOrdering();
 
836
}
 
837
 
 
838
SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
 
839
  return VT.bitsGT(Op.getValueType()) ?
 
840
    getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
 
841
    getNode(ISD::TRUNCATE, DL, VT, Op);
 
842
}
 
843
 
 
844
SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
 
845
  return VT.bitsGT(Op.getValueType()) ?
 
846
    getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
 
847
    getNode(ISD::TRUNCATE, DL, VT, Op);
 
848
}
 
849
 
 
850
SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
 
851
  assert(!VT.isVector() &&
 
852
         "getZeroExtendInReg should use the vector element type instead of "
 
853
         "the vector type!");
 
854
  if (Op.getValueType() == VT) return Op;
 
855
  unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
 
856
  APInt Imm = APInt::getLowBitsSet(BitWidth,
 
857
                                   VT.getSizeInBits());
 
858
  return getNode(ISD::AND, DL, Op.getValueType(), Op,
 
859
                 getConstant(Imm, Op.getValueType()));
 
860
}
 
861
 
 
862
/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
 
863
///
 
864
SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
 
865
  EVT EltVT = VT.getScalarType();
 
866
  SDValue NegOne =
 
867
    getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
 
868
  return getNode(ISD::XOR, DL, VT, Val, NegOne);
 
869
}
 
870
 
 
871
SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
 
872
  EVT EltVT = VT.getScalarType();
 
873
  assert((EltVT.getSizeInBits() >= 64 ||
 
874
         (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
 
875
         "getConstant with a uint64_t value that doesn't fit in the type!");
 
876
  return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
 
877
}
 
878
 
 
879
SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
 
880
  return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
 
881
}
 
882
 
 
883
SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
 
884
  assert(VT.isInteger() && "Cannot create FP integer constant!");
 
885
 
 
886
  EVT EltVT = VT.getScalarType();
 
887
  assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
 
888
         "APInt size does not match type size!");
 
889
 
 
890
  unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
 
891
  FoldingSetNodeID ID;
 
892
  AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
 
893
  ID.AddPointer(&Val);
 
894
  void *IP = 0;
 
895
  SDNode *N = NULL;
 
896
  if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
 
897
    if (!VT.isVector())
 
898
      return SDValue(N, 0);
 
899
 
 
900
  if (!N) {
 
901
    N = NodeAllocator.Allocate<ConstantSDNode>();
 
902
    new (N) ConstantSDNode(isT, &Val, EltVT);
 
903
    CSEMap.InsertNode(N, IP);
 
904
    AllNodes.push_back(N);
 
905
  }
 
906
 
 
907
  SDValue Result(N, 0);
 
908
  if (VT.isVector()) {
 
909
    SmallVector<SDValue, 8> Ops;
 
910
    Ops.assign(VT.getVectorNumElements(), Result);
 
911
    Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
 
912
                     VT, &Ops[0], Ops.size());
 
913
  }
 
914
  return Result;
 
915
}
 
916
 
 
917
SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
 
918
  return getConstant(Val, TLI.getPointerTy(), isTarget);
 
919
}
 
920
 
 
921
 
 
922
SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
 
923
  return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
 
924
}
 
925
 
 
926
SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
 
927
  assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
 
928
 
 
929
  EVT EltVT = VT.getScalarType();
 
930
 
 
931
  // Do the map lookup using the actual bit pattern for the floating point
 
932
  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
 
933
  // we don't have issues with SNANs.
 
934
  unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
 
935
  FoldingSetNodeID ID;
 
936
  AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
 
937
  ID.AddPointer(&V);
 
938
  void *IP = 0;
 
939
  SDNode *N = NULL;
 
940
  if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
 
941
    if (!VT.isVector())
 
942
      return SDValue(N, 0);
 
943
 
 
944
  if (!N) {
 
945
    N = NodeAllocator.Allocate<ConstantFPSDNode>();
 
946
    new (N) ConstantFPSDNode(isTarget, &V, EltVT);
 
947
    CSEMap.InsertNode(N, IP);
 
948
    AllNodes.push_back(N);
 
949
  }
 
950
 
 
951
  SDValue Result(N, 0);
 
952
  if (VT.isVector()) {
 
953
    SmallVector<SDValue, 8> Ops;
 
954
    Ops.assign(VT.getVectorNumElements(), Result);
 
955
    // FIXME DebugLoc info might be appropriate here
 
956
    Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
 
957
                     VT, &Ops[0], Ops.size());
 
958
  }
 
959
  return Result;
 
960
}
 
961
 
 
962
SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
 
963
  EVT EltVT = VT.getScalarType();
 
964
  if (EltVT==MVT::f32)
 
965
    return getConstantFP(APFloat((float)Val), VT, isTarget);
 
966
  else
 
967
    return getConstantFP(APFloat(Val), VT, isTarget);
 
968
}
 
969
 
 
970
SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
 
971
                                       EVT VT, int64_t Offset,
 
972
                                       bool isTargetGA,
 
973
                                       unsigned char TargetFlags) {
 
974
  assert((TargetFlags == 0 || isTargetGA) &&
 
975
         "Cannot set target flags on target-independent globals");
 
976
 
 
977
  // Truncate (with sign-extension) the offset value to the pointer size.
 
978
  EVT PTy = TLI.getPointerTy();
 
979
  unsigned BitWidth = PTy.getSizeInBits();
 
980
  if (BitWidth < 64)
 
981
    Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
 
982
 
 
983
  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
 
984
  if (!GVar) {
 
985
    // If GV is an alias then use the aliasee for determining thread-localness.
 
986
    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
 
987
      GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
 
988
  }
 
989
 
 
990
  unsigned Opc;
 
991
  if (GVar && GVar->isThreadLocal())
 
992
    Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
 
993
  else
 
994
    Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
 
995
 
 
996
  FoldingSetNodeID ID;
 
997
  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
 
998
  ID.AddPointer(GV);
 
999
  ID.AddInteger(Offset);
 
1000
  ID.AddInteger(TargetFlags);
 
1001
  void *IP = 0;
 
1002
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1003
    return SDValue(E, 0);
 
1004
 
 
1005
  SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
 
1006
  new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
 
1007
  CSEMap.InsertNode(N, IP);
 
1008
  AllNodes.push_back(N);
 
1009
  return SDValue(N, 0);
 
1010
}
 
1011
 
 
1012
SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
 
1013
  unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
 
1014
  FoldingSetNodeID ID;
 
1015
  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
 
1016
  ID.AddInteger(FI);
 
1017
  void *IP = 0;
 
1018
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1019
    return SDValue(E, 0);
 
1020
 
 
1021
  SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
 
1022
  new (N) FrameIndexSDNode(FI, VT, isTarget);
 
1023
  CSEMap.InsertNode(N, IP);
 
1024
  AllNodes.push_back(N);
 
1025
  return SDValue(N, 0);
 
1026
}
 
1027
 
 
1028
SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
 
1029
                                   unsigned char TargetFlags) {
 
1030
  assert((TargetFlags == 0 || isTarget) &&
 
1031
         "Cannot set target flags on target-independent jump tables");
 
1032
  unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
 
1033
  FoldingSetNodeID ID;
 
1034
  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
 
1035
  ID.AddInteger(JTI);
 
1036
  ID.AddInteger(TargetFlags);
 
1037
  void *IP = 0;
 
1038
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1039
    return SDValue(E, 0);
 
1040
 
 
1041
  SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
 
1042
  new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
 
1043
  CSEMap.InsertNode(N, IP);
 
1044
  AllNodes.push_back(N);
 
1045
  return SDValue(N, 0);
 
1046
}
 
1047
 
 
1048
SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
 
1049
                                      unsigned Alignment, int Offset,
 
1050
                                      bool isTarget,
 
1051
                                      unsigned char TargetFlags) {
 
1052
  assert((TargetFlags == 0 || isTarget) &&
 
1053
         "Cannot set target flags on target-independent globals");
 
1054
  if (Alignment == 0)
 
1055
    Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
 
1056
  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
 
1057
  FoldingSetNodeID ID;
 
1058
  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
 
1059
  ID.AddInteger(Alignment);
 
1060
  ID.AddInteger(Offset);
 
1061
  ID.AddPointer(C);
 
1062
  ID.AddInteger(TargetFlags);
 
1063
  void *IP = 0;
 
1064
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1065
    return SDValue(E, 0);
 
1066
 
 
1067
  SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
 
1068
  new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
 
1069
  CSEMap.InsertNode(N, IP);
 
1070
  AllNodes.push_back(N);
 
1071
  return SDValue(N, 0);
 
1072
}
 
1073
 
 
1074
 
 
1075
SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
 
1076
                                      unsigned Alignment, int Offset,
 
1077
                                      bool isTarget,
 
1078
                                      unsigned char TargetFlags) {
 
1079
  assert((TargetFlags == 0 || isTarget) &&
 
1080
         "Cannot set target flags on target-independent globals");
 
1081
  if (Alignment == 0)
 
1082
    Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
 
1083
  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
 
1084
  FoldingSetNodeID ID;
 
1085
  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
 
1086
  ID.AddInteger(Alignment);
 
1087
  ID.AddInteger(Offset);
 
1088
  C->AddSelectionDAGCSEId(ID);
 
1089
  ID.AddInteger(TargetFlags);
 
1090
  void *IP = 0;
 
1091
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1092
    return SDValue(E, 0);
 
1093
 
 
1094
  SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
 
1095
  new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
 
1096
  CSEMap.InsertNode(N, IP);
 
1097
  AllNodes.push_back(N);
 
1098
  return SDValue(N, 0);
 
1099
}
 
1100
 
 
1101
SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
 
1102
  FoldingSetNodeID ID;
 
1103
  AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
 
1104
  ID.AddPointer(MBB);
 
1105
  void *IP = 0;
 
1106
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1107
    return SDValue(E, 0);
 
1108
 
 
1109
  SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
 
1110
  new (N) BasicBlockSDNode(MBB);
 
1111
  CSEMap.InsertNode(N, IP);
 
1112
  AllNodes.push_back(N);
 
1113
  return SDValue(N, 0);
 
1114
}
 
1115
 
 
1116
SDValue SelectionDAG::getValueType(EVT VT) {
 
1117
  if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
 
1118
      ValueTypeNodes.size())
 
1119
    ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
 
1120
 
 
1121
  SDNode *&N = VT.isExtended() ?
 
1122
    ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
 
1123
 
 
1124
  if (N) return SDValue(N, 0);
 
1125
  N = NodeAllocator.Allocate<VTSDNode>();
 
1126
  new (N) VTSDNode(VT);
 
1127
  AllNodes.push_back(N);
 
1128
  return SDValue(N, 0);
 
1129
}
 
1130
 
 
1131
SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
 
1132
  SDNode *&N = ExternalSymbols[Sym];
 
1133
  if (N) return SDValue(N, 0);
 
1134
  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
 
1135
  new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
 
1136
  AllNodes.push_back(N);
 
1137
  return SDValue(N, 0);
 
1138
}
 
1139
 
 
1140
SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
 
1141
                                              unsigned char TargetFlags) {
 
1142
  SDNode *&N =
 
1143
    TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
 
1144
                                                               TargetFlags)];
 
1145
  if (N) return SDValue(N, 0);
 
1146
  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
 
1147
  new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
 
1148
  AllNodes.push_back(N);
 
1149
  return SDValue(N, 0);
 
1150
}
 
1151
 
 
1152
SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
 
1153
  if ((unsigned)Cond >= CondCodeNodes.size())
 
1154
    CondCodeNodes.resize(Cond+1);
 
1155
 
 
1156
  if (CondCodeNodes[Cond] == 0) {
 
1157
    CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
 
1158
    new (N) CondCodeSDNode(Cond);
 
1159
    CondCodeNodes[Cond] = N;
 
1160
    AllNodes.push_back(N);
 
1161
  }
 
1162
 
 
1163
  return SDValue(CondCodeNodes[Cond], 0);
 
1164
}
 
1165
 
 
1166
// commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
 
1167
// the shuffle mask M that point at N1 to point at N2, and indices that point
 
1168
// N2 to point at N1.
 
1169
static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
 
1170
  std::swap(N1, N2);
 
1171
  int NElts = M.size();
 
1172
  for (int i = 0; i != NElts; ++i) {
 
1173
    if (M[i] >= NElts)
 
1174
      M[i] -= NElts;
 
1175
    else if (M[i] >= 0)
 
1176
      M[i] += NElts;
 
1177
  }
 
1178
}
 
1179
 
 
1180
SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
 
1181
                                       SDValue N2, const int *Mask) {
 
1182
  assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
 
1183
  assert(VT.isVector() && N1.getValueType().isVector() &&
 
1184
         "Vector Shuffle VTs must be a vectors");
 
1185
  assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
 
1186
         && "Vector Shuffle VTs must have same element type");
 
1187
 
 
1188
  // Canonicalize shuffle undef, undef -> undef
 
1189
  if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
 
1190
    return getUNDEF(VT);
 
1191
 
 
1192
  // Validate that all indices in Mask are within the range of the elements
 
1193
  // input to the shuffle.
 
1194
  unsigned NElts = VT.getVectorNumElements();
 
1195
  SmallVector<int, 8> MaskVec;
 
1196
  for (unsigned i = 0; i != NElts; ++i) {
 
1197
    assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
 
1198
    MaskVec.push_back(Mask[i]);
 
1199
  }
 
1200
 
 
1201
  // Canonicalize shuffle v, v -> v, undef
 
1202
  if (N1 == N2) {
 
1203
    N2 = getUNDEF(VT);
 
1204
    for (unsigned i = 0; i != NElts; ++i)
 
1205
      if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
 
1206
  }
 
1207
 
 
1208
  // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
 
1209
  if (N1.getOpcode() == ISD::UNDEF)
 
1210
    commuteShuffle(N1, N2, MaskVec);
 
1211
 
 
1212
  // Canonicalize all index into lhs, -> shuffle lhs, undef
 
1213
  // Canonicalize all index into rhs, -> shuffle rhs, undef
 
1214
  bool AllLHS = true, AllRHS = true;
 
1215
  bool N2Undef = N2.getOpcode() == ISD::UNDEF;
 
1216
  for (unsigned i = 0; i != NElts; ++i) {
 
1217
    if (MaskVec[i] >= (int)NElts) {
 
1218
      if (N2Undef)
 
1219
        MaskVec[i] = -1;
 
1220
      else
 
1221
        AllLHS = false;
 
1222
    } else if (MaskVec[i] >= 0) {
 
1223
      AllRHS = false;
 
1224
    }
 
1225
  }
 
1226
  if (AllLHS && AllRHS)
 
1227
    return getUNDEF(VT);
 
1228
  if (AllLHS && !N2Undef)
 
1229
    N2 = getUNDEF(VT);
 
1230
  if (AllRHS) {
 
1231
    N1 = getUNDEF(VT);
 
1232
    commuteShuffle(N1, N2, MaskVec);
 
1233
  }
 
1234
 
 
1235
  // If Identity shuffle, or all shuffle in to undef, return that node.
 
1236
  bool AllUndef = true;
 
1237
  bool Identity = true;
 
1238
  for (unsigned i = 0; i != NElts; ++i) {
 
1239
    if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
 
1240
    if (MaskVec[i] >= 0) AllUndef = false;
 
1241
  }
 
1242
  if (Identity && NElts == N1.getValueType().getVectorNumElements())
 
1243
    return N1;
 
1244
  if (AllUndef)
 
1245
    return getUNDEF(VT);
 
1246
 
 
1247
  FoldingSetNodeID ID;
 
1248
  SDValue Ops[2] = { N1, N2 };
 
1249
  AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
 
1250
  for (unsigned i = 0; i != NElts; ++i)
 
1251
    ID.AddInteger(MaskVec[i]);
 
1252
 
 
1253
  void* IP = 0;
 
1254
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1255
    return SDValue(E, 0);
 
1256
 
 
1257
  // Allocate the mask array for the node out of the BumpPtrAllocator, since
 
1258
  // SDNode doesn't have access to it.  This memory will be "leaked" when
 
1259
  // the node is deallocated, but recovered when the NodeAllocator is released.
 
1260
  int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
 
1261
  memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
 
1262
 
 
1263
  ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
 
1264
  new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
 
1265
  CSEMap.InsertNode(N, IP);
 
1266
  AllNodes.push_back(N);
 
1267
  return SDValue(N, 0);
 
1268
}
 
1269
 
 
1270
SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
 
1271
                                       SDValue Val, SDValue DTy,
 
1272
                                       SDValue STy, SDValue Rnd, SDValue Sat,
 
1273
                                       ISD::CvtCode Code) {
 
1274
  // If the src and dest types are the same and the conversion is between
 
1275
  // integer types of the same sign or two floats, no conversion is necessary.
 
1276
  if (DTy == STy &&
 
1277
      (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
 
1278
    return Val;
 
1279
 
 
1280
  FoldingSetNodeID ID;
 
1281
  SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
 
1282
  AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
 
1283
  void* IP = 0;
 
1284
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1285
    return SDValue(E, 0);
 
1286
 
 
1287
  CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
 
1288
  new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
 
1289
  CSEMap.InsertNode(N, IP);
 
1290
  AllNodes.push_back(N);
 
1291
  return SDValue(N, 0);
 
1292
}
 
1293
 
 
1294
SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
 
1295
  FoldingSetNodeID ID;
 
1296
  AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
 
1297
  ID.AddInteger(RegNo);
 
1298
  void *IP = 0;
 
1299
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1300
    return SDValue(E, 0);
 
1301
 
 
1302
  SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
 
1303
  new (N) RegisterSDNode(RegNo, VT);
 
1304
  CSEMap.InsertNode(N, IP);
 
1305
  AllNodes.push_back(N);
 
1306
  return SDValue(N, 0);
 
1307
}
 
1308
 
 
1309
SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
 
1310
                               SDValue Root,
 
1311
                               unsigned LabelID) {
 
1312
  FoldingSetNodeID ID;
 
1313
  SDValue Ops[] = { Root };
 
1314
  AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
 
1315
  ID.AddInteger(LabelID);
 
1316
  void *IP = 0;
 
1317
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1318
    return SDValue(E, 0);
 
1319
 
 
1320
  SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
 
1321
  new (N) LabelSDNode(Opcode, dl, Root, LabelID);
 
1322
  CSEMap.InsertNode(N, IP);
 
1323
  AllNodes.push_back(N);
 
1324
  return SDValue(N, 0);
 
1325
}
 
1326
 
 
1327
SDValue SelectionDAG::getBlockAddress(BlockAddress *BA, EVT VT,
 
1328
                                      bool isTarget,
 
1329
                                      unsigned char TargetFlags) {
 
1330
  unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
 
1331
 
 
1332
  FoldingSetNodeID ID;
 
1333
  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
 
1334
  ID.AddPointer(BA);
 
1335
  ID.AddInteger(TargetFlags);
 
1336
  void *IP = 0;
 
1337
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1338
    return SDValue(E, 0);
 
1339
 
 
1340
  SDNode *N = NodeAllocator.Allocate<BlockAddressSDNode>();
 
1341
  new (N) BlockAddressSDNode(Opc, VT, BA, TargetFlags);
 
1342
  CSEMap.InsertNode(N, IP);
 
1343
  AllNodes.push_back(N);
 
1344
  return SDValue(N, 0);
 
1345
}
 
1346
 
 
1347
SDValue SelectionDAG::getSrcValue(const Value *V) {
 
1348
  assert((!V || V->getType()->isPointerTy()) &&
 
1349
         "SrcValue is not a pointer?");
 
1350
 
 
1351
  FoldingSetNodeID ID;
 
1352
  AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
 
1353
  ID.AddPointer(V);
 
1354
 
 
1355
  void *IP = 0;
 
1356
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
1357
    return SDValue(E, 0);
 
1358
 
 
1359
  SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
 
1360
  new (N) SrcValueSDNode(V);
 
1361
  CSEMap.InsertNode(N, IP);
 
1362
  AllNodes.push_back(N);
 
1363
  return SDValue(N, 0);
 
1364
}
 
1365
 
 
1366
/// getShiftAmountOperand - Return the specified value casted to
 
1367
/// the target's desired shift amount type.
 
1368
SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
 
1369
  EVT OpTy = Op.getValueType();
 
1370
  MVT ShTy = TLI.getShiftAmountTy();
 
1371
  if (OpTy == ShTy || OpTy.isVector()) return Op;
 
1372
 
 
1373
  ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ?  ISD::TRUNCATE : ISD::ZERO_EXTEND;
 
1374
  return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
 
1375
}
 
1376
 
 
1377
/// CreateStackTemporary - Create a stack temporary, suitable for holding the
 
1378
/// specified value type.
 
1379
SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
 
1380
  MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
 
1381
  unsigned ByteSize = VT.getStoreSize();
 
1382
  const Type *Ty = VT.getTypeForEVT(*getContext());
 
1383
  unsigned StackAlign =
 
1384
  std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
 
1385
 
 
1386
  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
 
1387
  return getFrameIndex(FrameIdx, TLI.getPointerTy());
 
1388
}
 
1389
 
 
1390
/// CreateStackTemporary - Create a stack temporary suitable for holding
 
1391
/// either of the specified value types.
 
1392
SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
 
1393
  unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
 
1394
                            VT2.getStoreSizeInBits())/8;
 
1395
  const Type *Ty1 = VT1.getTypeForEVT(*getContext());
 
1396
  const Type *Ty2 = VT2.getTypeForEVT(*getContext());
 
1397
  const TargetData *TD = TLI.getTargetData();
 
1398
  unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
 
1399
                            TD->getPrefTypeAlignment(Ty2));
 
1400
 
 
1401
  MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
 
1402
  int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
 
1403
  return getFrameIndex(FrameIdx, TLI.getPointerTy());
 
1404
}
 
1405
 
 
1406
SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
 
1407
                                SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
 
1408
  // These setcc operations always fold.
 
1409
  switch (Cond) {
 
1410
  default: break;
 
1411
  case ISD::SETFALSE:
 
1412
  case ISD::SETFALSE2: return getConstant(0, VT);
 
1413
  case ISD::SETTRUE:
 
1414
  case ISD::SETTRUE2:  return getConstant(1, VT);
 
1415
 
 
1416
  case ISD::SETOEQ:
 
1417
  case ISD::SETOGT:
 
1418
  case ISD::SETOGE:
 
1419
  case ISD::SETOLT:
 
1420
  case ISD::SETOLE:
 
1421
  case ISD::SETONE:
 
1422
  case ISD::SETO:
 
1423
  case ISD::SETUO:
 
1424
  case ISD::SETUEQ:
 
1425
  case ISD::SETUNE:
 
1426
    assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
 
1427
    break;
 
1428
  }
 
1429
 
 
1430
  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
 
1431
    const APInt &C2 = N2C->getAPIntValue();
 
1432
    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
 
1433
      const APInt &C1 = N1C->getAPIntValue();
 
1434
 
 
1435
      switch (Cond) {
 
1436
      default: llvm_unreachable("Unknown integer setcc!");
 
1437
      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
 
1438
      case ISD::SETNE:  return getConstant(C1 != C2, VT);
 
1439
      case ISD::SETULT: return getConstant(C1.ult(C2), VT);
 
1440
      case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
 
1441
      case ISD::SETULE: return getConstant(C1.ule(C2), VT);
 
1442
      case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
 
1443
      case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
 
1444
      case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
 
1445
      case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
 
1446
      case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
 
1447
      }
 
1448
    }
 
1449
  }
 
1450
  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
 
1451
    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
 
1452
      // No compile time operations on this type yet.
 
1453
      if (N1C->getValueType(0) == MVT::ppcf128)
 
1454
        return SDValue();
 
1455
 
 
1456
      APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
 
1457
      switch (Cond) {
 
1458
      default: break;
 
1459
      case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
 
1460
                          return getUNDEF(VT);
 
1461
                        // fall through
 
1462
      case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
 
1463
      case ISD::SETNE:  if (R==APFloat::cmpUnordered)
 
1464
                          return getUNDEF(VT);
 
1465
                        // fall through
 
1466
      case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
 
1467
                                           R==APFloat::cmpLessThan, VT);
 
1468
      case ISD::SETLT:  if (R==APFloat::cmpUnordered)
 
1469
                          return getUNDEF(VT);
 
1470
                        // fall through
 
1471
      case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
 
1472
      case ISD::SETGT:  if (R==APFloat::cmpUnordered)
 
1473
                          return getUNDEF(VT);
 
1474
                        // fall through
 
1475
      case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
 
1476
      case ISD::SETLE:  if (R==APFloat::cmpUnordered)
 
1477
                          return getUNDEF(VT);
 
1478
                        // fall through
 
1479
      case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
 
1480
                                           R==APFloat::cmpEqual, VT);
 
1481
      case ISD::SETGE:  if (R==APFloat::cmpUnordered)
 
1482
                          return getUNDEF(VT);
 
1483
                        // fall through
 
1484
      case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
 
1485
                                           R==APFloat::cmpEqual, VT);
 
1486
      case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
 
1487
      case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
 
1488
      case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
 
1489
                                           R==APFloat::cmpEqual, VT);
 
1490
      case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
 
1491
      case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
 
1492
                                           R==APFloat::cmpLessThan, VT);
 
1493
      case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
 
1494
                                           R==APFloat::cmpUnordered, VT);
 
1495
      case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
 
1496
      case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
 
1497
      }
 
1498
    } else {
 
1499
      // Ensure that the constant occurs on the RHS.
 
1500
      return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
 
1501
    }
 
1502
  }
 
1503
 
 
1504
  // Could not fold it.
 
1505
  return SDValue();
 
1506
}
 
1507
 
 
1508
/// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
 
1509
/// use this predicate to simplify operations downstream.
 
1510
bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
 
1511
  // This predicate is not safe for vector operations.
 
1512
  if (Op.getValueType().isVector())
 
1513
    return false;
 
1514
 
 
1515
  unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
 
1516
  return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
 
1517
}
 
1518
 
 
1519
/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
 
1520
/// this predicate to simplify operations downstream.  Mask is known to be zero
 
1521
/// for bits that V cannot have.
 
1522
bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
 
1523
                                     unsigned Depth) const {
 
1524
  APInt KnownZero, KnownOne;
 
1525
  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
 
1526
  assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1527
  return (KnownZero & Mask) == Mask;
 
1528
}
 
1529
 
 
1530
/// ComputeMaskedBits - Determine which of the bits specified in Mask are
 
1531
/// known to be either zero or one and return them in the KnownZero/KnownOne
 
1532
/// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
 
1533
/// processing.
 
1534
void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
 
1535
                                     APInt &KnownZero, APInt &KnownOne,
 
1536
                                     unsigned Depth) const {
 
1537
  unsigned BitWidth = Mask.getBitWidth();
 
1538
  assert(BitWidth == Op.getValueType().getScalarType().getSizeInBits() &&
 
1539
         "Mask size mismatches value type size!");
 
1540
 
 
1541
  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
 
1542
  if (Depth == 6 || Mask == 0)
 
1543
    return;  // Limit search depth.
 
1544
 
 
1545
  APInt KnownZero2, KnownOne2;
 
1546
 
 
1547
  switch (Op.getOpcode()) {
 
1548
  case ISD::Constant:
 
1549
    // We know all of the bits for a constant!
 
1550
    KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
 
1551
    KnownZero = ~KnownOne & Mask;
 
1552
    return;
 
1553
  case ISD::AND:
 
1554
    // If either the LHS or the RHS are Zero, the result is zero.
 
1555
    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
 
1556
    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
 
1557
                      KnownZero2, KnownOne2, Depth+1);
 
1558
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1559
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1560
 
 
1561
    // Output known-1 bits are only known if set in both the LHS & RHS.
 
1562
    KnownOne &= KnownOne2;
 
1563
    // Output known-0 are known to be clear if zero in either the LHS | RHS.
 
1564
    KnownZero |= KnownZero2;
 
1565
    return;
 
1566
  case ISD::OR:
 
1567
    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
 
1568
    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
 
1569
                      KnownZero2, KnownOne2, Depth+1);
 
1570
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1571
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1572
 
 
1573
    // Output known-0 bits are only known if clear in both the LHS & RHS.
 
1574
    KnownZero &= KnownZero2;
 
1575
    // Output known-1 are known to be set if set in either the LHS | RHS.
 
1576
    KnownOne |= KnownOne2;
 
1577
    return;
 
1578
  case ISD::XOR: {
 
1579
    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
 
1580
    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
 
1581
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1582
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1583
 
 
1584
    // Output known-0 bits are known if clear or set in both the LHS & RHS.
 
1585
    APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
 
1586
    // Output known-1 are known to be set if set in only one of the LHS, RHS.
 
1587
    KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
 
1588
    KnownZero = KnownZeroOut;
 
1589
    return;
 
1590
  }
 
1591
  case ISD::MUL: {
 
1592
    APInt Mask2 = APInt::getAllOnesValue(BitWidth);
 
1593
    ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
 
1594
    ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
 
1595
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1596
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1597
 
 
1598
    // If low bits are zero in either operand, output low known-0 bits.
 
1599
    // Also compute a conserative estimate for high known-0 bits.
 
1600
    // More trickiness is possible, but this is sufficient for the
 
1601
    // interesting case of alignment computation.
 
1602
    KnownOne.clear();
 
1603
    unsigned TrailZ = KnownZero.countTrailingOnes() +
 
1604
                      KnownZero2.countTrailingOnes();
 
1605
    unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
 
1606
                               KnownZero2.countLeadingOnes(),
 
1607
                               BitWidth) - BitWidth;
 
1608
 
 
1609
    TrailZ = std::min(TrailZ, BitWidth);
 
1610
    LeadZ = std::min(LeadZ, BitWidth);
 
1611
    KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
 
1612
                APInt::getHighBitsSet(BitWidth, LeadZ);
 
1613
    KnownZero &= Mask;
 
1614
    return;
 
1615
  }
 
1616
  case ISD::UDIV: {
 
1617
    // For the purposes of computing leading zeros we can conservatively
 
1618
    // treat a udiv as a logical right shift by the power of 2 known to
 
1619
    // be less than the denominator.
 
1620
    APInt AllOnes = APInt::getAllOnesValue(BitWidth);
 
1621
    ComputeMaskedBits(Op.getOperand(0),
 
1622
                      AllOnes, KnownZero2, KnownOne2, Depth+1);
 
1623
    unsigned LeadZ = KnownZero2.countLeadingOnes();
 
1624
 
 
1625
    KnownOne2.clear();
 
1626
    KnownZero2.clear();
 
1627
    ComputeMaskedBits(Op.getOperand(1),
 
1628
                      AllOnes, KnownZero2, KnownOne2, Depth+1);
 
1629
    unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
 
1630
    if (RHSUnknownLeadingOnes != BitWidth)
 
1631
      LeadZ = std::min(BitWidth,
 
1632
                       LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
 
1633
 
 
1634
    KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
 
1635
    return;
 
1636
  }
 
1637
  case ISD::SELECT:
 
1638
    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
 
1639
    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
 
1640
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1641
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1642
 
 
1643
    // Only known if known in both the LHS and RHS.
 
1644
    KnownOne &= KnownOne2;
 
1645
    KnownZero &= KnownZero2;
 
1646
    return;
 
1647
  case ISD::SELECT_CC:
 
1648
    ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
 
1649
    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
 
1650
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1651
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1652
 
 
1653
    // Only known if known in both the LHS and RHS.
 
1654
    KnownOne &= KnownOne2;
 
1655
    KnownZero &= KnownZero2;
 
1656
    return;
 
1657
  case ISD::SADDO:
 
1658
  case ISD::UADDO:
 
1659
  case ISD::SSUBO:
 
1660
  case ISD::USUBO:
 
1661
  case ISD::SMULO:
 
1662
  case ISD::UMULO:
 
1663
    if (Op.getResNo() != 1)
 
1664
      return;
 
1665
    // The boolean result conforms to getBooleanContents.  Fall through.
 
1666
  case ISD::SETCC:
 
1667
    // If we know the result of a setcc has the top bits zero, use this info.
 
1668
    if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
 
1669
        BitWidth > 1)
 
1670
      KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
 
1671
    return;
 
1672
  case ISD::SHL:
 
1673
    // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
 
1674
    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
1675
      unsigned ShAmt = SA->getZExtValue();
 
1676
 
 
1677
      // If the shift count is an invalid immediate, don't do anything.
 
1678
      if (ShAmt >= BitWidth)
 
1679
        return;
 
1680
 
 
1681
      ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
 
1682
                        KnownZero, KnownOne, Depth+1);
 
1683
      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1684
      KnownZero <<= ShAmt;
 
1685
      KnownOne  <<= ShAmt;
 
1686
      // low bits known zero.
 
1687
      KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
 
1688
    }
 
1689
    return;
 
1690
  case ISD::SRL:
 
1691
    // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
 
1692
    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
1693
      unsigned ShAmt = SA->getZExtValue();
 
1694
 
 
1695
      // If the shift count is an invalid immediate, don't do anything.
 
1696
      if (ShAmt >= BitWidth)
 
1697
        return;
 
1698
 
 
1699
      ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
 
1700
                        KnownZero, KnownOne, Depth+1);
 
1701
      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1702
      KnownZero = KnownZero.lshr(ShAmt);
 
1703
      KnownOne  = KnownOne.lshr(ShAmt);
 
1704
 
 
1705
      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
 
1706
      KnownZero |= HighBits;  // High bits known zero.
 
1707
    }
 
1708
    return;
 
1709
  case ISD::SRA:
 
1710
    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
1711
      unsigned ShAmt = SA->getZExtValue();
 
1712
 
 
1713
      // If the shift count is an invalid immediate, don't do anything.
 
1714
      if (ShAmt >= BitWidth)
 
1715
        return;
 
1716
 
 
1717
      APInt InDemandedMask = (Mask << ShAmt);
 
1718
      // If any of the demanded bits are produced by the sign extension, we also
 
1719
      // demand the input sign bit.
 
1720
      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
 
1721
      if (HighBits.getBoolValue())
 
1722
        InDemandedMask |= APInt::getSignBit(BitWidth);
 
1723
 
 
1724
      ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
 
1725
                        Depth+1);
 
1726
      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1727
      KnownZero = KnownZero.lshr(ShAmt);
 
1728
      KnownOne  = KnownOne.lshr(ShAmt);
 
1729
 
 
1730
      // Handle the sign bits.
 
1731
      APInt SignBit = APInt::getSignBit(BitWidth);
 
1732
      SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
 
1733
 
 
1734
      if (KnownZero.intersects(SignBit)) {
 
1735
        KnownZero |= HighBits;  // New bits are known zero.
 
1736
      } else if (KnownOne.intersects(SignBit)) {
 
1737
        KnownOne  |= HighBits;  // New bits are known one.
 
1738
      }
 
1739
    }
 
1740
    return;
 
1741
  case ISD::SIGN_EXTEND_INREG: {
 
1742
    EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
 
1743
    unsigned EBits = EVT.getScalarType().getSizeInBits();
 
1744
 
 
1745
    // Sign extension.  Compute the demanded bits in the result that are not
 
1746
    // present in the input.
 
1747
    APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
 
1748
 
 
1749
    APInt InSignBit = APInt::getSignBit(EBits);
 
1750
    APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
 
1751
 
 
1752
    // If the sign extended bits are demanded, we know that the sign
 
1753
    // bit is demanded.
 
1754
    InSignBit.zext(BitWidth);
 
1755
    if (NewBits.getBoolValue())
 
1756
      InputDemandedBits |= InSignBit;
 
1757
 
 
1758
    ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
 
1759
                      KnownZero, KnownOne, Depth+1);
 
1760
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1761
 
 
1762
    // If the sign bit of the input is known set or clear, then we know the
 
1763
    // top bits of the result.
 
1764
    if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
 
1765
      KnownZero |= NewBits;
 
1766
      KnownOne  &= ~NewBits;
 
1767
    } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
 
1768
      KnownOne  |= NewBits;
 
1769
      KnownZero &= ~NewBits;
 
1770
    } else {                              // Input sign bit unknown
 
1771
      KnownZero &= ~NewBits;
 
1772
      KnownOne  &= ~NewBits;
 
1773
    }
 
1774
    return;
 
1775
  }
 
1776
  case ISD::CTTZ:
 
1777
  case ISD::CTLZ:
 
1778
  case ISD::CTPOP: {
 
1779
    unsigned LowBits = Log2_32(BitWidth)+1;
 
1780
    KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
 
1781
    KnownOne.clear();
 
1782
    return;
 
1783
  }
 
1784
  case ISD::LOAD: {
 
1785
    if (ISD::isZEXTLoad(Op.getNode())) {
 
1786
      LoadSDNode *LD = cast<LoadSDNode>(Op);
 
1787
      EVT VT = LD->getMemoryVT();
 
1788
      unsigned MemBits = VT.getScalarType().getSizeInBits();
 
1789
      KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
 
1790
    }
 
1791
    return;
 
1792
  }
 
1793
  case ISD::ZERO_EXTEND: {
 
1794
    EVT InVT = Op.getOperand(0).getValueType();
 
1795
    unsigned InBits = InVT.getScalarType().getSizeInBits();
 
1796
    APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
 
1797
    APInt InMask    = Mask;
 
1798
    InMask.trunc(InBits);
 
1799
    KnownZero.trunc(InBits);
 
1800
    KnownOne.trunc(InBits);
 
1801
    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
 
1802
    KnownZero.zext(BitWidth);
 
1803
    KnownOne.zext(BitWidth);
 
1804
    KnownZero |= NewBits;
 
1805
    return;
 
1806
  }
 
1807
  case ISD::SIGN_EXTEND: {
 
1808
    EVT InVT = Op.getOperand(0).getValueType();
 
1809
    unsigned InBits = InVT.getScalarType().getSizeInBits();
 
1810
    APInt InSignBit = APInt::getSignBit(InBits);
 
1811
    APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
 
1812
    APInt InMask = Mask;
 
1813
    InMask.trunc(InBits);
 
1814
 
 
1815
    // If any of the sign extended bits are demanded, we know that the sign
 
1816
    // bit is demanded. Temporarily set this bit in the mask for our callee.
 
1817
    if (NewBits.getBoolValue())
 
1818
      InMask |= InSignBit;
 
1819
 
 
1820
    KnownZero.trunc(InBits);
 
1821
    KnownOne.trunc(InBits);
 
1822
    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
 
1823
 
 
1824
    // Note if the sign bit is known to be zero or one.
 
1825
    bool SignBitKnownZero = KnownZero.isNegative();
 
1826
    bool SignBitKnownOne  = KnownOne.isNegative();
 
1827
    assert(!(SignBitKnownZero && SignBitKnownOne) &&
 
1828
           "Sign bit can't be known to be both zero and one!");
 
1829
 
 
1830
    // If the sign bit wasn't actually demanded by our caller, we don't
 
1831
    // want it set in the KnownZero and KnownOne result values. Reset the
 
1832
    // mask and reapply it to the result values.
 
1833
    InMask = Mask;
 
1834
    InMask.trunc(InBits);
 
1835
    KnownZero &= InMask;
 
1836
    KnownOne  &= InMask;
 
1837
 
 
1838
    KnownZero.zext(BitWidth);
 
1839
    KnownOne.zext(BitWidth);
 
1840
 
 
1841
    // If the sign bit is known zero or one, the top bits match.
 
1842
    if (SignBitKnownZero)
 
1843
      KnownZero |= NewBits;
 
1844
    else if (SignBitKnownOne)
 
1845
      KnownOne  |= NewBits;
 
1846
    return;
 
1847
  }
 
1848
  case ISD::ANY_EXTEND: {
 
1849
    EVT InVT = Op.getOperand(0).getValueType();
 
1850
    unsigned InBits = InVT.getScalarType().getSizeInBits();
 
1851
    APInt InMask = Mask;
 
1852
    InMask.trunc(InBits);
 
1853
    KnownZero.trunc(InBits);
 
1854
    KnownOne.trunc(InBits);
 
1855
    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
 
1856
    KnownZero.zext(BitWidth);
 
1857
    KnownOne.zext(BitWidth);
 
1858
    return;
 
1859
  }
 
1860
  case ISD::TRUNCATE: {
 
1861
    EVT InVT = Op.getOperand(0).getValueType();
 
1862
    unsigned InBits = InVT.getScalarType().getSizeInBits();
 
1863
    APInt InMask = Mask;
 
1864
    InMask.zext(InBits);
 
1865
    KnownZero.zext(InBits);
 
1866
    KnownOne.zext(InBits);
 
1867
    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
 
1868
    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
 
1869
    KnownZero.trunc(BitWidth);
 
1870
    KnownOne.trunc(BitWidth);
 
1871
    break;
 
1872
  }
 
1873
  case ISD::AssertZext: {
 
1874
    EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
 
1875
    APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
 
1876
    ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
 
1877
                      KnownOne, Depth+1);
 
1878
    KnownZero |= (~InMask) & Mask;
 
1879
    return;
 
1880
  }
 
1881
  case ISD::FGETSIGN:
 
1882
    // All bits are zero except the low bit.
 
1883
    KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
 
1884
    return;
 
1885
 
 
1886
  case ISD::SUB: {
 
1887
    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
 
1888
      // We know that the top bits of C-X are clear if X contains less bits
 
1889
      // than C (i.e. no wrap-around can happen).  For example, 20-X is
 
1890
      // positive if we can prove that X is >= 0 and < 16.
 
1891
      if (CLHS->getAPIntValue().isNonNegative()) {
 
1892
        unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
 
1893
        // NLZ can't be BitWidth with no sign bit
 
1894
        APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
 
1895
        ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
 
1896
                          Depth+1);
 
1897
 
 
1898
        // If all of the MaskV bits are known to be zero, then we know the
 
1899
        // output top bits are zero, because we now know that the output is
 
1900
        // from [0-C].
 
1901
        if ((KnownZero2 & MaskV) == MaskV) {
 
1902
          unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
 
1903
          // Top bits known zero.
 
1904
          KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
 
1905
        }
 
1906
      }
 
1907
    }
 
1908
  }
 
1909
  // fall through
 
1910
  case ISD::ADD: {
 
1911
    // Output known-0 bits are known if clear or set in both the low clear bits
 
1912
    // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
 
1913
    // low 3 bits clear.
 
1914
    APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
 
1915
    ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
 
1916
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1917
    unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
 
1918
 
 
1919
    ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
 
1920
    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
 
1921
    KnownZeroOut = std::min(KnownZeroOut,
 
1922
                            KnownZero2.countTrailingOnes());
 
1923
 
 
1924
    KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
 
1925
    return;
 
1926
  }
 
1927
  case ISD::SREM:
 
1928
    if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
1929
      const APInt &RA = Rem->getAPIntValue().abs();
 
1930
      if (RA.isPowerOf2()) {
 
1931
        APInt LowBits = RA - 1;
 
1932
        APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
 
1933
        ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
 
1934
 
 
1935
        // The low bits of the first operand are unchanged by the srem.
 
1936
        KnownZero = KnownZero2 & LowBits;
 
1937
        KnownOne = KnownOne2 & LowBits;
 
1938
 
 
1939
        // If the first operand is non-negative or has all low bits zero, then
 
1940
        // the upper bits are all zero.
 
1941
        if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
 
1942
          KnownZero |= ~LowBits;
 
1943
 
 
1944
        // If the first operand is negative and not all low bits are zero, then
 
1945
        // the upper bits are all one.
 
1946
        if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
 
1947
          KnownOne |= ~LowBits;
 
1948
 
 
1949
        KnownZero &= Mask;
 
1950
        KnownOne &= Mask;
 
1951
 
 
1952
        assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
 
1953
      }
 
1954
    }
 
1955
    return;
 
1956
  case ISD::UREM: {
 
1957
    if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
1958
      const APInt &RA = Rem->getAPIntValue();
 
1959
      if (RA.isPowerOf2()) {
 
1960
        APInt LowBits = (RA - 1);
 
1961
        APInt Mask2 = LowBits & Mask;
 
1962
        KnownZero |= ~LowBits & Mask;
 
1963
        ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
 
1964
        assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
 
1965
        break;
 
1966
      }
 
1967
    }
 
1968
 
 
1969
    // Since the result is less than or equal to either operand, any leading
 
1970
    // zero bits in either operand must also exist in the result.
 
1971
    APInt AllOnes = APInt::getAllOnesValue(BitWidth);
 
1972
    ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
 
1973
                      Depth+1);
 
1974
    ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
 
1975
                      Depth+1);
 
1976
 
 
1977
    uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
 
1978
                                KnownZero2.countLeadingOnes());
 
1979
    KnownOne.clear();
 
1980
    KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
 
1981
    return;
 
1982
  }
 
1983
  default:
 
1984
    // Allow the target to implement this method for its nodes.
 
1985
    if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
 
1986
  case ISD::INTRINSIC_WO_CHAIN:
 
1987
  case ISD::INTRINSIC_W_CHAIN:
 
1988
  case ISD::INTRINSIC_VOID:
 
1989
      TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
 
1990
                                         Depth);
 
1991
    }
 
1992
    return;
 
1993
  }
 
1994
}
 
1995
 
 
1996
/// ComputeNumSignBits - Return the number of times the sign bit of the
 
1997
/// register is replicated into the other bits.  We know that at least 1 bit
 
1998
/// is always equal to the sign bit (itself), but other cases can give us
 
1999
/// information.  For example, immediately after an "SRA X, 2", we know that
 
2000
/// the top 3 bits are all equal to each other, so we return 3.
 
2001
unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
 
2002
  EVT VT = Op.getValueType();
 
2003
  assert(VT.isInteger() && "Invalid VT!");
 
2004
  unsigned VTBits = VT.getScalarType().getSizeInBits();
 
2005
  unsigned Tmp, Tmp2;
 
2006
  unsigned FirstAnswer = 1;
 
2007
 
 
2008
  if (Depth == 6)
 
2009
    return 1;  // Limit search depth.
 
2010
 
 
2011
  switch (Op.getOpcode()) {
 
2012
  default: break;
 
2013
  case ISD::AssertSext:
 
2014
    Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
 
2015
    return VTBits-Tmp+1;
 
2016
  case ISD::AssertZext:
 
2017
    Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
 
2018
    return VTBits-Tmp;
 
2019
 
 
2020
  case ISD::Constant: {
 
2021
    const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
 
2022
    // If negative, return # leading ones.
 
2023
    if (Val.isNegative())
 
2024
      return Val.countLeadingOnes();
 
2025
 
 
2026
    // Return # leading zeros.
 
2027
    return Val.countLeadingZeros();
 
2028
  }
 
2029
 
 
2030
  case ISD::SIGN_EXTEND:
 
2031
    Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
 
2032
    return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
 
2033
 
 
2034
  case ISD::SIGN_EXTEND_INREG:
 
2035
    // Max of the input and what this extends.
 
2036
    Tmp =
 
2037
      cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
 
2038
    Tmp = VTBits-Tmp+1;
 
2039
 
 
2040
    Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
 
2041
    return std::max(Tmp, Tmp2);
 
2042
 
 
2043
  case ISD::SRA:
 
2044
    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
 
2045
    // SRA X, C   -> adds C sign bits.
 
2046
    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
2047
      Tmp += C->getZExtValue();
 
2048
      if (Tmp > VTBits) Tmp = VTBits;
 
2049
    }
 
2050
    return Tmp;
 
2051
  case ISD::SHL:
 
2052
    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
2053
      // shl destroys sign bits.
 
2054
      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
 
2055
      if (C->getZExtValue() >= VTBits ||      // Bad shift.
 
2056
          C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
 
2057
      return Tmp - C->getZExtValue();
 
2058
    }
 
2059
    break;
 
2060
  case ISD::AND:
 
2061
  case ISD::OR:
 
2062
  case ISD::XOR:    // NOT is handled here.
 
2063
    // Logical binary ops preserve the number of sign bits at the worst.
 
2064
    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
 
2065
    if (Tmp != 1) {
 
2066
      Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
 
2067
      FirstAnswer = std::min(Tmp, Tmp2);
 
2068
      // We computed what we know about the sign bits as our first
 
2069
      // answer. Now proceed to the generic code that uses
 
2070
      // ComputeMaskedBits, and pick whichever answer is better.
 
2071
    }
 
2072
    break;
 
2073
 
 
2074
  case ISD::SELECT:
 
2075
    Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
 
2076
    if (Tmp == 1) return 1;  // Early out.
 
2077
    Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
 
2078
    return std::min(Tmp, Tmp2);
 
2079
 
 
2080
  case ISD::SADDO:
 
2081
  case ISD::UADDO:
 
2082
  case ISD::SSUBO:
 
2083
  case ISD::USUBO:
 
2084
  case ISD::SMULO:
 
2085
  case ISD::UMULO:
 
2086
    if (Op.getResNo() != 1)
 
2087
      break;
 
2088
    // The boolean result conforms to getBooleanContents.  Fall through.
 
2089
  case ISD::SETCC:
 
2090
    // If setcc returns 0/-1, all bits are sign bits.
 
2091
    if (TLI.getBooleanContents() ==
 
2092
        TargetLowering::ZeroOrNegativeOneBooleanContent)
 
2093
      return VTBits;
 
2094
    break;
 
2095
  case ISD::ROTL:
 
2096
  case ISD::ROTR:
 
2097
    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
 
2098
      unsigned RotAmt = C->getZExtValue() & (VTBits-1);
 
2099
 
 
2100
      // Handle rotate right by N like a rotate left by 32-N.
 
2101
      if (Op.getOpcode() == ISD::ROTR)
 
2102
        RotAmt = (VTBits-RotAmt) & (VTBits-1);
 
2103
 
 
2104
      // If we aren't rotating out all of the known-in sign bits, return the
 
2105
      // number that are left.  This handles rotl(sext(x), 1) for example.
 
2106
      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
 
2107
      if (Tmp > RotAmt+1) return Tmp-RotAmt;
 
2108
    }
 
2109
    break;
 
2110
  case ISD::ADD:
 
2111
    // Add can have at most one carry bit.  Thus we know that the output
 
2112
    // is, at worst, one more bit than the inputs.
 
2113
    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
 
2114
    if (Tmp == 1) return 1;  // Early out.
 
2115
 
 
2116
    // Special case decrementing a value (ADD X, -1):
 
2117
    if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
 
2118
      if (CRHS->isAllOnesValue()) {
 
2119
        APInt KnownZero, KnownOne;
 
2120
        APInt Mask = APInt::getAllOnesValue(VTBits);
 
2121
        ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
 
2122
 
 
2123
        // If the input is known to be 0 or 1, the output is 0/-1, which is all
 
2124
        // sign bits set.
 
2125
        if ((KnownZero | APInt(VTBits, 1)) == Mask)
 
2126
          return VTBits;
 
2127
 
 
2128
        // If we are subtracting one from a positive number, there is no carry
 
2129
        // out of the result.
 
2130
        if (KnownZero.isNegative())
 
2131
          return Tmp;
 
2132
      }
 
2133
 
 
2134
    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
 
2135
    if (Tmp2 == 1) return 1;
 
2136
      return std::min(Tmp, Tmp2)-1;
 
2137
    break;
 
2138
 
 
2139
  case ISD::SUB:
 
2140
    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
 
2141
    if (Tmp2 == 1) return 1;
 
2142
 
 
2143
    // Handle NEG.
 
2144
    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
 
2145
      if (CLHS->isNullValue()) {
 
2146
        APInt KnownZero, KnownOne;
 
2147
        APInt Mask = APInt::getAllOnesValue(VTBits);
 
2148
        ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
 
2149
        // If the input is known to be 0 or 1, the output is 0/-1, which is all
 
2150
        // sign bits set.
 
2151
        if ((KnownZero | APInt(VTBits, 1)) == Mask)
 
2152
          return VTBits;
 
2153
 
 
2154
        // If the input is known to be positive (the sign bit is known clear),
 
2155
        // the output of the NEG has the same number of sign bits as the input.
 
2156
        if (KnownZero.isNegative())
 
2157
          return Tmp2;
 
2158
 
 
2159
        // Otherwise, we treat this like a SUB.
 
2160
      }
 
2161
 
 
2162
    // Sub can have at most one carry bit.  Thus we know that the output
 
2163
    // is, at worst, one more bit than the inputs.
 
2164
    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
 
2165
    if (Tmp == 1) return 1;  // Early out.
 
2166
      return std::min(Tmp, Tmp2)-1;
 
2167
    break;
 
2168
  case ISD::TRUNCATE:
 
2169
    // FIXME: it's tricky to do anything useful for this, but it is an important
 
2170
    // case for targets like X86.
 
2171
    break;
 
2172
  }
 
2173
 
 
2174
  // Handle LOADX separately here. EXTLOAD case will fallthrough.
 
2175
  if (Op.getOpcode() == ISD::LOAD) {
 
2176
    LoadSDNode *LD = cast<LoadSDNode>(Op);
 
2177
    unsigned ExtType = LD->getExtensionType();
 
2178
    switch (ExtType) {
 
2179
    default: break;
 
2180
    case ISD::SEXTLOAD:    // '17' bits known
 
2181
      Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
 
2182
      return VTBits-Tmp+1;
 
2183
    case ISD::ZEXTLOAD:    // '16' bits known
 
2184
      Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
 
2185
      return VTBits-Tmp;
 
2186
    }
 
2187
  }
 
2188
 
 
2189
  // Allow the target to implement this method for its nodes.
 
2190
  if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
 
2191
      Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
 
2192
      Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
 
2193
      Op.getOpcode() == ISD::INTRINSIC_VOID) {
 
2194
    unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
 
2195
    if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
 
2196
  }
 
2197
 
 
2198
  // Finally, if we can prove that the top bits of the result are 0's or 1's,
 
2199
  // use this information.
 
2200
  APInt KnownZero, KnownOne;
 
2201
  APInt Mask = APInt::getAllOnesValue(VTBits);
 
2202
  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
 
2203
 
 
2204
  if (KnownZero.isNegative()) {        // sign bit is 0
 
2205
    Mask = KnownZero;
 
2206
  } else if (KnownOne.isNegative()) {  // sign bit is 1;
 
2207
    Mask = KnownOne;
 
2208
  } else {
 
2209
    // Nothing known.
 
2210
    return FirstAnswer;
 
2211
  }
 
2212
 
 
2213
  // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
 
2214
  // the number of identical bits in the top of the input value.
 
2215
  Mask = ~Mask;
 
2216
  Mask <<= Mask.getBitWidth()-VTBits;
 
2217
  // Return # leading zeros.  We use 'min' here in case Val was zero before
 
2218
  // shifting.  We don't want to return '64' as for an i32 "0".
 
2219
  return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
 
2220
}
 
2221
 
 
2222
bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
 
2223
  // If we're told that NaNs won't happen, assume they won't.
 
2224
  if (FiniteOnlyFPMath())
 
2225
    return true;
 
2226
 
 
2227
  // If the value is a constant, we can obviously see if it is a NaN or not.
 
2228
  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
 
2229
    return !C->getValueAPF().isNaN();
 
2230
 
 
2231
  // TODO: Recognize more cases here.
 
2232
 
 
2233
  return false;
 
2234
}
 
2235
 
 
2236
bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
 
2237
  // If the value is a constant, we can obviously see if it is a zero or not.
 
2238
  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
 
2239
    return !C->isZero();
 
2240
 
 
2241
  // TODO: Recognize more cases here.
 
2242
 
 
2243
  return false;
 
2244
}
 
2245
 
 
2246
bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
 
2247
  // Check the obvious case.
 
2248
  if (A == B) return true;
 
2249
 
 
2250
  // For for negative and positive zero.
 
2251
  if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
 
2252
    if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
 
2253
      if (CA->isZero() && CB->isZero()) return true;
 
2254
 
 
2255
  // Otherwise they may not be equal.
 
2256
  return false;
 
2257
}
 
2258
 
 
2259
bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
 
2260
  GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
 
2261
  if (!GA) return false;
 
2262
  if (GA->getOffset() != 0) return false;
 
2263
  GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
 
2264
  if (!GV) return false;
 
2265
  MachineModuleInfo *MMI = getMachineModuleInfo();
 
2266
  return MMI && MMI->hasDebugInfo();
 
2267
}
 
2268
 
 
2269
 
 
2270
/// getShuffleScalarElt - Returns the scalar element that will make up the ith
 
2271
/// element of the result of the vector shuffle.
 
2272
SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
 
2273
                                          unsigned i) {
 
2274
  EVT VT = N->getValueType(0);
 
2275
  DebugLoc dl = N->getDebugLoc();
 
2276
  if (N->getMaskElt(i) < 0)
 
2277
    return getUNDEF(VT.getVectorElementType());
 
2278
  unsigned Index = N->getMaskElt(i);
 
2279
  unsigned NumElems = VT.getVectorNumElements();
 
2280
  SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
 
2281
  Index %= NumElems;
 
2282
 
 
2283
  if (V.getOpcode() == ISD::BIT_CONVERT) {
 
2284
    V = V.getOperand(0);
 
2285
    EVT VVT = V.getValueType();
 
2286
    if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
 
2287
      return SDValue();
 
2288
  }
 
2289
  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
 
2290
    return (Index == 0) ? V.getOperand(0)
 
2291
                      : getUNDEF(VT.getVectorElementType());
 
2292
  if (V.getOpcode() == ISD::BUILD_VECTOR)
 
2293
    return V.getOperand(Index);
 
2294
  if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
 
2295
    return getShuffleScalarElt(SVN, Index);
 
2296
  return SDValue();
 
2297
}
 
2298
 
 
2299
 
 
2300
/// getNode - Gets or creates the specified node.
 
2301
///
 
2302
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
 
2303
  FoldingSetNodeID ID;
 
2304
  AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
 
2305
  void *IP = 0;
 
2306
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
2307
    return SDValue(E, 0);
 
2308
 
 
2309
  SDNode *N = NodeAllocator.Allocate<SDNode>();
 
2310
  new (N) SDNode(Opcode, DL, getVTList(VT));
 
2311
  CSEMap.InsertNode(N, IP);
 
2312
 
 
2313
  AllNodes.push_back(N);
 
2314
#ifndef NDEBUG
 
2315
  VerifyNode(N);
 
2316
#endif
 
2317
  return SDValue(N, 0);
 
2318
}
 
2319
 
 
2320
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
 
2321
                              EVT VT, SDValue Operand) {
 
2322
  // Constant fold unary operations with an integer constant operand.
 
2323
  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
 
2324
    const APInt &Val = C->getAPIntValue();
 
2325
    unsigned BitWidth = VT.getSizeInBits();
 
2326
    switch (Opcode) {
 
2327
    default: break;
 
2328
    case ISD::SIGN_EXTEND:
 
2329
      return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
 
2330
    case ISD::ANY_EXTEND:
 
2331
    case ISD::ZERO_EXTEND:
 
2332
    case ISD::TRUNCATE:
 
2333
      return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
 
2334
    case ISD::UINT_TO_FP:
 
2335
    case ISD::SINT_TO_FP: {
 
2336
      const uint64_t zero[] = {0, 0};
 
2337
      // No compile time operations on this type.
 
2338
      if (VT==MVT::ppcf128)
 
2339
        break;
 
2340
      APFloat apf = APFloat(APInt(BitWidth, 2, zero));
 
2341
      (void)apf.convertFromAPInt(Val,
 
2342
                                 Opcode==ISD::SINT_TO_FP,
 
2343
                                 APFloat::rmNearestTiesToEven);
 
2344
      return getConstantFP(apf, VT);
 
2345
    }
 
2346
    case ISD::BIT_CONVERT:
 
2347
      if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
 
2348
        return getConstantFP(Val.bitsToFloat(), VT);
 
2349
      else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
 
2350
        return getConstantFP(Val.bitsToDouble(), VT);
 
2351
      break;
 
2352
    case ISD::BSWAP:
 
2353
      return getConstant(Val.byteSwap(), VT);
 
2354
    case ISD::CTPOP:
 
2355
      return getConstant(Val.countPopulation(), VT);
 
2356
    case ISD::CTLZ:
 
2357
      return getConstant(Val.countLeadingZeros(), VT);
 
2358
    case ISD::CTTZ:
 
2359
      return getConstant(Val.countTrailingZeros(), VT);
 
2360
    }
 
2361
  }
 
2362
 
 
2363
  // Constant fold unary operations with a floating point constant operand.
 
2364
  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
 
2365
    APFloat V = C->getValueAPF();    // make copy
 
2366
    if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
 
2367
      switch (Opcode) {
 
2368
      case ISD::FNEG:
 
2369
        V.changeSign();
 
2370
        return getConstantFP(V, VT);
 
2371
      case ISD::FABS:
 
2372
        V.clearSign();
 
2373
        return getConstantFP(V, VT);
 
2374
      case ISD::FP_ROUND:
 
2375
      case ISD::FP_EXTEND: {
 
2376
        bool ignored;
 
2377
        // This can return overflow, underflow, or inexact; we don't care.
 
2378
        // FIXME need to be more flexible about rounding mode.
 
2379
        (void)V.convert(*EVTToAPFloatSemantics(VT),
 
2380
                        APFloat::rmNearestTiesToEven, &ignored);
 
2381
        return getConstantFP(V, VT);
 
2382
      }
 
2383
      case ISD::FP_TO_SINT:
 
2384
      case ISD::FP_TO_UINT: {
 
2385
        integerPart x[2];
 
2386
        bool ignored;
 
2387
        assert(integerPartWidth >= 64);
 
2388
        // FIXME need to be more flexible about rounding mode.
 
2389
        APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
 
2390
                              Opcode==ISD::FP_TO_SINT,
 
2391
                              APFloat::rmTowardZero, &ignored);
 
2392
        if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
 
2393
          break;
 
2394
        APInt api(VT.getSizeInBits(), 2, x);
 
2395
        return getConstant(api, VT);
 
2396
      }
 
2397
      case ISD::BIT_CONVERT:
 
2398
        if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
 
2399
          return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
 
2400
        else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
 
2401
          return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
 
2402
        break;
 
2403
      }
 
2404
    }
 
2405
  }
 
2406
 
 
2407
  unsigned OpOpcode = Operand.getNode()->getOpcode();
 
2408
  switch (Opcode) {
 
2409
  case ISD::TokenFactor:
 
2410
  case ISD::MERGE_VALUES:
 
2411
  case ISD::CONCAT_VECTORS:
 
2412
    return Operand;         // Factor, merge or concat of one node?  No need.
 
2413
  case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
 
2414
  case ISD::FP_EXTEND:
 
2415
    assert(VT.isFloatingPoint() &&
 
2416
           Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
 
2417
    if (Operand.getValueType() == VT) return Operand;  // noop conversion.
 
2418
    assert((!VT.isVector() ||
 
2419
            VT.getVectorNumElements() ==
 
2420
            Operand.getValueType().getVectorNumElements()) &&
 
2421
           "Vector element count mismatch!");
 
2422
    if (Operand.getOpcode() == ISD::UNDEF)
 
2423
      return getUNDEF(VT);
 
2424
    break;
 
2425
  case ISD::SIGN_EXTEND:
 
2426
    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
 
2427
           "Invalid SIGN_EXTEND!");
 
2428
    if (Operand.getValueType() == VT) return Operand;   // noop extension
 
2429
    assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
 
2430
           "Invalid sext node, dst < src!");
 
2431
    assert((!VT.isVector() ||
 
2432
            VT.getVectorNumElements() ==
 
2433
            Operand.getValueType().getVectorNumElements()) &&
 
2434
           "Vector element count mismatch!");
 
2435
    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
 
2436
      return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
 
2437
    break;
 
2438
  case ISD::ZERO_EXTEND:
 
2439
    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
 
2440
           "Invalid ZERO_EXTEND!");
 
2441
    if (Operand.getValueType() == VT) return Operand;   // noop extension
 
2442
    assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
 
2443
           "Invalid zext node, dst < src!");
 
2444
    assert((!VT.isVector() ||
 
2445
            VT.getVectorNumElements() ==
 
2446
            Operand.getValueType().getVectorNumElements()) &&
 
2447
           "Vector element count mismatch!");
 
2448
    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
 
2449
      return getNode(ISD::ZERO_EXTEND, DL, VT,
 
2450
                     Operand.getNode()->getOperand(0));
 
2451
    break;
 
2452
  case ISD::ANY_EXTEND:
 
2453
    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
 
2454
           "Invalid ANY_EXTEND!");
 
2455
    if (Operand.getValueType() == VT) return Operand;   // noop extension
 
2456
    assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
 
2457
           "Invalid anyext node, dst < src!");
 
2458
    assert((!VT.isVector() ||
 
2459
            VT.getVectorNumElements() ==
 
2460
            Operand.getValueType().getVectorNumElements()) &&
 
2461
           "Vector element count mismatch!");
 
2462
    if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
 
2463
      // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
 
2464
      return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
 
2465
    break;
 
2466
  case ISD::TRUNCATE:
 
2467
    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
 
2468
           "Invalid TRUNCATE!");
 
2469
    if (Operand.getValueType() == VT) return Operand;   // noop truncate
 
2470
    assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
 
2471
           "Invalid truncate node, src < dst!");
 
2472
    assert((!VT.isVector() ||
 
2473
            VT.getVectorNumElements() ==
 
2474
            Operand.getValueType().getVectorNumElements()) &&
 
2475
           "Vector element count mismatch!");
 
2476
    if (OpOpcode == ISD::TRUNCATE)
 
2477
      return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
 
2478
    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
 
2479
             OpOpcode == ISD::ANY_EXTEND) {
 
2480
      // If the source is smaller than the dest, we still need an extend.
 
2481
      if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
 
2482
            .bitsLT(VT.getScalarType()))
 
2483
        return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
 
2484
      else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
 
2485
        return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
 
2486
      else
 
2487
        return Operand.getNode()->getOperand(0);
 
2488
    }
 
2489
    break;
 
2490
  case ISD::BIT_CONVERT:
 
2491
    // Basic sanity checking.
 
2492
    assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
 
2493
           && "Cannot BIT_CONVERT between types of different sizes!");
 
2494
    if (VT == Operand.getValueType()) return Operand;  // noop conversion.
 
2495
    if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
 
2496
      return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
 
2497
    if (OpOpcode == ISD::UNDEF)
 
2498
      return getUNDEF(VT);
 
2499
    break;
 
2500
  case ISD::SCALAR_TO_VECTOR:
 
2501
    assert(VT.isVector() && !Operand.getValueType().isVector() &&
 
2502
           (VT.getVectorElementType() == Operand.getValueType() ||
 
2503
            (VT.getVectorElementType().isInteger() &&
 
2504
             Operand.getValueType().isInteger() &&
 
2505
             VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
 
2506
           "Illegal SCALAR_TO_VECTOR node!");
 
2507
    if (OpOpcode == ISD::UNDEF)
 
2508
      return getUNDEF(VT);
 
2509
    // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
 
2510
    if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
 
2511
        isa<ConstantSDNode>(Operand.getOperand(1)) &&
 
2512
        Operand.getConstantOperandVal(1) == 0 &&
 
2513
        Operand.getOperand(0).getValueType() == VT)
 
2514
      return Operand.getOperand(0);
 
2515
    break;
 
2516
  case ISD::FNEG:
 
2517
    // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
 
2518
    if (UnsafeFPMath && OpOpcode == ISD::FSUB)
 
2519
      return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
 
2520
                     Operand.getNode()->getOperand(0));
 
2521
    if (OpOpcode == ISD::FNEG)  // --X -> X
 
2522
      return Operand.getNode()->getOperand(0);
 
2523
    break;
 
2524
  case ISD::FABS:
 
2525
    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
 
2526
      return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
 
2527
    break;
 
2528
  }
 
2529
 
 
2530
  SDNode *N;
 
2531
  SDVTList VTs = getVTList(VT);
 
2532
  if (VT != MVT::Flag) { // Don't CSE flag producing nodes
 
2533
    FoldingSetNodeID ID;
 
2534
    SDValue Ops[1] = { Operand };
 
2535
    AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
 
2536
    void *IP = 0;
 
2537
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
2538
      return SDValue(E, 0);
 
2539
 
 
2540
    N = NodeAllocator.Allocate<UnarySDNode>();
 
2541
    new (N) UnarySDNode(Opcode, DL, VTs, Operand);
 
2542
    CSEMap.InsertNode(N, IP);
 
2543
  } else {
 
2544
    N = NodeAllocator.Allocate<UnarySDNode>();
 
2545
    new (N) UnarySDNode(Opcode, DL, VTs, Operand);
 
2546
  }
 
2547
 
 
2548
  AllNodes.push_back(N);
 
2549
#ifndef NDEBUG
 
2550
  VerifyNode(N);
 
2551
#endif
 
2552
  return SDValue(N, 0);
 
2553
}
 
2554
 
 
2555
SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
 
2556
                                             EVT VT,
 
2557
                                             ConstantSDNode *Cst1,
 
2558
                                             ConstantSDNode *Cst2) {
 
2559
  const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
 
2560
 
 
2561
  switch (Opcode) {
 
2562
  case ISD::ADD:  return getConstant(C1 + C2, VT);
 
2563
  case ISD::SUB:  return getConstant(C1 - C2, VT);
 
2564
  case ISD::MUL:  return getConstant(C1 * C2, VT);
 
2565
  case ISD::UDIV:
 
2566
    if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
 
2567
    break;
 
2568
  case ISD::UREM:
 
2569
    if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
 
2570
    break;
 
2571
  case ISD::SDIV:
 
2572
    if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
 
2573
    break;
 
2574
  case ISD::SREM:
 
2575
    if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
 
2576
    break;
 
2577
  case ISD::AND:  return getConstant(C1 & C2, VT);
 
2578
  case ISD::OR:   return getConstant(C1 | C2, VT);
 
2579
  case ISD::XOR:  return getConstant(C1 ^ C2, VT);
 
2580
  case ISD::SHL:  return getConstant(C1 << C2, VT);
 
2581
  case ISD::SRL:  return getConstant(C1.lshr(C2), VT);
 
2582
  case ISD::SRA:  return getConstant(C1.ashr(C2), VT);
 
2583
  case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
 
2584
  case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
 
2585
  default: break;
 
2586
  }
 
2587
 
 
2588
  return SDValue();
 
2589
}
 
2590
 
 
2591
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
 
2592
                              SDValue N1, SDValue N2) {
 
2593
  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
 
2594
  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
 
2595
  switch (Opcode) {
 
2596
  default: break;
 
2597
  case ISD::TokenFactor:
 
2598
    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
 
2599
           N2.getValueType() == MVT::Other && "Invalid token factor!");
 
2600
    // Fold trivial token factors.
 
2601
    if (N1.getOpcode() == ISD::EntryToken) return N2;
 
2602
    if (N2.getOpcode() == ISD::EntryToken) return N1;
 
2603
    if (N1 == N2) return N1;
 
2604
    break;
 
2605
  case ISD::CONCAT_VECTORS:
 
2606
    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
 
2607
    // one big BUILD_VECTOR.
 
2608
    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
 
2609
        N2.getOpcode() == ISD::BUILD_VECTOR) {
 
2610
      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
 
2611
      Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
 
2612
      return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
 
2613
    }
 
2614
    break;
 
2615
  case ISD::AND:
 
2616
    assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
 
2617
           N1.getValueType() == VT && "Binary operator types must match!");
 
2618
    // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
 
2619
    // worth handling here.
 
2620
    if (N2C && N2C->isNullValue())
 
2621
      return N2;
 
2622
    if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
 
2623
      return N1;
 
2624
    break;
 
2625
  case ISD::OR:
 
2626
  case ISD::XOR:
 
2627
  case ISD::ADD:
 
2628
  case ISD::SUB:
 
2629
    assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
 
2630
           N1.getValueType() == VT && "Binary operator types must match!");
 
2631
    // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
 
2632
    // it's worth handling here.
 
2633
    if (N2C && N2C->isNullValue())
 
2634
      return N1;
 
2635
    break;
 
2636
  case ISD::UDIV:
 
2637
  case ISD::UREM:
 
2638
  case ISD::MULHU:
 
2639
  case ISD::MULHS:
 
2640
  case ISD::MUL:
 
2641
  case ISD::SDIV:
 
2642
  case ISD::SREM:
 
2643
    assert(VT.isInteger() && "This operator does not apply to FP types!");
 
2644
    // fall through
 
2645
  case ISD::FADD:
 
2646
  case ISD::FSUB:
 
2647
  case ISD::FMUL:
 
2648
  case ISD::FDIV:
 
2649
  case ISD::FREM:
 
2650
    if (UnsafeFPMath) {
 
2651
      if (Opcode == ISD::FADD) {
 
2652
        // 0+x --> x
 
2653
        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
 
2654
          if (CFP->getValueAPF().isZero())
 
2655
            return N2;
 
2656
        // x+0 --> x
 
2657
        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
 
2658
          if (CFP->getValueAPF().isZero())
 
2659
            return N1;
 
2660
      } else if (Opcode == ISD::FSUB) {
 
2661
        // x-0 --> x
 
2662
        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
 
2663
          if (CFP->getValueAPF().isZero())
 
2664
            return N1;
 
2665
      }
 
2666
    }
 
2667
    assert(N1.getValueType() == N2.getValueType() &&
 
2668
           N1.getValueType() == VT && "Binary operator types must match!");
 
2669
    break;
 
2670
  case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
 
2671
    assert(N1.getValueType() == VT &&
 
2672
           N1.getValueType().isFloatingPoint() &&
 
2673
           N2.getValueType().isFloatingPoint() &&
 
2674
           "Invalid FCOPYSIGN!");
 
2675
    break;
 
2676
  case ISD::SHL:
 
2677
  case ISD::SRA:
 
2678
  case ISD::SRL:
 
2679
  case ISD::ROTL:
 
2680
  case ISD::ROTR:
 
2681
    assert(VT == N1.getValueType() &&
 
2682
           "Shift operators return type must be the same as their first arg");
 
2683
    assert(VT.isInteger() && N2.getValueType().isInteger() &&
 
2684
           "Shifts only work on integers");
 
2685
 
 
2686
    // Always fold shifts of i1 values so the code generator doesn't need to
 
2687
    // handle them.  Since we know the size of the shift has to be less than the
 
2688
    // size of the value, the shift/rotate count is guaranteed to be zero.
 
2689
    if (VT == MVT::i1)
 
2690
      return N1;
 
2691
    if (N2C && N2C->isNullValue())
 
2692
      return N1;
 
2693
    break;
 
2694
  case ISD::FP_ROUND_INREG: {
 
2695
    EVT EVT = cast<VTSDNode>(N2)->getVT();
 
2696
    assert(VT == N1.getValueType() && "Not an inreg round!");
 
2697
    assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
 
2698
           "Cannot FP_ROUND_INREG integer types");
 
2699
    assert(EVT.isVector() == VT.isVector() &&
 
2700
           "FP_ROUND_INREG type should be vector iff the operand "
 
2701
           "type is vector!");
 
2702
    assert((!EVT.isVector() ||
 
2703
            EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
 
2704
           "Vector element counts must match in FP_ROUND_INREG");
 
2705
    assert(EVT.bitsLE(VT) && "Not rounding down!");
 
2706
    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
 
2707
    break;
 
2708
  }
 
2709
  case ISD::FP_ROUND:
 
2710
    assert(VT.isFloatingPoint() &&
 
2711
           N1.getValueType().isFloatingPoint() &&
 
2712
           VT.bitsLE(N1.getValueType()) &&
 
2713
           isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
 
2714
    if (N1.getValueType() == VT) return N1;  // noop conversion.
 
2715
    break;
 
2716
  case ISD::AssertSext:
 
2717
  case ISD::AssertZext: {
 
2718
    EVT EVT = cast<VTSDNode>(N2)->getVT();
 
2719
    assert(VT == N1.getValueType() && "Not an inreg extend!");
 
2720
    assert(VT.isInteger() && EVT.isInteger() &&
 
2721
           "Cannot *_EXTEND_INREG FP types");
 
2722
    assert(!EVT.isVector() &&
 
2723
           "AssertSExt/AssertZExt type should be the vector element type "
 
2724
           "rather than the vector type!");
 
2725
    assert(EVT.bitsLE(VT) && "Not extending!");
 
2726
    if (VT == EVT) return N1; // noop assertion.
 
2727
    break;
 
2728
  }
 
2729
  case ISD::SIGN_EXTEND_INREG: {
 
2730
    EVT EVT = cast<VTSDNode>(N2)->getVT();
 
2731
    assert(VT == N1.getValueType() && "Not an inreg extend!");
 
2732
    assert(VT.isInteger() && EVT.isInteger() &&
 
2733
           "Cannot *_EXTEND_INREG FP types");
 
2734
    assert(EVT.isVector() == VT.isVector() &&
 
2735
           "SIGN_EXTEND_INREG type should be vector iff the operand "
 
2736
           "type is vector!");
 
2737
    assert((!EVT.isVector() ||
 
2738
            EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
 
2739
           "Vector element counts must match in SIGN_EXTEND_INREG");
 
2740
    assert(EVT.bitsLE(VT) && "Not extending!");
 
2741
    if (EVT == VT) return N1;  // Not actually extending
 
2742
 
 
2743
    if (N1C) {
 
2744
      APInt Val = N1C->getAPIntValue();
 
2745
      unsigned FromBits = EVT.getScalarType().getSizeInBits();
 
2746
      Val <<= Val.getBitWidth()-FromBits;
 
2747
      Val = Val.ashr(Val.getBitWidth()-FromBits);
 
2748
      return getConstant(Val, VT);
 
2749
    }
 
2750
    break;
 
2751
  }
 
2752
  case ISD::EXTRACT_VECTOR_ELT:
 
2753
    // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
 
2754
    if (N1.getOpcode() == ISD::UNDEF)
 
2755
      return getUNDEF(VT);
 
2756
 
 
2757
    // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
 
2758
    // expanding copies of large vectors from registers.
 
2759
    if (N2C &&
 
2760
        N1.getOpcode() == ISD::CONCAT_VECTORS &&
 
2761
        N1.getNumOperands() > 0) {
 
2762
      unsigned Factor =
 
2763
        N1.getOperand(0).getValueType().getVectorNumElements();
 
2764
      return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
 
2765
                     N1.getOperand(N2C->getZExtValue() / Factor),
 
2766
                     getConstant(N2C->getZExtValue() % Factor,
 
2767
                                 N2.getValueType()));
 
2768
    }
 
2769
 
 
2770
    // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
 
2771
    // expanding large vector constants.
 
2772
    if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
 
2773
      SDValue Elt = N1.getOperand(N2C->getZExtValue());
 
2774
      EVT VEltTy = N1.getValueType().getVectorElementType();
 
2775
      if (Elt.getValueType() != VEltTy) {
 
2776
        // If the vector element type is not legal, the BUILD_VECTOR operands
 
2777
        // are promoted and implicitly truncated.  Make that explicit here.
 
2778
        Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
 
2779
      }
 
2780
      if (VT != VEltTy) {
 
2781
        // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
 
2782
        // result is implicitly extended.
 
2783
        Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
 
2784
      }
 
2785
      return Elt;
 
2786
    }
 
2787
 
 
2788
    // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
 
2789
    // operations are lowered to scalars.
 
2790
    if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
 
2791
      // If the indices are the same, return the inserted element else
 
2792
      // if the indices are known different, extract the element from
 
2793
      // the original vector.
 
2794
      if (N1.getOperand(2) == N2) {
 
2795
        if (VT == N1.getOperand(1).getValueType())
 
2796
          return N1.getOperand(1);
 
2797
        else
 
2798
          return getSExtOrTrunc(N1.getOperand(1), DL, VT);
 
2799
      } else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
 
2800
                 isa<ConstantSDNode>(N2))
 
2801
        return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
 
2802
    }
 
2803
    break;
 
2804
  case ISD::EXTRACT_ELEMENT:
 
2805
    assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
 
2806
    assert(!N1.getValueType().isVector() && !VT.isVector() &&
 
2807
           (N1.getValueType().isInteger() == VT.isInteger()) &&
 
2808
           "Wrong types for EXTRACT_ELEMENT!");
 
2809
 
 
2810
    // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
 
2811
    // 64-bit integers into 32-bit parts.  Instead of building the extract of
 
2812
    // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
 
2813
    if (N1.getOpcode() == ISD::BUILD_PAIR)
 
2814
      return N1.getOperand(N2C->getZExtValue());
 
2815
 
 
2816
    // EXTRACT_ELEMENT of a constant int is also very common.
 
2817
    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
 
2818
      unsigned ElementSize = VT.getSizeInBits();
 
2819
      unsigned Shift = ElementSize * N2C->getZExtValue();
 
2820
      APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
 
2821
      return getConstant(ShiftedVal.trunc(ElementSize), VT);
 
2822
    }
 
2823
    break;
 
2824
  case ISD::EXTRACT_SUBVECTOR:
 
2825
    if (N1.getValueType() == VT) // Trivial extraction.
 
2826
      return N1;
 
2827
    break;
 
2828
  }
 
2829
 
 
2830
  if (N1C) {
 
2831
    if (N2C) {
 
2832
      SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
 
2833
      if (SV.getNode()) return SV;
 
2834
    } else {      // Cannonicalize constant to RHS if commutative
 
2835
      if (isCommutativeBinOp(Opcode)) {
 
2836
        std::swap(N1C, N2C);
 
2837
        std::swap(N1, N2);
 
2838
      }
 
2839
    }
 
2840
  }
 
2841
 
 
2842
  // Constant fold FP operations.
 
2843
  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
 
2844
  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
 
2845
  if (N1CFP) {
 
2846
    if (!N2CFP && isCommutativeBinOp(Opcode)) {
 
2847
      // Cannonicalize constant to RHS if commutative
 
2848
      std::swap(N1CFP, N2CFP);
 
2849
      std::swap(N1, N2);
 
2850
    } else if (N2CFP && VT != MVT::ppcf128) {
 
2851
      APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
 
2852
      APFloat::opStatus s;
 
2853
      switch (Opcode) {
 
2854
      case ISD::FADD:
 
2855
        s = V1.add(V2, APFloat::rmNearestTiesToEven);
 
2856
        if (s != APFloat::opInvalidOp)
 
2857
          return getConstantFP(V1, VT);
 
2858
        break;
 
2859
      case ISD::FSUB:
 
2860
        s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
 
2861
        if (s!=APFloat::opInvalidOp)
 
2862
          return getConstantFP(V1, VT);
 
2863
        break;
 
2864
      case ISD::FMUL:
 
2865
        s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
 
2866
        if (s!=APFloat::opInvalidOp)
 
2867
          return getConstantFP(V1, VT);
 
2868
        break;
 
2869
      case ISD::FDIV:
 
2870
        s = V1.divide(V2, APFloat::rmNearestTiesToEven);
 
2871
        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
 
2872
          return getConstantFP(V1, VT);
 
2873
        break;
 
2874
      case ISD::FREM :
 
2875
        s = V1.mod(V2, APFloat::rmNearestTiesToEven);
 
2876
        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
 
2877
          return getConstantFP(V1, VT);
 
2878
        break;
 
2879
      case ISD::FCOPYSIGN:
 
2880
        V1.copySign(V2);
 
2881
        return getConstantFP(V1, VT);
 
2882
      default: break;
 
2883
      }
 
2884
    }
 
2885
  }
 
2886
 
 
2887
  // Canonicalize an UNDEF to the RHS, even over a constant.
 
2888
  if (N1.getOpcode() == ISD::UNDEF) {
 
2889
    if (isCommutativeBinOp(Opcode)) {
 
2890
      std::swap(N1, N2);
 
2891
    } else {
 
2892
      switch (Opcode) {
 
2893
      case ISD::FP_ROUND_INREG:
 
2894
      case ISD::SIGN_EXTEND_INREG:
 
2895
      case ISD::SUB:
 
2896
      case ISD::FSUB:
 
2897
      case ISD::FDIV:
 
2898
      case ISD::FREM:
 
2899
      case ISD::SRA:
 
2900
        return N1;     // fold op(undef, arg2) -> undef
 
2901
      case ISD::UDIV:
 
2902
      case ISD::SDIV:
 
2903
      case ISD::UREM:
 
2904
      case ISD::SREM:
 
2905
      case ISD::SRL:
 
2906
      case ISD::SHL:
 
2907
        if (!VT.isVector())
 
2908
          return getConstant(0, VT);    // fold op(undef, arg2) -> 0
 
2909
        // For vectors, we can't easily build an all zero vector, just return
 
2910
        // the LHS.
 
2911
        return N2;
 
2912
      }
 
2913
    }
 
2914
  }
 
2915
 
 
2916
  // Fold a bunch of operators when the RHS is undef.
 
2917
  if (N2.getOpcode() == ISD::UNDEF) {
 
2918
    switch (Opcode) {
 
2919
    case ISD::XOR:
 
2920
      if (N1.getOpcode() == ISD::UNDEF)
 
2921
        // Handle undef ^ undef -> 0 special case. This is a common
 
2922
        // idiom (misuse).
 
2923
        return getConstant(0, VT);
 
2924
      // fallthrough
 
2925
    case ISD::ADD:
 
2926
    case ISD::ADDC:
 
2927
    case ISD::ADDE:
 
2928
    case ISD::SUB:
 
2929
    case ISD::UDIV:
 
2930
    case ISD::SDIV:
 
2931
    case ISD::UREM:
 
2932
    case ISD::SREM:
 
2933
      return N2;       // fold op(arg1, undef) -> undef
 
2934
    case ISD::FADD:
 
2935
    case ISD::FSUB:
 
2936
    case ISD::FMUL:
 
2937
    case ISD::FDIV:
 
2938
    case ISD::FREM:
 
2939
      if (UnsafeFPMath)
 
2940
        return N2;
 
2941
      break;
 
2942
    case ISD::MUL:
 
2943
    case ISD::AND:
 
2944
    case ISD::SRL:
 
2945
    case ISD::SHL:
 
2946
      if (!VT.isVector())
 
2947
        return getConstant(0, VT);  // fold op(arg1, undef) -> 0
 
2948
      // For vectors, we can't easily build an all zero vector, just return
 
2949
      // the LHS.
 
2950
      return N1;
 
2951
    case ISD::OR:
 
2952
      if (!VT.isVector())
 
2953
        return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
 
2954
      // For vectors, we can't easily build an all one vector, just return
 
2955
      // the LHS.
 
2956
      return N1;
 
2957
    case ISD::SRA:
 
2958
      return N1;
 
2959
    }
 
2960
  }
 
2961
 
 
2962
  // Memoize this node if possible.
 
2963
  SDNode *N;
 
2964
  SDVTList VTs = getVTList(VT);
 
2965
  if (VT != MVT::Flag) {
 
2966
    SDValue Ops[] = { N1, N2 };
 
2967
    FoldingSetNodeID ID;
 
2968
    AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
 
2969
    void *IP = 0;
 
2970
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
2971
      return SDValue(E, 0);
 
2972
 
 
2973
    N = NodeAllocator.Allocate<BinarySDNode>();
 
2974
    new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
 
2975
    CSEMap.InsertNode(N, IP);
 
2976
  } else {
 
2977
    N = NodeAllocator.Allocate<BinarySDNode>();
 
2978
    new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
 
2979
  }
 
2980
 
 
2981
  AllNodes.push_back(N);
 
2982
#ifndef NDEBUG
 
2983
  VerifyNode(N);
 
2984
#endif
 
2985
  return SDValue(N, 0);
 
2986
}
 
2987
 
 
2988
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
 
2989
                              SDValue N1, SDValue N2, SDValue N3) {
 
2990
  // Perform various simplifications.
 
2991
  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
 
2992
  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
 
2993
  switch (Opcode) {
 
2994
  case ISD::CONCAT_VECTORS:
 
2995
    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
 
2996
    // one big BUILD_VECTOR.
 
2997
    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
 
2998
        N2.getOpcode() == ISD::BUILD_VECTOR &&
 
2999
        N3.getOpcode() == ISD::BUILD_VECTOR) {
 
3000
      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
 
3001
      Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
 
3002
      Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
 
3003
      return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
 
3004
    }
 
3005
    break;
 
3006
  case ISD::SETCC: {
 
3007
    // Use FoldSetCC to simplify SETCC's.
 
3008
    SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
 
3009
    if (Simp.getNode()) return Simp;
 
3010
    break;
 
3011
  }
 
3012
  case ISD::SELECT:
 
3013
    if (N1C) {
 
3014
     if (N1C->getZExtValue())
 
3015
        return N2;             // select true, X, Y -> X
 
3016
      else
 
3017
        return N3;             // select false, X, Y -> Y
 
3018
    }
 
3019
 
 
3020
    if (N2 == N3) return N2;   // select C, X, X -> X
 
3021
    break;
 
3022
  case ISD::BRCOND:
 
3023
    if (N2C) {
 
3024
      if (N2C->getZExtValue()) // Unconditional branch
 
3025
        return getNode(ISD::BR, DL, MVT::Other, N1, N3);
 
3026
      else
 
3027
        return N1;         // Never-taken branch
 
3028
    }
 
3029
    break;
 
3030
  case ISD::VECTOR_SHUFFLE:
 
3031
    llvm_unreachable("should use getVectorShuffle constructor!");
 
3032
    break;
 
3033
  case ISD::BIT_CONVERT:
 
3034
    // Fold bit_convert nodes from a type to themselves.
 
3035
    if (N1.getValueType() == VT)
 
3036
      return N1;
 
3037
    break;
 
3038
  }
 
3039
 
 
3040
  // Memoize node if it doesn't produce a flag.
 
3041
  SDNode *N;
 
3042
  SDVTList VTs = getVTList(VT);
 
3043
  if (VT != MVT::Flag) {
 
3044
    SDValue Ops[] = { N1, N2, N3 };
 
3045
    FoldingSetNodeID ID;
 
3046
    AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
 
3047
    void *IP = 0;
 
3048
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
3049
      return SDValue(E, 0);
 
3050
 
 
3051
    N = NodeAllocator.Allocate<TernarySDNode>();
 
3052
    new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
 
3053
    CSEMap.InsertNode(N, IP);
 
3054
  } else {
 
3055
    N = NodeAllocator.Allocate<TernarySDNode>();
 
3056
    new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
 
3057
  }
 
3058
 
 
3059
  AllNodes.push_back(N);
 
3060
#ifndef NDEBUG
 
3061
  VerifyNode(N);
 
3062
#endif
 
3063
  return SDValue(N, 0);
 
3064
}
 
3065
 
 
3066
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
 
3067
                              SDValue N1, SDValue N2, SDValue N3,
 
3068
                              SDValue N4) {
 
3069
  SDValue Ops[] = { N1, N2, N3, N4 };
 
3070
  return getNode(Opcode, DL, VT, Ops, 4);
 
3071
}
 
3072
 
 
3073
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
 
3074
                              SDValue N1, SDValue N2, SDValue N3,
 
3075
                              SDValue N4, SDValue N5) {
 
3076
  SDValue Ops[] = { N1, N2, N3, N4, N5 };
 
3077
  return getNode(Opcode, DL, VT, Ops, 5);
 
3078
}
 
3079
 
 
3080
/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
 
3081
/// the incoming stack arguments to be loaded from the stack.
 
3082
SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
 
3083
  SmallVector<SDValue, 8> ArgChains;
 
3084
 
 
3085
  // Include the original chain at the beginning of the list. When this is
 
3086
  // used by target LowerCall hooks, this helps legalize find the
 
3087
  // CALLSEQ_BEGIN node.
 
3088
  ArgChains.push_back(Chain);
 
3089
 
 
3090
  // Add a chain value for each stack argument.
 
3091
  for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
 
3092
       UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
 
3093
    if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
 
3094
      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
 
3095
        if (FI->getIndex() < 0)
 
3096
          ArgChains.push_back(SDValue(L, 1));
 
3097
 
 
3098
  // Build a tokenfactor for all the chains.
 
3099
  return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
 
3100
                 &ArgChains[0], ArgChains.size());
 
3101
}
 
3102
 
 
3103
/// getMemsetValue - Vectorized representation of the memset value
 
3104
/// operand.
 
3105
static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
 
3106
                              DebugLoc dl) {
 
3107
  unsigned NumBits = VT.getScalarType().getSizeInBits();
 
3108
  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
 
3109
    APInt Val = APInt(NumBits, C->getZExtValue() & 255);
 
3110
    unsigned Shift = 8;
 
3111
    for (unsigned i = NumBits; i > 8; i >>= 1) {
 
3112
      Val = (Val << Shift) | Val;
 
3113
      Shift <<= 1;
 
3114
    }
 
3115
    if (VT.isInteger())
 
3116
      return DAG.getConstant(Val, VT);
 
3117
    return DAG.getConstantFP(APFloat(Val), VT);
 
3118
  }
 
3119
 
 
3120
  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
 
3121
  Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
 
3122
  unsigned Shift = 8;
 
3123
  for (unsigned i = NumBits; i > 8; i >>= 1) {
 
3124
    Value = DAG.getNode(ISD::OR, dl, VT,
 
3125
                        DAG.getNode(ISD::SHL, dl, VT, Value,
 
3126
                                    DAG.getConstant(Shift,
 
3127
                                                    TLI.getShiftAmountTy())),
 
3128
                        Value);
 
3129
    Shift <<= 1;
 
3130
  }
 
3131
 
 
3132
  return Value;
 
3133
}
 
3134
 
 
3135
/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
 
3136
/// used when a memcpy is turned into a memset when the source is a constant
 
3137
/// string ptr.
 
3138
static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
 
3139
                                  const TargetLowering &TLI,
 
3140
                                  std::string &Str, unsigned Offset) {
 
3141
  // Handle vector with all elements zero.
 
3142
  if (Str.empty()) {
 
3143
    if (VT.isInteger())
 
3144
      return DAG.getConstant(0, VT);
 
3145
    unsigned NumElts = VT.getVectorNumElements();
 
3146
    MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
 
3147
    return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
 
3148
                       DAG.getConstant(0,
 
3149
                       EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
 
3150
  }
 
3151
 
 
3152
  assert(!VT.isVector() && "Can't handle vector type here!");
 
3153
  unsigned NumBits = VT.getSizeInBits();
 
3154
  unsigned MSB = NumBits / 8;
 
3155
  uint64_t Val = 0;
 
3156
  if (TLI.isLittleEndian())
 
3157
    Offset = Offset + MSB - 1;
 
3158
  for (unsigned i = 0; i != MSB; ++i) {
 
3159
    Val = (Val << 8) | (unsigned char)Str[Offset];
 
3160
    Offset += TLI.isLittleEndian() ? -1 : 1;
 
3161
  }
 
3162
  return DAG.getConstant(Val, VT);
 
3163
}
 
3164
 
 
3165
/// getMemBasePlusOffset - Returns base and offset node for the
 
3166
///
 
3167
static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
 
3168
                                      SelectionDAG &DAG) {
 
3169
  EVT VT = Base.getValueType();
 
3170
  return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
 
3171
                     VT, Base, DAG.getConstant(Offset, VT));
 
3172
}
 
3173
 
 
3174
/// isMemSrcFromString - Returns true if memcpy source is a string constant.
 
3175
///
 
3176
static bool isMemSrcFromString(SDValue Src, std::string &Str) {
 
3177
  unsigned SrcDelta = 0;
 
3178
  GlobalAddressSDNode *G = NULL;
 
3179
  if (Src.getOpcode() == ISD::GlobalAddress)
 
3180
    G = cast<GlobalAddressSDNode>(Src);
 
3181
  else if (Src.getOpcode() == ISD::ADD &&
 
3182
           Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
 
3183
           Src.getOperand(1).getOpcode() == ISD::Constant) {
 
3184
    G = cast<GlobalAddressSDNode>(Src.getOperand(0));
 
3185
    SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
 
3186
  }
 
3187
  if (!G)
 
3188
    return false;
 
3189
 
 
3190
  GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
 
3191
  if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
 
3192
    return true;
 
3193
 
 
3194
  return false;
 
3195
}
 
3196
 
 
3197
/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
 
3198
/// to replace the memset / memcpy is below the threshold. It also returns the
 
3199
/// types of the sequence of memory ops to perform memset / memcpy.
 
3200
static
 
3201
bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
 
3202
                              SDValue Dst, SDValue Src,
 
3203
                              unsigned Limit, uint64_t Size, unsigned &Align,
 
3204
                              std::string &Str, bool &isSrcStr,
 
3205
                              SelectionDAG &DAG,
 
3206
                              const TargetLowering &TLI) {
 
3207
  isSrcStr = isMemSrcFromString(Src, Str);
 
3208
  bool isSrcConst = isa<ConstantSDNode>(Src);
 
3209
  EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
 
3210
  bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
 
3211
  if (VT != MVT::iAny) {
 
3212
    const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
 
3213
    unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
 
3214
    // If source is a string constant, this will require an unaligned load.
 
3215
    if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
 
3216
      if (Dst.getOpcode() != ISD::FrameIndex) {
 
3217
        // Can't change destination alignment. It requires a unaligned store.
 
3218
        if (AllowUnalign)
 
3219
          VT = MVT::iAny;
 
3220
      } else {
 
3221
        int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
 
3222
        MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
 
3223
        if (MFI->isFixedObjectIndex(FI)) {
 
3224
          // Can't change destination alignment. It requires a unaligned store.
 
3225
          if (AllowUnalign)
 
3226
            VT = MVT::iAny;
 
3227
        } else {
 
3228
          // Give the stack frame object a larger alignment if needed.
 
3229
          if (MFI->getObjectAlignment(FI) < NewAlign)
 
3230
            MFI->setObjectAlignment(FI, NewAlign);
 
3231
          Align = NewAlign;
 
3232
        }
 
3233
      }
 
3234
    }
 
3235
  }
 
3236
 
 
3237
  if (VT == MVT::iAny) {
 
3238
    if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
 
3239
      VT = MVT::i64;
 
3240
    } else {
 
3241
      switch (Align & 7) {
 
3242
      case 0:  VT = MVT::i64; break;
 
3243
      case 4:  VT = MVT::i32; break;
 
3244
      case 2:  VT = MVT::i16; break;
 
3245
      default: VT = MVT::i8;  break;
 
3246
      }
 
3247
    }
 
3248
 
 
3249
    MVT LVT = MVT::i64;
 
3250
    while (!TLI.isTypeLegal(LVT))
 
3251
      LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
 
3252
    assert(LVT.isInteger());
 
3253
 
 
3254
    if (VT.bitsGT(LVT))
 
3255
      VT = LVT;
 
3256
  }
 
3257
 
 
3258
  unsigned NumMemOps = 0;
 
3259
  while (Size != 0) {
 
3260
    unsigned VTSize = VT.getSizeInBits() / 8;
 
3261
    while (VTSize > Size) {
 
3262
      // For now, only use non-vector load / store's for the left-over pieces.
 
3263
      if (VT.isVector()) {
 
3264
        VT = MVT::i64;
 
3265
        while (!TLI.isTypeLegal(VT))
 
3266
          VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
 
3267
        VTSize = VT.getSizeInBits() / 8;
 
3268
      } else {
 
3269
        // This can result in a type that is not legal on the target, e.g.
 
3270
        // 1 or 2 bytes on PPC.
 
3271
        VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
 
3272
        VTSize >>= 1;
 
3273
      }
 
3274
    }
 
3275
 
 
3276
    if (++NumMemOps > Limit)
 
3277
      return false;
 
3278
    MemOps.push_back(VT);
 
3279
    Size -= VTSize;
 
3280
  }
 
3281
 
 
3282
  return true;
 
3283
}
 
3284
 
 
3285
static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
 
3286
                                         SDValue Chain, SDValue Dst,
 
3287
                                         SDValue Src, uint64_t Size,
 
3288
                                         unsigned Align, bool AlwaysInline,
 
3289
                                         const Value *DstSV, uint64_t DstSVOff,
 
3290
                                         const Value *SrcSV, uint64_t SrcSVOff){
 
3291
  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
 
3292
 
 
3293
  // Expand memcpy to a series of load and store ops if the size operand falls
 
3294
  // below a certain threshold.
 
3295
  std::vector<EVT> MemOps;
 
3296
  uint64_t Limit = -1ULL;
 
3297
  if (!AlwaysInline)
 
3298
    Limit = TLI.getMaxStoresPerMemcpy();
 
3299
  unsigned DstAlign = Align;  // Destination alignment can change.
 
3300
  std::string Str;
 
3301
  bool CopyFromStr;
 
3302
  if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
 
3303
                                Str, CopyFromStr, DAG, TLI))
 
3304
    return SDValue();
 
3305
 
 
3306
 
 
3307
  bool isZeroStr = CopyFromStr && Str.empty();
 
3308
  SmallVector<SDValue, 8> OutChains;
 
3309
  unsigned NumMemOps = MemOps.size();
 
3310
  uint64_t SrcOff = 0, DstOff = 0;
 
3311
  for (unsigned i = 0; i != NumMemOps; ++i) {
 
3312
    EVT VT = MemOps[i];
 
3313
    unsigned VTSize = VT.getSizeInBits() / 8;
 
3314
    SDValue Value, Store;
 
3315
 
 
3316
    if (CopyFromStr && (isZeroStr || !VT.isVector())) {
 
3317
      // It's unlikely a store of a vector immediate can be done in a single
 
3318
      // instruction. It would require a load from a constantpool first.
 
3319
      // We also handle store a vector with all zero's.
 
3320
      // FIXME: Handle other cases where store of vector immediate is done in
 
3321
      // a single instruction.
 
3322
      Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
 
3323
      Store = DAG.getStore(Chain, dl, Value,
 
3324
                           getMemBasePlusOffset(Dst, DstOff, DAG),
 
3325
                           DstSV, DstSVOff + DstOff, false, false, DstAlign);
 
3326
    } else {
 
3327
      // The type might not be legal for the target.  This should only happen
 
3328
      // if the type is smaller than a legal type, as on PPC, so the right
 
3329
      // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
 
3330
      // to Load/Store if NVT==VT.
 
3331
      // FIXME does the case above also need this?
 
3332
      EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
 
3333
      assert(NVT.bitsGE(VT));
 
3334
      Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
 
3335
                             getMemBasePlusOffset(Src, SrcOff, DAG),
 
3336
                             SrcSV, SrcSVOff + SrcOff, VT, false, false, Align);
 
3337
      Store = DAG.getTruncStore(Chain, dl, Value,
 
3338
                                getMemBasePlusOffset(Dst, DstOff, DAG),
 
3339
                                DstSV, DstSVOff + DstOff, VT, false, false,
 
3340
                                DstAlign);
 
3341
    }
 
3342
    OutChains.push_back(Store);
 
3343
    SrcOff += VTSize;
 
3344
    DstOff += VTSize;
 
3345
  }
 
3346
 
 
3347
  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
 
3348
                     &OutChains[0], OutChains.size());
 
3349
}
 
3350
 
 
3351
static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
 
3352
                                          SDValue Chain, SDValue Dst,
 
3353
                                          SDValue Src, uint64_t Size,
 
3354
                                          unsigned Align, bool AlwaysInline,
 
3355
                                          const Value *DstSV, uint64_t DstSVOff,
 
3356
                                          const Value *SrcSV, uint64_t SrcSVOff){
 
3357
  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
 
3358
 
 
3359
  // Expand memmove to a series of load and store ops if the size operand falls
 
3360
  // below a certain threshold.
 
3361
  std::vector<EVT> MemOps;
 
3362
  uint64_t Limit = -1ULL;
 
3363
  if (!AlwaysInline)
 
3364
    Limit = TLI.getMaxStoresPerMemmove();
 
3365
  unsigned DstAlign = Align;  // Destination alignment can change.
 
3366
  std::string Str;
 
3367
  bool CopyFromStr;
 
3368
  if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
 
3369
                                Str, CopyFromStr, DAG, TLI))
 
3370
    return SDValue();
 
3371
 
 
3372
  uint64_t SrcOff = 0, DstOff = 0;
 
3373
 
 
3374
  SmallVector<SDValue, 8> LoadValues;
 
3375
  SmallVector<SDValue, 8> LoadChains;
 
3376
  SmallVector<SDValue, 8> OutChains;
 
3377
  unsigned NumMemOps = MemOps.size();
 
3378
  for (unsigned i = 0; i < NumMemOps; i++) {
 
3379
    EVT VT = MemOps[i];
 
3380
    unsigned VTSize = VT.getSizeInBits() / 8;
 
3381
    SDValue Value, Store;
 
3382
 
 
3383
    Value = DAG.getLoad(VT, dl, Chain,
 
3384
                        getMemBasePlusOffset(Src, SrcOff, DAG),
 
3385
                        SrcSV, SrcSVOff + SrcOff, false, false, Align);
 
3386
    LoadValues.push_back(Value);
 
3387
    LoadChains.push_back(Value.getValue(1));
 
3388
    SrcOff += VTSize;
 
3389
  }
 
3390
  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
 
3391
                      &LoadChains[0], LoadChains.size());
 
3392
  OutChains.clear();
 
3393
  for (unsigned i = 0; i < NumMemOps; i++) {
 
3394
    EVT VT = MemOps[i];
 
3395
    unsigned VTSize = VT.getSizeInBits() / 8;
 
3396
    SDValue Value, Store;
 
3397
 
 
3398
    Store = DAG.getStore(Chain, dl, LoadValues[i],
 
3399
                         getMemBasePlusOffset(Dst, DstOff, DAG),
 
3400
                         DstSV, DstSVOff + DstOff, false, false, DstAlign);
 
3401
    OutChains.push_back(Store);
 
3402
    DstOff += VTSize;
 
3403
  }
 
3404
 
 
3405
  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
 
3406
                     &OutChains[0], OutChains.size());
 
3407
}
 
3408
 
 
3409
static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
 
3410
                                 SDValue Chain, SDValue Dst,
 
3411
                                 SDValue Src, uint64_t Size,
 
3412
                                 unsigned Align,
 
3413
                                 const Value *DstSV, uint64_t DstSVOff) {
 
3414
  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
 
3415
 
 
3416
  // Expand memset to a series of load/store ops if the size operand
 
3417
  // falls below a certain threshold.
 
3418
  std::vector<EVT> MemOps;
 
3419
  std::string Str;
 
3420
  bool CopyFromStr;
 
3421
  if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
 
3422
                                Size, Align, Str, CopyFromStr, DAG, TLI))
 
3423
    return SDValue();
 
3424
 
 
3425
  SmallVector<SDValue, 8> OutChains;
 
3426
  uint64_t DstOff = 0;
 
3427
 
 
3428
  unsigned NumMemOps = MemOps.size();
 
3429
  for (unsigned i = 0; i < NumMemOps; i++) {
 
3430
    EVT VT = MemOps[i];
 
3431
    unsigned VTSize = VT.getSizeInBits() / 8;
 
3432
    SDValue Value = getMemsetValue(Src, VT, DAG, dl);
 
3433
    SDValue Store = DAG.getStore(Chain, dl, Value,
 
3434
                                 getMemBasePlusOffset(Dst, DstOff, DAG),
 
3435
                                 DstSV, DstSVOff + DstOff, false, false, 0);
 
3436
    OutChains.push_back(Store);
 
3437
    DstOff += VTSize;
 
3438
  }
 
3439
 
 
3440
  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
 
3441
                     &OutChains[0], OutChains.size());
 
3442
}
 
3443
 
 
3444
SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
 
3445
                                SDValue Src, SDValue Size,
 
3446
                                unsigned Align, bool AlwaysInline,
 
3447
                                const Value *DstSV, uint64_t DstSVOff,
 
3448
                                const Value *SrcSV, uint64_t SrcSVOff) {
 
3449
 
 
3450
  // Check to see if we should lower the memcpy to loads and stores first.
 
3451
  // For cases within the target-specified limits, this is the best choice.
 
3452
  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
 
3453
  if (ConstantSize) {
 
3454
    // Memcpy with size zero? Just return the original chain.
 
3455
    if (ConstantSize->isNullValue())
 
3456
      return Chain;
 
3457
 
 
3458
    SDValue Result =
 
3459
      getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
 
3460
                              ConstantSize->getZExtValue(),
 
3461
                              Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
 
3462
    if (Result.getNode())
 
3463
      return Result;
 
3464
  }
 
3465
 
 
3466
  // Then check to see if we should lower the memcpy with target-specific
 
3467
  // code. If the target chooses to do this, this is the next best.
 
3468
  SDValue Result =
 
3469
    TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
 
3470
                                AlwaysInline,
 
3471
                                DstSV, DstSVOff, SrcSV, SrcSVOff);
 
3472
  if (Result.getNode())
 
3473
    return Result;
 
3474
 
 
3475
  // If we really need inline code and the target declined to provide it,
 
3476
  // use a (potentially long) sequence of loads and stores.
 
3477
  if (AlwaysInline) {
 
3478
    assert(ConstantSize && "AlwaysInline requires a constant size!");
 
3479
    return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
 
3480
                                   ConstantSize->getZExtValue(), Align, true,
 
3481
                                   DstSV, DstSVOff, SrcSV, SrcSVOff);
 
3482
  }
 
3483
 
 
3484
  // Emit a library call.
 
3485
  TargetLowering::ArgListTy Args;
 
3486
  TargetLowering::ArgListEntry Entry;
 
3487
  Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
 
3488
  Entry.Node = Dst; Args.push_back(Entry);
 
3489
  Entry.Node = Src; Args.push_back(Entry);
 
3490
  Entry.Node = Size; Args.push_back(Entry);
 
3491
  // FIXME: pass in DebugLoc
 
3492
  std::pair<SDValue,SDValue> CallResult =
 
3493
    TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
 
3494
                    false, false, false, false, 0,
 
3495
                    TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
 
3496
                    /*isReturnValueUsed=*/false,
 
3497
                    getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
 
3498
                                      TLI.getPointerTy()),
 
3499
                    Args, *this, dl);
 
3500
  return CallResult.second;
 
3501
}
 
3502
 
 
3503
SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
 
3504
                                 SDValue Src, SDValue Size,
 
3505
                                 unsigned Align,
 
3506
                                 const Value *DstSV, uint64_t DstSVOff,
 
3507
                                 const Value *SrcSV, uint64_t SrcSVOff) {
 
3508
 
 
3509
  // Check to see if we should lower the memmove to loads and stores first.
 
3510
  // For cases within the target-specified limits, this is the best choice.
 
3511
  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
 
3512
  if (ConstantSize) {
 
3513
    // Memmove with size zero? Just return the original chain.
 
3514
    if (ConstantSize->isNullValue())
 
3515
      return Chain;
 
3516
 
 
3517
    SDValue Result =
 
3518
      getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
 
3519
                               ConstantSize->getZExtValue(),
 
3520
                               Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
 
3521
    if (Result.getNode())
 
3522
      return Result;
 
3523
  }
 
3524
 
 
3525
  // Then check to see if we should lower the memmove with target-specific
 
3526
  // code. If the target chooses to do this, this is the next best.
 
3527
  SDValue Result =
 
3528
    TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
 
3529
                                 DstSV, DstSVOff, SrcSV, SrcSVOff);
 
3530
  if (Result.getNode())
 
3531
    return Result;
 
3532
 
 
3533
  // Emit a library call.
 
3534
  TargetLowering::ArgListTy Args;
 
3535
  TargetLowering::ArgListEntry Entry;
 
3536
  Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
 
3537
  Entry.Node = Dst; Args.push_back(Entry);
 
3538
  Entry.Node = Src; Args.push_back(Entry);
 
3539
  Entry.Node = Size; Args.push_back(Entry);
 
3540
  // FIXME:  pass in DebugLoc
 
3541
  std::pair<SDValue,SDValue> CallResult =
 
3542
    TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
 
3543
                    false, false, false, false, 0,
 
3544
                    TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
 
3545
                    /*isReturnValueUsed=*/false,
 
3546
                    getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
 
3547
                                      TLI.getPointerTy()),
 
3548
                    Args, *this, dl);
 
3549
  return CallResult.second;
 
3550
}
 
3551
 
 
3552
SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
 
3553
                                SDValue Src, SDValue Size,
 
3554
                                unsigned Align,
 
3555
                                const Value *DstSV, uint64_t DstSVOff) {
 
3556
 
 
3557
  // Check to see if we should lower the memset to stores first.
 
3558
  // For cases within the target-specified limits, this is the best choice.
 
3559
  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
 
3560
  if (ConstantSize) {
 
3561
    // Memset with size zero? Just return the original chain.
 
3562
    if (ConstantSize->isNullValue())
 
3563
      return Chain;
 
3564
 
 
3565
    SDValue Result =
 
3566
      getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
 
3567
                      Align, DstSV, DstSVOff);
 
3568
    if (Result.getNode())
 
3569
      return Result;
 
3570
  }
 
3571
 
 
3572
  // Then check to see if we should lower the memset with target-specific
 
3573
  // code. If the target chooses to do this, this is the next best.
 
3574
  SDValue Result =
 
3575
    TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
 
3576
                                DstSV, DstSVOff);
 
3577
  if (Result.getNode())
 
3578
    return Result;
 
3579
 
 
3580
  // Emit a library call.
 
3581
  const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
 
3582
  TargetLowering::ArgListTy Args;
 
3583
  TargetLowering::ArgListEntry Entry;
 
3584
  Entry.Node = Dst; Entry.Ty = IntPtrTy;
 
3585
  Args.push_back(Entry);
 
3586
  // Extend or truncate the argument to be an i32 value for the call.
 
3587
  if (Src.getValueType().bitsGT(MVT::i32))
 
3588
    Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
 
3589
  else
 
3590
    Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
 
3591
  Entry.Node = Src;
 
3592
  Entry.Ty = Type::getInt32Ty(*getContext());
 
3593
  Entry.isSExt = true;
 
3594
  Args.push_back(Entry);
 
3595
  Entry.Node = Size;
 
3596
  Entry.Ty = IntPtrTy;
 
3597
  Entry.isSExt = false;
 
3598
  Args.push_back(Entry);
 
3599
  // FIXME: pass in DebugLoc
 
3600
  std::pair<SDValue,SDValue> CallResult =
 
3601
    TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
 
3602
                    false, false, false, false, 0,
 
3603
                    TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
 
3604
                    /*isReturnValueUsed=*/false,
 
3605
                    getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
 
3606
                                      TLI.getPointerTy()),
 
3607
                    Args, *this, dl);
 
3608
  return CallResult.second;
 
3609
}
 
3610
 
 
3611
SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
 
3612
                                SDValue Chain,
 
3613
                                SDValue Ptr, SDValue Cmp,
 
3614
                                SDValue Swp, const Value* PtrVal,
 
3615
                                unsigned Alignment) {
 
3616
  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
 
3617
    Alignment = getEVTAlignment(MemVT);
 
3618
 
 
3619
  // Check if the memory reference references a frame index
 
3620
  if (!PtrVal)
 
3621
    if (const FrameIndexSDNode *FI =
 
3622
          dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
 
3623
      PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
 
3624
 
 
3625
  MachineFunction &MF = getMachineFunction();
 
3626
  unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
 
3627
 
 
3628
  // For now, atomics are considered to be volatile always.
 
3629
  Flags |= MachineMemOperand::MOVolatile;
 
3630
 
 
3631
  MachineMemOperand *MMO =
 
3632
    MF.getMachineMemOperand(PtrVal, Flags, 0,
 
3633
                            MemVT.getStoreSize(), Alignment);
 
3634
 
 
3635
  return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
 
3636
}
 
3637
 
 
3638
SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
 
3639
                                SDValue Chain,
 
3640
                                SDValue Ptr, SDValue Cmp,
 
3641
                                SDValue Swp, MachineMemOperand *MMO) {
 
3642
  assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
 
3643
  assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
 
3644
 
 
3645
  EVT VT = Cmp.getValueType();
 
3646
 
 
3647
  SDVTList VTs = getVTList(VT, MVT::Other);
 
3648
  FoldingSetNodeID ID;
 
3649
  ID.AddInteger(MemVT.getRawBits());
 
3650
  SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
 
3651
  AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
 
3652
  void* IP = 0;
 
3653
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
 
3654
    cast<AtomicSDNode>(E)->refineAlignment(MMO);
 
3655
    return SDValue(E, 0);
 
3656
  }
 
3657
  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
 
3658
  new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Cmp, Swp, MMO);
 
3659
  CSEMap.InsertNode(N, IP);
 
3660
  AllNodes.push_back(N);
 
3661
  return SDValue(N, 0);
 
3662
}
 
3663
 
 
3664
SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
 
3665
                                SDValue Chain,
 
3666
                                SDValue Ptr, SDValue Val,
 
3667
                                const Value* PtrVal,
 
3668
                                unsigned Alignment) {
 
3669
  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
 
3670
    Alignment = getEVTAlignment(MemVT);
 
3671
 
 
3672
  // Check if the memory reference references a frame index
 
3673
  if (!PtrVal)
 
3674
    if (const FrameIndexSDNode *FI =
 
3675
          dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
 
3676
      PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
 
3677
 
 
3678
  MachineFunction &MF = getMachineFunction();
 
3679
  unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
 
3680
 
 
3681
  // For now, atomics are considered to be volatile always.
 
3682
  Flags |= MachineMemOperand::MOVolatile;
 
3683
 
 
3684
  MachineMemOperand *MMO =
 
3685
    MF.getMachineMemOperand(PtrVal, Flags, 0,
 
3686
                            MemVT.getStoreSize(), Alignment);
 
3687
 
 
3688
  return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
 
3689
}
 
3690
 
 
3691
SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
 
3692
                                SDValue Chain,
 
3693
                                SDValue Ptr, SDValue Val,
 
3694
                                MachineMemOperand *MMO) {
 
3695
  assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
 
3696
          Opcode == ISD::ATOMIC_LOAD_SUB ||
 
3697
          Opcode == ISD::ATOMIC_LOAD_AND ||
 
3698
          Opcode == ISD::ATOMIC_LOAD_OR ||
 
3699
          Opcode == ISD::ATOMIC_LOAD_XOR ||
 
3700
          Opcode == ISD::ATOMIC_LOAD_NAND ||
 
3701
          Opcode == ISD::ATOMIC_LOAD_MIN ||
 
3702
          Opcode == ISD::ATOMIC_LOAD_MAX ||
 
3703
          Opcode == ISD::ATOMIC_LOAD_UMIN ||
 
3704
          Opcode == ISD::ATOMIC_LOAD_UMAX ||
 
3705
          Opcode == ISD::ATOMIC_SWAP) &&
 
3706
         "Invalid Atomic Op");
 
3707
 
 
3708
  EVT VT = Val.getValueType();
 
3709
 
 
3710
  SDVTList VTs = getVTList(VT, MVT::Other);
 
3711
  FoldingSetNodeID ID;
 
3712
  ID.AddInteger(MemVT.getRawBits());
 
3713
  SDValue Ops[] = {Chain, Ptr, Val};
 
3714
  AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
 
3715
  void* IP = 0;
 
3716
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
 
3717
    cast<AtomicSDNode>(E)->refineAlignment(MMO);
 
3718
    return SDValue(E, 0);
 
3719
  }
 
3720
  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
 
3721
  new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Val, MMO);
 
3722
  CSEMap.InsertNode(N, IP);
 
3723
  AllNodes.push_back(N);
 
3724
  return SDValue(N, 0);
 
3725
}
 
3726
 
 
3727
/// getMergeValues - Create a MERGE_VALUES node from the given operands.
 
3728
/// Allowed to return something different (and simpler) if Simplify is true.
 
3729
SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
 
3730
                                     DebugLoc dl) {
 
3731
  if (NumOps == 1)
 
3732
    return Ops[0];
 
3733
 
 
3734
  SmallVector<EVT, 4> VTs;
 
3735
  VTs.reserve(NumOps);
 
3736
  for (unsigned i = 0; i < NumOps; ++i)
 
3737
    VTs.push_back(Ops[i].getValueType());
 
3738
  return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
 
3739
                 Ops, NumOps);
 
3740
}
 
3741
 
 
3742
SDValue
 
3743
SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
 
3744
                                  const EVT *VTs, unsigned NumVTs,
 
3745
                                  const SDValue *Ops, unsigned NumOps,
 
3746
                                  EVT MemVT, const Value *srcValue, int SVOff,
 
3747
                                  unsigned Align, bool Vol,
 
3748
                                  bool ReadMem, bool WriteMem) {
 
3749
  return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
 
3750
                             MemVT, srcValue, SVOff, Align, Vol,
 
3751
                             ReadMem, WriteMem);
 
3752
}
 
3753
 
 
3754
SDValue
 
3755
SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
 
3756
                                  const SDValue *Ops, unsigned NumOps,
 
3757
                                  EVT MemVT, const Value *srcValue, int SVOff,
 
3758
                                  unsigned Align, bool Vol,
 
3759
                                  bool ReadMem, bool WriteMem) {
 
3760
  if (Align == 0)  // Ensure that codegen never sees alignment 0
 
3761
    Align = getEVTAlignment(MemVT);
 
3762
 
 
3763
  MachineFunction &MF = getMachineFunction();
 
3764
  unsigned Flags = 0;
 
3765
  if (WriteMem)
 
3766
    Flags |= MachineMemOperand::MOStore;
 
3767
  if (ReadMem)
 
3768
    Flags |= MachineMemOperand::MOLoad;
 
3769
  if (Vol)
 
3770
    Flags |= MachineMemOperand::MOVolatile;
 
3771
  MachineMemOperand *MMO =
 
3772
    MF.getMachineMemOperand(srcValue, Flags, SVOff,
 
3773
                            MemVT.getStoreSize(), Align);
 
3774
 
 
3775
  return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
 
3776
}
 
3777
 
 
3778
SDValue
 
3779
SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
 
3780
                                  const SDValue *Ops, unsigned NumOps,
 
3781
                                  EVT MemVT, MachineMemOperand *MMO) {
 
3782
  assert((Opcode == ISD::INTRINSIC_VOID ||
 
3783
          Opcode == ISD::INTRINSIC_W_CHAIN ||
 
3784
          (Opcode <= INT_MAX &&
 
3785
           (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
 
3786
         "Opcode is not a memory-accessing opcode!");
 
3787
 
 
3788
  // Memoize the node unless it returns a flag.
 
3789
  MemIntrinsicSDNode *N;
 
3790
  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
 
3791
    FoldingSetNodeID ID;
 
3792
    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
 
3793
    void *IP = 0;
 
3794
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
 
3795
      cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
 
3796
      return SDValue(E, 0);
 
3797
    }
 
3798
 
 
3799
    N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
 
3800
    new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
 
3801
    CSEMap.InsertNode(N, IP);
 
3802
  } else {
 
3803
    N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
 
3804
    new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
 
3805
  }
 
3806
  AllNodes.push_back(N);
 
3807
  return SDValue(N, 0);
 
3808
}
 
3809
 
 
3810
SDValue
 
3811
SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
 
3812
                      ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
 
3813
                      SDValue Ptr, SDValue Offset,
 
3814
                      const Value *SV, int SVOffset, EVT MemVT,
 
3815
                      bool isVolatile, bool isNonTemporal,
 
3816
                      unsigned Alignment) {
 
3817
  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
 
3818
    Alignment = getEVTAlignment(VT);
 
3819
 
 
3820
  // Check if the memory reference references a frame index
 
3821
  if (!SV)
 
3822
    if (const FrameIndexSDNode *FI =
 
3823
          dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
 
3824
      SV = PseudoSourceValue::getFixedStack(FI->getIndex());
 
3825
 
 
3826
  MachineFunction &MF = getMachineFunction();
 
3827
  unsigned Flags = MachineMemOperand::MOLoad;
 
3828
  if (isVolatile)
 
3829
    Flags |= MachineMemOperand::MOVolatile;
 
3830
  if (isNonTemporal)
 
3831
    Flags |= MachineMemOperand::MONonTemporal;
 
3832
  MachineMemOperand *MMO =
 
3833
    MF.getMachineMemOperand(SV, Flags, SVOffset,
 
3834
                            MemVT.getStoreSize(), Alignment);
 
3835
  return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
 
3836
}
 
3837
 
 
3838
SDValue
 
3839
SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
 
3840
                      ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
 
3841
                      SDValue Ptr, SDValue Offset, EVT MemVT,
 
3842
                      MachineMemOperand *MMO) {
 
3843
  if (VT == MemVT) {
 
3844
    ExtType = ISD::NON_EXTLOAD;
 
3845
  } else if (ExtType == ISD::NON_EXTLOAD) {
 
3846
    assert(VT == MemVT && "Non-extending load from different memory type!");
 
3847
  } else {
 
3848
    // Extending load.
 
3849
    assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
 
3850
           "Should only be an extending load, not truncating!");
 
3851
    assert(VT.isInteger() == MemVT.isInteger() &&
 
3852
           "Cannot convert from FP to Int or Int -> FP!");
 
3853
    assert(VT.isVector() == MemVT.isVector() &&
 
3854
           "Cannot use trunc store to convert to or from a vector!");
 
3855
    assert((!VT.isVector() ||
 
3856
            VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
 
3857
           "Cannot use trunc store to change the number of vector elements!");
 
3858
  }
 
3859
 
 
3860
  bool Indexed = AM != ISD::UNINDEXED;
 
3861
  assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
 
3862
         "Unindexed load with an offset!");
 
3863
 
 
3864
  SDVTList VTs = Indexed ?
 
3865
    getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
 
3866
  SDValue Ops[] = { Chain, Ptr, Offset };
 
3867
  FoldingSetNodeID ID;
 
3868
  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
 
3869
  ID.AddInteger(MemVT.getRawBits());
 
3870
  ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
 
3871
                                     MMO->isNonTemporal()));
 
3872
  void *IP = 0;
 
3873
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
 
3874
    cast<LoadSDNode>(E)->refineAlignment(MMO);
 
3875
    return SDValue(E, 0);
 
3876
  }
 
3877
  SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
 
3878
  new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, MemVT, MMO);
 
3879
  CSEMap.InsertNode(N, IP);
 
3880
  AllNodes.push_back(N);
 
3881
  return SDValue(N, 0);
 
3882
}
 
3883
 
 
3884
SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
 
3885
                              SDValue Chain, SDValue Ptr,
 
3886
                              const Value *SV, int SVOffset,
 
3887
                              bool isVolatile, bool isNonTemporal,
 
3888
                              unsigned Alignment) {
 
3889
  SDValue Undef = getUNDEF(Ptr.getValueType());
 
3890
  return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
 
3891
                 SV, SVOffset, VT, isVolatile, isNonTemporal, Alignment);
 
3892
}
 
3893
 
 
3894
SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
 
3895
                                 SDValue Chain, SDValue Ptr,
 
3896
                                 const Value *SV,
 
3897
                                 int SVOffset, EVT MemVT,
 
3898
                                 bool isVolatile, bool isNonTemporal,
 
3899
                                 unsigned Alignment) {
 
3900
  SDValue Undef = getUNDEF(Ptr.getValueType());
 
3901
  return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
 
3902
                 SV, SVOffset, MemVT, isVolatile, isNonTemporal, Alignment);
 
3903
}
 
3904
 
 
3905
SDValue
 
3906
SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
 
3907
                             SDValue Offset, ISD::MemIndexedMode AM) {
 
3908
  LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
 
3909
  assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
 
3910
         "Load is already a indexed load!");
 
3911
  return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
 
3912
                 LD->getChain(), Base, Offset, LD->getSrcValue(),
 
3913
                 LD->getSrcValueOffset(), LD->getMemoryVT(),
 
3914
                 LD->isVolatile(), LD->isNonTemporal(), LD->getAlignment());
 
3915
}
 
3916
 
 
3917
SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
 
3918
                               SDValue Ptr, const Value *SV, int SVOffset,
 
3919
                               bool isVolatile, bool isNonTemporal,
 
3920
                               unsigned Alignment) {
 
3921
  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
 
3922
    Alignment = getEVTAlignment(Val.getValueType());
 
3923
 
 
3924
  // Check if the memory reference references a frame index
 
3925
  if (!SV)
 
3926
    if (const FrameIndexSDNode *FI =
 
3927
          dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
 
3928
      SV = PseudoSourceValue::getFixedStack(FI->getIndex());
 
3929
 
 
3930
  MachineFunction &MF = getMachineFunction();
 
3931
  unsigned Flags = MachineMemOperand::MOStore;
 
3932
  if (isVolatile)
 
3933
    Flags |= MachineMemOperand::MOVolatile;
 
3934
  if (isNonTemporal)
 
3935
    Flags |= MachineMemOperand::MONonTemporal;
 
3936
  MachineMemOperand *MMO =
 
3937
    MF.getMachineMemOperand(SV, Flags, SVOffset,
 
3938
                            Val.getValueType().getStoreSize(), Alignment);
 
3939
 
 
3940
  return getStore(Chain, dl, Val, Ptr, MMO);
 
3941
}
 
3942
 
 
3943
SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
 
3944
                               SDValue Ptr, MachineMemOperand *MMO) {
 
3945
  EVT VT = Val.getValueType();
 
3946
  SDVTList VTs = getVTList(MVT::Other);
 
3947
  SDValue Undef = getUNDEF(Ptr.getValueType());
 
3948
  SDValue Ops[] = { Chain, Val, Ptr, Undef };
 
3949
  FoldingSetNodeID ID;
 
3950
  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
 
3951
  ID.AddInteger(VT.getRawBits());
 
3952
  ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
 
3953
                                     MMO->isNonTemporal()));
 
3954
  void *IP = 0;
 
3955
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
 
3956
    cast<StoreSDNode>(E)->refineAlignment(MMO);
 
3957
    return SDValue(E, 0);
 
3958
  }
 
3959
  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
 
3960
  new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, VT, MMO);
 
3961
  CSEMap.InsertNode(N, IP);
 
3962
  AllNodes.push_back(N);
 
3963
  return SDValue(N, 0);
 
3964
}
 
3965
 
 
3966
SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
 
3967
                                    SDValue Ptr, const Value *SV,
 
3968
                                    int SVOffset, EVT SVT,
 
3969
                                    bool isVolatile, bool isNonTemporal,
 
3970
                                    unsigned Alignment) {
 
3971
  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
 
3972
    Alignment = getEVTAlignment(SVT);
 
3973
 
 
3974
  // Check if the memory reference references a frame index
 
3975
  if (!SV)
 
3976
    if (const FrameIndexSDNode *FI =
 
3977
          dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
 
3978
      SV = PseudoSourceValue::getFixedStack(FI->getIndex());
 
3979
 
 
3980
  MachineFunction &MF = getMachineFunction();
 
3981
  unsigned Flags = MachineMemOperand::MOStore;
 
3982
  if (isVolatile)
 
3983
    Flags |= MachineMemOperand::MOVolatile;
 
3984
  if (isNonTemporal)
 
3985
    Flags |= MachineMemOperand::MONonTemporal;
 
3986
  MachineMemOperand *MMO =
 
3987
    MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
 
3988
 
 
3989
  return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
 
3990
}
 
3991
 
 
3992
SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
 
3993
                                    SDValue Ptr, EVT SVT,
 
3994
                                    MachineMemOperand *MMO) {
 
3995
  EVT VT = Val.getValueType();
 
3996
 
 
3997
  if (VT == SVT)
 
3998
    return getStore(Chain, dl, Val, Ptr, MMO);
 
3999
 
 
4000
  assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
 
4001
         "Should only be a truncating store, not extending!");
 
4002
  assert(VT.isInteger() == SVT.isInteger() &&
 
4003
         "Can't do FP-INT conversion!");
 
4004
  assert(VT.isVector() == SVT.isVector() &&
 
4005
         "Cannot use trunc store to convert to or from a vector!");
 
4006
  assert((!VT.isVector() ||
 
4007
          VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
 
4008
         "Cannot use trunc store to change the number of vector elements!");
 
4009
 
 
4010
  SDVTList VTs = getVTList(MVT::Other);
 
4011
  SDValue Undef = getUNDEF(Ptr.getValueType());
 
4012
  SDValue Ops[] = { Chain, Val, Ptr, Undef };
 
4013
  FoldingSetNodeID ID;
 
4014
  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
 
4015
  ID.AddInteger(SVT.getRawBits());
 
4016
  ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
 
4017
                                     MMO->isNonTemporal()));
 
4018
  void *IP = 0;
 
4019
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
 
4020
    cast<StoreSDNode>(E)->refineAlignment(MMO);
 
4021
    return SDValue(E, 0);
 
4022
  }
 
4023
  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
 
4024
  new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, SVT, MMO);
 
4025
  CSEMap.InsertNode(N, IP);
 
4026
  AllNodes.push_back(N);
 
4027
  return SDValue(N, 0);
 
4028
}
 
4029
 
 
4030
SDValue
 
4031
SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
 
4032
                              SDValue Offset, ISD::MemIndexedMode AM) {
 
4033
  StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
 
4034
  assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
 
4035
         "Store is already a indexed store!");
 
4036
  SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
 
4037
  SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
 
4038
  FoldingSetNodeID ID;
 
4039
  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
 
4040
  ID.AddInteger(ST->getMemoryVT().getRawBits());
 
4041
  ID.AddInteger(ST->getRawSubclassData());
 
4042
  void *IP = 0;
 
4043
  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
4044
    return SDValue(E, 0);
 
4045
 
 
4046
  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
 
4047
  new (N) StoreSDNode(Ops, dl, VTs, AM,
 
4048
                      ST->isTruncatingStore(), ST->getMemoryVT(),
 
4049
                      ST->getMemOperand());
 
4050
  CSEMap.InsertNode(N, IP);
 
4051
  AllNodes.push_back(N);
 
4052
  return SDValue(N, 0);
 
4053
}
 
4054
 
 
4055
SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
 
4056
                               SDValue Chain, SDValue Ptr,
 
4057
                               SDValue SV) {
 
4058
  SDValue Ops[] = { Chain, Ptr, SV };
 
4059
  return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
 
4060
}
 
4061
 
 
4062
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
 
4063
                              const SDUse *Ops, unsigned NumOps) {
 
4064
  switch (NumOps) {
 
4065
  case 0: return getNode(Opcode, DL, VT);
 
4066
  case 1: return getNode(Opcode, DL, VT, Ops[0]);
 
4067
  case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
 
4068
  case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
 
4069
  default: break;
 
4070
  }
 
4071
 
 
4072
  // Copy from an SDUse array into an SDValue array for use with
 
4073
  // the regular getNode logic.
 
4074
  SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
 
4075
  return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
 
4076
}
 
4077
 
 
4078
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
 
4079
                              const SDValue *Ops, unsigned NumOps) {
 
4080
  switch (NumOps) {
 
4081
  case 0: return getNode(Opcode, DL, VT);
 
4082
  case 1: return getNode(Opcode, DL, VT, Ops[0]);
 
4083
  case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
 
4084
  case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
 
4085
  default: break;
 
4086
  }
 
4087
 
 
4088
  switch (Opcode) {
 
4089
  default: break;
 
4090
  case ISD::SELECT_CC: {
 
4091
    assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
 
4092
    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
 
4093
           "LHS and RHS of condition must have same type!");
 
4094
    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
 
4095
           "True and False arms of SelectCC must have same type!");
 
4096
    assert(Ops[2].getValueType() == VT &&
 
4097
           "select_cc node must be of same type as true and false value!");
 
4098
    break;
 
4099
  }
 
4100
  case ISD::BR_CC: {
 
4101
    assert(NumOps == 5 && "BR_CC takes 5 operands!");
 
4102
    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
 
4103
           "LHS/RHS of comparison should match types!");
 
4104
    break;
 
4105
  }
 
4106
  }
 
4107
 
 
4108
  // Memoize nodes.
 
4109
  SDNode *N;
 
4110
  SDVTList VTs = getVTList(VT);
 
4111
 
 
4112
  if (VT != MVT::Flag) {
 
4113
    FoldingSetNodeID ID;
 
4114
    AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
 
4115
    void *IP = 0;
 
4116
 
 
4117
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
4118
      return SDValue(E, 0);
 
4119
 
 
4120
    N = NodeAllocator.Allocate<SDNode>();
 
4121
    new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
 
4122
    CSEMap.InsertNode(N, IP);
 
4123
  } else {
 
4124
    N = NodeAllocator.Allocate<SDNode>();
 
4125
    new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
 
4126
  }
 
4127
 
 
4128
  AllNodes.push_back(N);
 
4129
#ifndef NDEBUG
 
4130
  VerifyNode(N);
 
4131
#endif
 
4132
  return SDValue(N, 0);
 
4133
}
 
4134
 
 
4135
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
 
4136
                              const std::vector<EVT> &ResultTys,
 
4137
                              const SDValue *Ops, unsigned NumOps) {
 
4138
  return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
 
4139
                 Ops, NumOps);
 
4140
}
 
4141
 
 
4142
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
 
4143
                              const EVT *VTs, unsigned NumVTs,
 
4144
                              const SDValue *Ops, unsigned NumOps) {
 
4145
  if (NumVTs == 1)
 
4146
    return getNode(Opcode, DL, VTs[0], Ops, NumOps);
 
4147
  return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
 
4148
}
 
4149
 
 
4150
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
 
4151
                              const SDValue *Ops, unsigned NumOps) {
 
4152
  if (VTList.NumVTs == 1)
 
4153
    return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
 
4154
 
 
4155
#if 0
 
4156
  switch (Opcode) {
 
4157
  // FIXME: figure out how to safely handle things like
 
4158
  // int foo(int x) { return 1 << (x & 255); }
 
4159
  // int bar() { return foo(256); }
 
4160
  case ISD::SRA_PARTS:
 
4161
  case ISD::SRL_PARTS:
 
4162
  case ISD::SHL_PARTS:
 
4163
    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
 
4164
        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
 
4165
      return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
 
4166
    else if (N3.getOpcode() == ISD::AND)
 
4167
      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
 
4168
        // If the and is only masking out bits that cannot effect the shift,
 
4169
        // eliminate the and.
 
4170
        unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
 
4171
        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
 
4172
          return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
 
4173
      }
 
4174
    break;
 
4175
  }
 
4176
#endif
 
4177
 
 
4178
  // Memoize the node unless it returns a flag.
 
4179
  SDNode *N;
 
4180
  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
 
4181
    FoldingSetNodeID ID;
 
4182
    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
 
4183
    void *IP = 0;
 
4184
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
4185
      return SDValue(E, 0);
 
4186
 
 
4187
    if (NumOps == 1) {
 
4188
      N = NodeAllocator.Allocate<UnarySDNode>();
 
4189
      new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
 
4190
    } else if (NumOps == 2) {
 
4191
      N = NodeAllocator.Allocate<BinarySDNode>();
 
4192
      new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
 
4193
    } else if (NumOps == 3) {
 
4194
      N = NodeAllocator.Allocate<TernarySDNode>();
 
4195
      new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
 
4196
    } else {
 
4197
      N = NodeAllocator.Allocate<SDNode>();
 
4198
      new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
 
4199
    }
 
4200
    CSEMap.InsertNode(N, IP);
 
4201
  } else {
 
4202
    if (NumOps == 1) {
 
4203
      N = NodeAllocator.Allocate<UnarySDNode>();
 
4204
      new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
 
4205
    } else if (NumOps == 2) {
 
4206
      N = NodeAllocator.Allocate<BinarySDNode>();
 
4207
      new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
 
4208
    } else if (NumOps == 3) {
 
4209
      N = NodeAllocator.Allocate<TernarySDNode>();
 
4210
      new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
 
4211
    } else {
 
4212
      N = NodeAllocator.Allocate<SDNode>();
 
4213
      new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
 
4214
    }
 
4215
  }
 
4216
  AllNodes.push_back(N);
 
4217
#ifndef NDEBUG
 
4218
  VerifyNode(N);
 
4219
#endif
 
4220
  return SDValue(N, 0);
 
4221
}
 
4222
 
 
4223
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
 
4224
  return getNode(Opcode, DL, VTList, 0, 0);
 
4225
}
 
4226
 
 
4227
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
 
4228
                              SDValue N1) {
 
4229
  SDValue Ops[] = { N1 };
 
4230
  return getNode(Opcode, DL, VTList, Ops, 1);
 
4231
}
 
4232
 
 
4233
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
 
4234
                              SDValue N1, SDValue N2) {
 
4235
  SDValue Ops[] = { N1, N2 };
 
4236
  return getNode(Opcode, DL, VTList, Ops, 2);
 
4237
}
 
4238
 
 
4239
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
 
4240
                              SDValue N1, SDValue N2, SDValue N3) {
 
4241
  SDValue Ops[] = { N1, N2, N3 };
 
4242
  return getNode(Opcode, DL, VTList, Ops, 3);
 
4243
}
 
4244
 
 
4245
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
 
4246
                              SDValue N1, SDValue N2, SDValue N3,
 
4247
                              SDValue N4) {
 
4248
  SDValue Ops[] = { N1, N2, N3, N4 };
 
4249
  return getNode(Opcode, DL, VTList, Ops, 4);
 
4250
}
 
4251
 
 
4252
SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
 
4253
                              SDValue N1, SDValue N2, SDValue N3,
 
4254
                              SDValue N4, SDValue N5) {
 
4255
  SDValue Ops[] = { N1, N2, N3, N4, N5 };
 
4256
  return getNode(Opcode, DL, VTList, Ops, 5);
 
4257
}
 
4258
 
 
4259
SDVTList SelectionDAG::getVTList(EVT VT) {
 
4260
  return makeVTList(SDNode::getValueTypeList(VT), 1);
 
4261
}
 
4262
 
 
4263
SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
 
4264
  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
 
4265
       E = VTList.rend(); I != E; ++I)
 
4266
    if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
 
4267
      return *I;
 
4268
 
 
4269
  EVT *Array = Allocator.Allocate<EVT>(2);
 
4270
  Array[0] = VT1;
 
4271
  Array[1] = VT2;
 
4272
  SDVTList Result = makeVTList(Array, 2);
 
4273
  VTList.push_back(Result);
 
4274
  return Result;
 
4275
}
 
4276
 
 
4277
SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
 
4278
  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
 
4279
       E = VTList.rend(); I != E; ++I)
 
4280
    if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
 
4281
                          I->VTs[2] == VT3)
 
4282
      return *I;
 
4283
 
 
4284
  EVT *Array = Allocator.Allocate<EVT>(3);
 
4285
  Array[0] = VT1;
 
4286
  Array[1] = VT2;
 
4287
  Array[2] = VT3;
 
4288
  SDVTList Result = makeVTList(Array, 3);
 
4289
  VTList.push_back(Result);
 
4290
  return Result;
 
4291
}
 
4292
 
 
4293
SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
 
4294
  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
 
4295
       E = VTList.rend(); I != E; ++I)
 
4296
    if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
 
4297
                          I->VTs[2] == VT3 && I->VTs[3] == VT4)
 
4298
      return *I;
 
4299
 
 
4300
  EVT *Array = Allocator.Allocate<EVT>(4);
 
4301
  Array[0] = VT1;
 
4302
  Array[1] = VT2;
 
4303
  Array[2] = VT3;
 
4304
  Array[3] = VT4;
 
4305
  SDVTList Result = makeVTList(Array, 4);
 
4306
  VTList.push_back(Result);
 
4307
  return Result;
 
4308
}
 
4309
 
 
4310
SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
 
4311
  switch (NumVTs) {
 
4312
    case 0: llvm_unreachable("Cannot have nodes without results!");
 
4313
    case 1: return getVTList(VTs[0]);
 
4314
    case 2: return getVTList(VTs[0], VTs[1]);
 
4315
    case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
 
4316
    case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
 
4317
    default: break;
 
4318
  }
 
4319
 
 
4320
  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
 
4321
       E = VTList.rend(); I != E; ++I) {
 
4322
    if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
 
4323
      continue;
 
4324
 
 
4325
    bool NoMatch = false;
 
4326
    for (unsigned i = 2; i != NumVTs; ++i)
 
4327
      if (VTs[i] != I->VTs[i]) {
 
4328
        NoMatch = true;
 
4329
        break;
 
4330
      }
 
4331
    if (!NoMatch)
 
4332
      return *I;
 
4333
  }
 
4334
 
 
4335
  EVT *Array = Allocator.Allocate<EVT>(NumVTs);
 
4336
  std::copy(VTs, VTs+NumVTs, Array);
 
4337
  SDVTList Result = makeVTList(Array, NumVTs);
 
4338
  VTList.push_back(Result);
 
4339
  return Result;
 
4340
}
 
4341
 
 
4342
 
 
4343
/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
 
4344
/// specified operands.  If the resultant node already exists in the DAG,
 
4345
/// this does not modify the specified node, instead it returns the node that
 
4346
/// already exists.  If the resultant node does not exist in the DAG, the
 
4347
/// input node is returned.  As a degenerate case, if you specify the same
 
4348
/// input operands as the node already has, the input node is returned.
 
4349
SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
 
4350
  SDNode *N = InN.getNode();
 
4351
  assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
 
4352
 
 
4353
  // Check to see if there is no change.
 
4354
  if (Op == N->getOperand(0)) return InN;
 
4355
 
 
4356
  // See if the modified node already exists.
 
4357
  void *InsertPos = 0;
 
4358
  if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
 
4359
    return SDValue(Existing, InN.getResNo());
 
4360
 
 
4361
  // Nope it doesn't.  Remove the node from its current place in the maps.
 
4362
  if (InsertPos)
 
4363
    if (!RemoveNodeFromCSEMaps(N))
 
4364
      InsertPos = 0;
 
4365
 
 
4366
  // Now we update the operands.
 
4367
  N->OperandList[0].set(Op);
 
4368
 
 
4369
  // If this gets put into a CSE map, add it.
 
4370
  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
 
4371
  return InN;
 
4372
}
 
4373
 
 
4374
SDValue SelectionDAG::
 
4375
UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
 
4376
  SDNode *N = InN.getNode();
 
4377
  assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
 
4378
 
 
4379
  // Check to see if there is no change.
 
4380
  if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
 
4381
    return InN;   // No operands changed, just return the input node.
 
4382
 
 
4383
  // See if the modified node already exists.
 
4384
  void *InsertPos = 0;
 
4385
  if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
 
4386
    return SDValue(Existing, InN.getResNo());
 
4387
 
 
4388
  // Nope it doesn't.  Remove the node from its current place in the maps.
 
4389
  if (InsertPos)
 
4390
    if (!RemoveNodeFromCSEMaps(N))
 
4391
      InsertPos = 0;
 
4392
 
 
4393
  // Now we update the operands.
 
4394
  if (N->OperandList[0] != Op1)
 
4395
    N->OperandList[0].set(Op1);
 
4396
  if (N->OperandList[1] != Op2)
 
4397
    N->OperandList[1].set(Op2);
 
4398
 
 
4399
  // If this gets put into a CSE map, add it.
 
4400
  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
 
4401
  return InN;
 
4402
}
 
4403
 
 
4404
SDValue SelectionDAG::
 
4405
UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
 
4406
  SDValue Ops[] = { Op1, Op2, Op3 };
 
4407
  return UpdateNodeOperands(N, Ops, 3);
 
4408
}
 
4409
 
 
4410
SDValue SelectionDAG::
 
4411
UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
 
4412
                   SDValue Op3, SDValue Op4) {
 
4413
  SDValue Ops[] = { Op1, Op2, Op3, Op4 };
 
4414
  return UpdateNodeOperands(N, Ops, 4);
 
4415
}
 
4416
 
 
4417
SDValue SelectionDAG::
 
4418
UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
 
4419
                   SDValue Op3, SDValue Op4, SDValue Op5) {
 
4420
  SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
 
4421
  return UpdateNodeOperands(N, Ops, 5);
 
4422
}
 
4423
 
 
4424
SDValue SelectionDAG::
 
4425
UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
 
4426
  SDNode *N = InN.getNode();
 
4427
  assert(N->getNumOperands() == NumOps &&
 
4428
         "Update with wrong number of operands");
 
4429
 
 
4430
  // Check to see if there is no change.
 
4431
  bool AnyChange = false;
 
4432
  for (unsigned i = 0; i != NumOps; ++i) {
 
4433
    if (Ops[i] != N->getOperand(i)) {
 
4434
      AnyChange = true;
 
4435
      break;
 
4436
    }
 
4437
  }
 
4438
 
 
4439
  // No operands changed, just return the input node.
 
4440
  if (!AnyChange) return InN;
 
4441
 
 
4442
  // See if the modified node already exists.
 
4443
  void *InsertPos = 0;
 
4444
  if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
 
4445
    return SDValue(Existing, InN.getResNo());
 
4446
 
 
4447
  // Nope it doesn't.  Remove the node from its current place in the maps.
 
4448
  if (InsertPos)
 
4449
    if (!RemoveNodeFromCSEMaps(N))
 
4450
      InsertPos = 0;
 
4451
 
 
4452
  // Now we update the operands.
 
4453
  for (unsigned i = 0; i != NumOps; ++i)
 
4454
    if (N->OperandList[i] != Ops[i])
 
4455
      N->OperandList[i].set(Ops[i]);
 
4456
 
 
4457
  // If this gets put into a CSE map, add it.
 
4458
  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
 
4459
  return InN;
 
4460
}
 
4461
 
 
4462
/// DropOperands - Release the operands and set this node to have
 
4463
/// zero operands.
 
4464
void SDNode::DropOperands() {
 
4465
  // Unlike the code in MorphNodeTo that does this, we don't need to
 
4466
  // watch for dead nodes here.
 
4467
  for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
 
4468
    SDUse &Use = *I++;
 
4469
    Use.set(SDValue());
 
4470
  }
 
4471
}
 
4472
 
 
4473
/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
 
4474
/// machine opcode.
 
4475
///
 
4476
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4477
                                   EVT VT) {
 
4478
  SDVTList VTs = getVTList(VT);
 
4479
  return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
 
4480
}
 
4481
 
 
4482
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4483
                                   EVT VT, SDValue Op1) {
 
4484
  SDVTList VTs = getVTList(VT);
 
4485
  SDValue Ops[] = { Op1 };
 
4486
  return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
 
4487
}
 
4488
 
 
4489
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4490
                                   EVT VT, SDValue Op1,
 
4491
                                   SDValue Op2) {
 
4492
  SDVTList VTs = getVTList(VT);
 
4493
  SDValue Ops[] = { Op1, Op2 };
 
4494
  return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
 
4495
}
 
4496
 
 
4497
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4498
                                   EVT VT, SDValue Op1,
 
4499
                                   SDValue Op2, SDValue Op3) {
 
4500
  SDVTList VTs = getVTList(VT);
 
4501
  SDValue Ops[] = { Op1, Op2, Op3 };
 
4502
  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
 
4503
}
 
4504
 
 
4505
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4506
                                   EVT VT, const SDValue *Ops,
 
4507
                                   unsigned NumOps) {
 
4508
  SDVTList VTs = getVTList(VT);
 
4509
  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
 
4510
}
 
4511
 
 
4512
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4513
                                   EVT VT1, EVT VT2, const SDValue *Ops,
 
4514
                                   unsigned NumOps) {
 
4515
  SDVTList VTs = getVTList(VT1, VT2);
 
4516
  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
 
4517
}
 
4518
 
 
4519
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4520
                                   EVT VT1, EVT VT2) {
 
4521
  SDVTList VTs = getVTList(VT1, VT2);
 
4522
  return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
 
4523
}
 
4524
 
 
4525
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4526
                                   EVT VT1, EVT VT2, EVT VT3,
 
4527
                                   const SDValue *Ops, unsigned NumOps) {
 
4528
  SDVTList VTs = getVTList(VT1, VT2, VT3);
 
4529
  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
 
4530
}
 
4531
 
 
4532
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4533
                                   EVT VT1, EVT VT2, EVT VT3, EVT VT4,
 
4534
                                   const SDValue *Ops, unsigned NumOps) {
 
4535
  SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
 
4536
  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
 
4537
}
 
4538
 
 
4539
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4540
                                   EVT VT1, EVT VT2,
 
4541
                                   SDValue Op1) {
 
4542
  SDVTList VTs = getVTList(VT1, VT2);
 
4543
  SDValue Ops[] = { Op1 };
 
4544
  return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
 
4545
}
 
4546
 
 
4547
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4548
                                   EVT VT1, EVT VT2,
 
4549
                                   SDValue Op1, SDValue Op2) {
 
4550
  SDVTList VTs = getVTList(VT1, VT2);
 
4551
  SDValue Ops[] = { Op1, Op2 };
 
4552
  return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
 
4553
}
 
4554
 
 
4555
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4556
                                   EVT VT1, EVT VT2,
 
4557
                                   SDValue Op1, SDValue Op2,
 
4558
                                   SDValue Op3) {
 
4559
  SDVTList VTs = getVTList(VT1, VT2);
 
4560
  SDValue Ops[] = { Op1, Op2, Op3 };
 
4561
  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
 
4562
}
 
4563
 
 
4564
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4565
                                   EVT VT1, EVT VT2, EVT VT3,
 
4566
                                   SDValue Op1, SDValue Op2,
 
4567
                                   SDValue Op3) {
 
4568
  SDVTList VTs = getVTList(VT1, VT2, VT3);
 
4569
  SDValue Ops[] = { Op1, Op2, Op3 };
 
4570
  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
 
4571
}
 
4572
 
 
4573
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 
4574
                                   SDVTList VTs, const SDValue *Ops,
 
4575
                                   unsigned NumOps) {
 
4576
  N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
 
4577
  // Reset the NodeID to -1.
 
4578
  N->setNodeId(-1);
 
4579
  return N;
 
4580
}
 
4581
 
 
4582
/// MorphNodeTo - This *mutates* the specified node to have the specified
 
4583
/// return type, opcode, and operands.
 
4584
///
 
4585
/// Note that MorphNodeTo returns the resultant node.  If there is already a
 
4586
/// node of the specified opcode and operands, it returns that node instead of
 
4587
/// the current one.  Note that the DebugLoc need not be the same.
 
4588
///
 
4589
/// Using MorphNodeTo is faster than creating a new node and swapping it in
 
4590
/// with ReplaceAllUsesWith both because it often avoids allocating a new
 
4591
/// node, and because it doesn't require CSE recalculation for any of
 
4592
/// the node's users.
 
4593
///
 
4594
SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
 
4595
                                  SDVTList VTs, const SDValue *Ops,
 
4596
                                  unsigned NumOps) {
 
4597
  // If an identical node already exists, use it.
 
4598
  void *IP = 0;
 
4599
  if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
 
4600
    FoldingSetNodeID ID;
 
4601
    AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
 
4602
    if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
 
4603
      return ON;
 
4604
  }
 
4605
 
 
4606
  if (!RemoveNodeFromCSEMaps(N))
 
4607
    IP = 0;
 
4608
 
 
4609
  // Start the morphing.
 
4610
  N->NodeType = Opc;
 
4611
  N->ValueList = VTs.VTs;
 
4612
  N->NumValues = VTs.NumVTs;
 
4613
 
 
4614
  // Clear the operands list, updating used nodes to remove this from their
 
4615
  // use list.  Keep track of any operands that become dead as a result.
 
4616
  SmallPtrSet<SDNode*, 16> DeadNodeSet;
 
4617
  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
 
4618
    SDUse &Use = *I++;
 
4619
    SDNode *Used = Use.getNode();
 
4620
    Use.set(SDValue());
 
4621
    if (Used->use_empty())
 
4622
      DeadNodeSet.insert(Used);
 
4623
  }
 
4624
 
 
4625
  if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
 
4626
    // Initialize the memory references information.
 
4627
    MN->setMemRefs(0, 0);
 
4628
    // If NumOps is larger than the # of operands we can have in a
 
4629
    // MachineSDNode, reallocate the operand list.
 
4630
    if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
 
4631
      if (MN->OperandsNeedDelete)
 
4632
        delete[] MN->OperandList;
 
4633
      if (NumOps > array_lengthof(MN->LocalOperands))
 
4634
        // We're creating a final node that will live unmorphed for the
 
4635
        // remainder of the current SelectionDAG iteration, so we can allocate
 
4636
        // the operands directly out of a pool with no recycling metadata.
 
4637
        MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
 
4638
                        Ops, NumOps);
 
4639
      else
 
4640
        MN->InitOperands(MN->LocalOperands, Ops, NumOps);
 
4641
      MN->OperandsNeedDelete = false;
 
4642
    } else
 
4643
      MN->InitOperands(MN->OperandList, Ops, NumOps);
 
4644
  } else {
 
4645
    // If NumOps is larger than the # of operands we currently have, reallocate
 
4646
    // the operand list.
 
4647
    if (NumOps > N->NumOperands) {
 
4648
      if (N->OperandsNeedDelete)
 
4649
        delete[] N->OperandList;
 
4650
      N->InitOperands(new SDUse[NumOps], Ops, NumOps);
 
4651
      N->OperandsNeedDelete = true;
 
4652
    } else
 
4653
      N->InitOperands(N->OperandList, Ops, NumOps);
 
4654
  }
 
4655
 
 
4656
  // Delete any nodes that are still dead after adding the uses for the
 
4657
  // new operands.
 
4658
  if (!DeadNodeSet.empty()) {
 
4659
    SmallVector<SDNode *, 16> DeadNodes;
 
4660
    for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
 
4661
         E = DeadNodeSet.end(); I != E; ++I)
 
4662
      if ((*I)->use_empty())
 
4663
        DeadNodes.push_back(*I);
 
4664
    RemoveDeadNodes(DeadNodes);
 
4665
  }
 
4666
 
 
4667
  if (IP)
 
4668
    CSEMap.InsertNode(N, IP);   // Memoize the new node.
 
4669
  return N;
 
4670
}
 
4671
 
 
4672
 
 
4673
/// getMachineNode - These are used for target selectors to create a new node
 
4674
/// with specified return type(s), MachineInstr opcode, and operands.
 
4675
///
 
4676
/// Note that getMachineNode returns the resultant node.  If there is already a
 
4677
/// node of the specified opcode and operands, it returns that node instead of
 
4678
/// the current one.
 
4679
MachineSDNode *
 
4680
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
 
4681
  SDVTList VTs = getVTList(VT);
 
4682
  return getMachineNode(Opcode, dl, VTs, 0, 0);
 
4683
}
 
4684
 
 
4685
MachineSDNode *
 
4686
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
 
4687
  SDVTList VTs = getVTList(VT);
 
4688
  SDValue Ops[] = { Op1 };
 
4689
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4690
}
 
4691
 
 
4692
MachineSDNode *
 
4693
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
 
4694
                             SDValue Op1, SDValue Op2) {
 
4695
  SDVTList VTs = getVTList(VT);
 
4696
  SDValue Ops[] = { Op1, Op2 };
 
4697
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4698
}
 
4699
 
 
4700
MachineSDNode *
 
4701
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
 
4702
                             SDValue Op1, SDValue Op2, SDValue Op3) {
 
4703
  SDVTList VTs = getVTList(VT);
 
4704
  SDValue Ops[] = { Op1, Op2, Op3 };
 
4705
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4706
}
 
4707
 
 
4708
MachineSDNode *
 
4709
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
 
4710
                             const SDValue *Ops, unsigned NumOps) {
 
4711
  SDVTList VTs = getVTList(VT);
 
4712
  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
 
4713
}
 
4714
 
 
4715
MachineSDNode *
 
4716
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
 
4717
  SDVTList VTs = getVTList(VT1, VT2);
 
4718
  return getMachineNode(Opcode, dl, VTs, 0, 0);
 
4719
}
 
4720
 
 
4721
MachineSDNode *
 
4722
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4723
                             EVT VT1, EVT VT2, SDValue Op1) {
 
4724
  SDVTList VTs = getVTList(VT1, VT2);
 
4725
  SDValue Ops[] = { Op1 };
 
4726
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4727
}
 
4728
 
 
4729
MachineSDNode *
 
4730
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4731
                             EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
 
4732
  SDVTList VTs = getVTList(VT1, VT2);
 
4733
  SDValue Ops[] = { Op1, Op2 };
 
4734
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4735
}
 
4736
 
 
4737
MachineSDNode *
 
4738
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4739
                             EVT VT1, EVT VT2, SDValue Op1,
 
4740
                             SDValue Op2, SDValue Op3) {
 
4741
  SDVTList VTs = getVTList(VT1, VT2);
 
4742
  SDValue Ops[] = { Op1, Op2, Op3 };
 
4743
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4744
}
 
4745
 
 
4746
MachineSDNode *
 
4747
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4748
                             EVT VT1, EVT VT2,
 
4749
                             const SDValue *Ops, unsigned NumOps) {
 
4750
  SDVTList VTs = getVTList(VT1, VT2);
 
4751
  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
 
4752
}
 
4753
 
 
4754
MachineSDNode *
 
4755
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4756
                             EVT VT1, EVT VT2, EVT VT3,
 
4757
                             SDValue Op1, SDValue Op2) {
 
4758
  SDVTList VTs = getVTList(VT1, VT2, VT3);
 
4759
  SDValue Ops[] = { Op1, Op2 };
 
4760
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4761
}
 
4762
 
 
4763
MachineSDNode *
 
4764
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4765
                             EVT VT1, EVT VT2, EVT VT3,
 
4766
                             SDValue Op1, SDValue Op2, SDValue Op3) {
 
4767
  SDVTList VTs = getVTList(VT1, VT2, VT3);
 
4768
  SDValue Ops[] = { Op1, Op2, Op3 };
 
4769
  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
 
4770
}
 
4771
 
 
4772
MachineSDNode *
 
4773
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4774
                             EVT VT1, EVT VT2, EVT VT3,
 
4775
                             const SDValue *Ops, unsigned NumOps) {
 
4776
  SDVTList VTs = getVTList(VT1, VT2, VT3);
 
4777
  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
 
4778
}
 
4779
 
 
4780
MachineSDNode *
 
4781
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
 
4782
                             EVT VT2, EVT VT3, EVT VT4,
 
4783
                             const SDValue *Ops, unsigned NumOps) {
 
4784
  SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
 
4785
  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
 
4786
}
 
4787
 
 
4788
MachineSDNode *
 
4789
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
 
4790
                             const std::vector<EVT> &ResultTys,
 
4791
                             const SDValue *Ops, unsigned NumOps) {
 
4792
  SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
 
4793
  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
 
4794
}
 
4795
 
 
4796
MachineSDNode *
 
4797
SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
 
4798
                             const SDValue *Ops, unsigned NumOps) {
 
4799
  bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
 
4800
  MachineSDNode *N;
 
4801
  void *IP;
 
4802
 
 
4803
  if (DoCSE) {
 
4804
    FoldingSetNodeID ID;
 
4805
    AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
 
4806
    IP = 0;
 
4807
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
4808
      return cast<MachineSDNode>(E);
 
4809
  }
 
4810
 
 
4811
  // Allocate a new MachineSDNode.
 
4812
  N = NodeAllocator.Allocate<MachineSDNode>();
 
4813
  new (N) MachineSDNode(~Opcode, DL, VTs);
 
4814
 
 
4815
  // Initialize the operands list.
 
4816
  if (NumOps > array_lengthof(N->LocalOperands))
 
4817
    // We're creating a final node that will live unmorphed for the
 
4818
    // remainder of the current SelectionDAG iteration, so we can allocate
 
4819
    // the operands directly out of a pool with no recycling metadata.
 
4820
    N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
 
4821
                    Ops, NumOps);
 
4822
  else
 
4823
    N->InitOperands(N->LocalOperands, Ops, NumOps);
 
4824
  N->OperandsNeedDelete = false;
 
4825
 
 
4826
  if (DoCSE)
 
4827
    CSEMap.InsertNode(N, IP);
 
4828
 
 
4829
  AllNodes.push_back(N);
 
4830
#ifndef NDEBUG
 
4831
  VerifyNode(N);
 
4832
#endif
 
4833
  return N;
 
4834
}
 
4835
 
 
4836
/// getTargetExtractSubreg - A convenience function for creating
 
4837
/// TargetOpcode::EXTRACT_SUBREG nodes.
 
4838
SDValue
 
4839
SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
 
4840
                                     SDValue Operand) {
 
4841
  SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
 
4842
  SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
 
4843
                                  VT, Operand, SRIdxVal);
 
4844
  return SDValue(Subreg, 0);
 
4845
}
 
4846
 
 
4847
/// getTargetInsertSubreg - A convenience function for creating
 
4848
/// TargetOpcode::INSERT_SUBREG nodes.
 
4849
SDValue
 
4850
SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
 
4851
                                    SDValue Operand, SDValue Subreg) {
 
4852
  SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
 
4853
  SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
 
4854
                                  VT, Operand, Subreg, SRIdxVal);
 
4855
  return SDValue(Result, 0);
 
4856
}
 
4857
 
 
4858
/// getNodeIfExists - Get the specified node if it's already available, or
 
4859
/// else return NULL.
 
4860
SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
 
4861
                                      const SDValue *Ops, unsigned NumOps) {
 
4862
  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
 
4863
    FoldingSetNodeID ID;
 
4864
    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
 
4865
    void *IP = 0;
 
4866
    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
 
4867
      return E;
 
4868
  }
 
4869
  return NULL;
 
4870
}
 
4871
 
 
4872
namespace {
 
4873
 
 
4874
/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
 
4875
/// pointed to by a use iterator is deleted, increment the use iterator
 
4876
/// so that it doesn't dangle.
 
4877
///
 
4878
/// This class also manages a "downlink" DAGUpdateListener, to forward
 
4879
/// messages to ReplaceAllUsesWith's callers.
 
4880
///
 
4881
class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
 
4882
  SelectionDAG::DAGUpdateListener *DownLink;
 
4883
  SDNode::use_iterator &UI;
 
4884
  SDNode::use_iterator &UE;
 
4885
 
 
4886
  virtual void NodeDeleted(SDNode *N, SDNode *E) {
 
4887
    // Increment the iterator as needed.
 
4888
    while (UI != UE && N == *UI)
 
4889
      ++UI;
 
4890
 
 
4891
    // Then forward the message.
 
4892
    if (DownLink) DownLink->NodeDeleted(N, E);
 
4893
  }
 
4894
 
 
4895
  virtual void NodeUpdated(SDNode *N) {
 
4896
    // Just forward the message.
 
4897
    if (DownLink) DownLink->NodeUpdated(N);
 
4898
  }
 
4899
 
 
4900
public:
 
4901
  RAUWUpdateListener(SelectionDAG::DAGUpdateListener *dl,
 
4902
                     SDNode::use_iterator &ui,
 
4903
                     SDNode::use_iterator &ue)
 
4904
    : DownLink(dl), UI(ui), UE(ue) {}
 
4905
};
 
4906
 
 
4907
}
 
4908
 
 
4909
/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
 
4910
/// This can cause recursive merging of nodes in the DAG.
 
4911
///
 
4912
/// This version assumes From has a single result value.
 
4913
///
 
4914
void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
 
4915
                                      DAGUpdateListener *UpdateListener) {
 
4916
  SDNode *From = FromN.getNode();
 
4917
  assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
 
4918
         "Cannot replace with this method!");
 
4919
  assert(From != To.getNode() && "Cannot replace uses of with self");
 
4920
 
 
4921
  // Iterate over all the existing uses of From. New uses will be added
 
4922
  // to the beginning of the use list, which we avoid visiting.
 
4923
  // This specifically avoids visiting uses of From that arise while the
 
4924
  // replacement is happening, because any such uses would be the result
 
4925
  // of CSE: If an existing node looks like From after one of its operands
 
4926
  // is replaced by To, we don't want to replace of all its users with To
 
4927
  // too. See PR3018 for more info.
 
4928
  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
 
4929
  RAUWUpdateListener Listener(UpdateListener, UI, UE);
 
4930
  while (UI != UE) {
 
4931
    SDNode *User = *UI;
 
4932
 
 
4933
    // This node is about to morph, remove its old self from the CSE maps.
 
4934
    RemoveNodeFromCSEMaps(User);
 
4935
 
 
4936
    // A user can appear in a use list multiple times, and when this
 
4937
    // happens the uses are usually next to each other in the list.
 
4938
    // To help reduce the number of CSE recomputations, process all
 
4939
    // the uses of this user that we can find this way.
 
4940
    do {
 
4941
      SDUse &Use = UI.getUse();
 
4942
      ++UI;
 
4943
      Use.set(To);
 
4944
    } while (UI != UE && *UI == User);
 
4945
 
 
4946
    // Now that we have modified User, add it back to the CSE maps.  If it
 
4947
    // already exists there, recursively merge the results together.
 
4948
    AddModifiedNodeToCSEMaps(User, &Listener);
 
4949
  }
 
4950
}
 
4951
 
 
4952
/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
 
4953
/// This can cause recursive merging of nodes in the DAG.
 
4954
///
 
4955
/// This version assumes that for each value of From, there is a
 
4956
/// corresponding value in To in the same position with the same type.
 
4957
///
 
4958
void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
 
4959
                                      DAGUpdateListener *UpdateListener) {
 
4960
#ifndef NDEBUG
 
4961
  for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
 
4962
    assert((!From->hasAnyUseOfValue(i) ||
 
4963
            From->getValueType(i) == To->getValueType(i)) &&
 
4964
           "Cannot use this version of ReplaceAllUsesWith!");
 
4965
#endif
 
4966
 
 
4967
  // Handle the trivial case.
 
4968
  if (From == To)
 
4969
    return;
 
4970
 
 
4971
  // Iterate over just the existing users of From. See the comments in
 
4972
  // the ReplaceAllUsesWith above.
 
4973
  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
 
4974
  RAUWUpdateListener Listener(UpdateListener, UI, UE);
 
4975
  while (UI != UE) {
 
4976
    SDNode *User = *UI;
 
4977
 
 
4978
    // This node is about to morph, remove its old self from the CSE maps.
 
4979
    RemoveNodeFromCSEMaps(User);
 
4980
 
 
4981
    // A user can appear in a use list multiple times, and when this
 
4982
    // happens the uses are usually next to each other in the list.
 
4983
    // To help reduce the number of CSE recomputations, process all
 
4984
    // the uses of this user that we can find this way.
 
4985
    do {
 
4986
      SDUse &Use = UI.getUse();
 
4987
      ++UI;
 
4988
      Use.setNode(To);
 
4989
    } while (UI != UE && *UI == User);
 
4990
 
 
4991
    // Now that we have modified User, add it back to the CSE maps.  If it
 
4992
    // already exists there, recursively merge the results together.
 
4993
    AddModifiedNodeToCSEMaps(User, &Listener);
 
4994
  }
 
4995
}
 
4996
 
 
4997
/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
 
4998
/// This can cause recursive merging of nodes in the DAG.
 
4999
///
 
5000
/// This version can replace From with any result values.  To must match the
 
5001
/// number and types of values returned by From.
 
5002
void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
 
5003
                                      const SDValue *To,
 
5004
                                      DAGUpdateListener *UpdateListener) {
 
5005
  if (From->getNumValues() == 1)  // Handle the simple case efficiently.
 
5006
    return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
 
5007
 
 
5008
  // Iterate over just the existing users of From. See the comments in
 
5009
  // the ReplaceAllUsesWith above.
 
5010
  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
 
5011
  RAUWUpdateListener Listener(UpdateListener, UI, UE);
 
5012
  while (UI != UE) {
 
5013
    SDNode *User = *UI;
 
5014
 
 
5015
    // This node is about to morph, remove its old self from the CSE maps.
 
5016
    RemoveNodeFromCSEMaps(User);
 
5017
 
 
5018
    // A user can appear in a use list multiple times, and when this
 
5019
    // happens the uses are usually next to each other in the list.
 
5020
    // To help reduce the number of CSE recomputations, process all
 
5021
    // the uses of this user that we can find this way.
 
5022
    do {
 
5023
      SDUse &Use = UI.getUse();
 
5024
      const SDValue &ToOp = To[Use.getResNo()];
 
5025
      ++UI;
 
5026
      Use.set(ToOp);
 
5027
    } while (UI != UE && *UI == User);
 
5028
 
 
5029
    // Now that we have modified User, add it back to the CSE maps.  If it
 
5030
    // already exists there, recursively merge the results together.
 
5031
    AddModifiedNodeToCSEMaps(User, &Listener);
 
5032
  }
 
5033
}
 
5034
 
 
5035
/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
 
5036
/// uses of other values produced by From.getNode() alone.  The Deleted
 
5037
/// vector is handled the same way as for ReplaceAllUsesWith.
 
5038
void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
 
5039
                                             DAGUpdateListener *UpdateListener){
 
5040
  // Handle the really simple, really trivial case efficiently.
 
5041
  if (From == To) return;
 
5042
 
 
5043
  // Handle the simple, trivial, case efficiently.
 
5044
  if (From.getNode()->getNumValues() == 1) {
 
5045
    ReplaceAllUsesWith(From, To, UpdateListener);
 
5046
    return;
 
5047
  }
 
5048
 
 
5049
  // Iterate over just the existing users of From. See the comments in
 
5050
  // the ReplaceAllUsesWith above.
 
5051
  SDNode::use_iterator UI = From.getNode()->use_begin(),
 
5052
                       UE = From.getNode()->use_end();
 
5053
  RAUWUpdateListener Listener(UpdateListener, UI, UE);
 
5054
  while (UI != UE) {
 
5055
    SDNode *User = *UI;
 
5056
    bool UserRemovedFromCSEMaps = false;
 
5057
 
 
5058
    // A user can appear in a use list multiple times, and when this
 
5059
    // happens the uses are usually next to each other in the list.
 
5060
    // To help reduce the number of CSE recomputations, process all
 
5061
    // the uses of this user that we can find this way.
 
5062
    do {
 
5063
      SDUse &Use = UI.getUse();
 
5064
 
 
5065
      // Skip uses of different values from the same node.
 
5066
      if (Use.getResNo() != From.getResNo()) {
 
5067
        ++UI;
 
5068
        continue;
 
5069
      }
 
5070
 
 
5071
      // If this node hasn't been modified yet, it's still in the CSE maps,
 
5072
      // so remove its old self from the CSE maps.
 
5073
      if (!UserRemovedFromCSEMaps) {
 
5074
        RemoveNodeFromCSEMaps(User);
 
5075
        UserRemovedFromCSEMaps = true;
 
5076
      }
 
5077
 
 
5078
      ++UI;
 
5079
      Use.set(To);
 
5080
    } while (UI != UE && *UI == User);
 
5081
 
 
5082
    // We are iterating over all uses of the From node, so if a use
 
5083
    // doesn't use the specific value, no changes are made.
 
5084
    if (!UserRemovedFromCSEMaps)
 
5085
      continue;
 
5086
 
 
5087
    // Now that we have modified User, add it back to the CSE maps.  If it
 
5088
    // already exists there, recursively merge the results together.
 
5089
    AddModifiedNodeToCSEMaps(User, &Listener);
 
5090
  }
 
5091
}
 
5092
 
 
5093
namespace {
 
5094
  /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
 
5095
  /// to record information about a use.
 
5096
  struct UseMemo {
 
5097
    SDNode *User;
 
5098
    unsigned Index;
 
5099
    SDUse *Use;
 
5100
  };
 
5101
 
 
5102
  /// operator< - Sort Memos by User.
 
5103
  bool operator<(const UseMemo &L, const UseMemo &R) {
 
5104
    return (intptr_t)L.User < (intptr_t)R.User;
 
5105
  }
 
5106
}
 
5107
 
 
5108
/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
 
5109
/// uses of other values produced by From.getNode() alone.  The same value
 
5110
/// may appear in both the From and To list.  The Deleted vector is
 
5111
/// handled the same way as for ReplaceAllUsesWith.
 
5112
void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
 
5113
                                              const SDValue *To,
 
5114
                                              unsigned Num,
 
5115
                                              DAGUpdateListener *UpdateListener){
 
5116
  // Handle the simple, trivial case efficiently.
 
5117
  if (Num == 1)
 
5118
    return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
 
5119
 
 
5120
  // Read up all the uses and make records of them. This helps
 
5121
  // processing new uses that are introduced during the
 
5122
  // replacement process.
 
5123
  SmallVector<UseMemo, 4> Uses;
 
5124
  for (unsigned i = 0; i != Num; ++i) {
 
5125
    unsigned FromResNo = From[i].getResNo();
 
5126
    SDNode *FromNode = From[i].getNode();
 
5127
    for (SDNode::use_iterator UI = FromNode->use_begin(),
 
5128
         E = FromNode->use_end(); UI != E; ++UI) {
 
5129
      SDUse &Use = UI.getUse();
 
5130
      if (Use.getResNo() == FromResNo) {
 
5131
        UseMemo Memo = { *UI, i, &Use };
 
5132
        Uses.push_back(Memo);
 
5133
      }
 
5134
    }
 
5135
  }
 
5136
 
 
5137
  // Sort the uses, so that all the uses from a given User are together.
 
5138
  std::sort(Uses.begin(), Uses.end());
 
5139
 
 
5140
  for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
 
5141
       UseIndex != UseIndexEnd; ) {
 
5142
    // We know that this user uses some value of From.  If it is the right
 
5143
    // value, update it.
 
5144
    SDNode *User = Uses[UseIndex].User;
 
5145
 
 
5146
    // This node is about to morph, remove its old self from the CSE maps.
 
5147
    RemoveNodeFromCSEMaps(User);
 
5148
 
 
5149
    // The Uses array is sorted, so all the uses for a given User
 
5150
    // are next to each other in the list.
 
5151
    // To help reduce the number of CSE recomputations, process all
 
5152
    // the uses of this user that we can find this way.
 
5153
    do {
 
5154
      unsigned i = Uses[UseIndex].Index;
 
5155
      SDUse &Use = *Uses[UseIndex].Use;
 
5156
      ++UseIndex;
 
5157
 
 
5158
      Use.set(To[i]);
 
5159
    } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
 
5160
 
 
5161
    // Now that we have modified User, add it back to the CSE maps.  If it
 
5162
    // already exists there, recursively merge the results together.
 
5163
    AddModifiedNodeToCSEMaps(User, UpdateListener);
 
5164
  }
 
5165
}
 
5166
 
 
5167
/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
 
5168
/// based on their topological order. It returns the maximum id and a vector
 
5169
/// of the SDNodes* in assigned order by reference.
 
5170
unsigned SelectionDAG::AssignTopologicalOrder() {
 
5171
 
 
5172
  unsigned DAGSize = 0;
 
5173
 
 
5174
  // SortedPos tracks the progress of the algorithm. Nodes before it are
 
5175
  // sorted, nodes after it are unsorted. When the algorithm completes
 
5176
  // it is at the end of the list.
 
5177
  allnodes_iterator SortedPos = allnodes_begin();
 
5178
 
 
5179
  // Visit all the nodes. Move nodes with no operands to the front of
 
5180
  // the list immediately. Annotate nodes that do have operands with their
 
5181
  // operand count. Before we do this, the Node Id fields of the nodes
 
5182
  // may contain arbitrary values. After, the Node Id fields for nodes
 
5183
  // before SortedPos will contain the topological sort index, and the
 
5184
  // Node Id fields for nodes At SortedPos and after will contain the
 
5185
  // count of outstanding operands.
 
5186
  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
 
5187
    SDNode *N = I++;
 
5188
    checkForCycles(N);
 
5189
    unsigned Degree = N->getNumOperands();
 
5190
    if (Degree == 0) {
 
5191
      // A node with no uses, add it to the result array immediately.
 
5192
      N->setNodeId(DAGSize++);
 
5193
      allnodes_iterator Q = N;
 
5194
      if (Q != SortedPos)
 
5195
        SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
 
5196
      assert(SortedPos != AllNodes.end() && "Overran node list");
 
5197
      ++SortedPos;
 
5198
    } else {
 
5199
      // Temporarily use the Node Id as scratch space for the degree count.
 
5200
      N->setNodeId(Degree);
 
5201
    }
 
5202
  }
 
5203
 
 
5204
  // Visit all the nodes. As we iterate, moves nodes into sorted order,
 
5205
  // such that by the time the end is reached all nodes will be sorted.
 
5206
  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
 
5207
    SDNode *N = I;
 
5208
    checkForCycles(N);
 
5209
    // N is in sorted position, so all its uses have one less operand
 
5210
    // that needs to be sorted.
 
5211
    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
 
5212
         UI != UE; ++UI) {
 
5213
      SDNode *P = *UI;
 
5214
      unsigned Degree = P->getNodeId();
 
5215
      assert(Degree != 0 && "Invalid node degree");
 
5216
      --Degree;
 
5217
      if (Degree == 0) {
 
5218
        // All of P's operands are sorted, so P may sorted now.
 
5219
        P->setNodeId(DAGSize++);
 
5220
        if (P != SortedPos)
 
5221
          SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
 
5222
        assert(SortedPos != AllNodes.end() && "Overran node list");
 
5223
        ++SortedPos;
 
5224
      } else {
 
5225
        // Update P's outstanding operand count.
 
5226
        P->setNodeId(Degree);
 
5227
      }
 
5228
    }
 
5229
    if (I == SortedPos) {
 
5230
#ifndef NDEBUG
 
5231
      SDNode *S = ++I;
 
5232
      dbgs() << "Overran sorted position:\n";
 
5233
      S->dumprFull();
 
5234
#endif
 
5235
      llvm_unreachable(0);
 
5236
    }
 
5237
  }
 
5238
 
 
5239
  assert(SortedPos == AllNodes.end() &&
 
5240
         "Topological sort incomplete!");
 
5241
  assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
 
5242
         "First node in topological sort is not the entry token!");
 
5243
  assert(AllNodes.front().getNodeId() == 0 &&
 
5244
         "First node in topological sort has non-zero id!");
 
5245
  assert(AllNodes.front().getNumOperands() == 0 &&
 
5246
         "First node in topological sort has operands!");
 
5247
  assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
 
5248
         "Last node in topologic sort has unexpected id!");
 
5249
  assert(AllNodes.back().use_empty() &&
 
5250
         "Last node in topologic sort has users!");
 
5251
  assert(DAGSize == allnodes_size() && "Node count mismatch!");
 
5252
  return DAGSize;
 
5253
}
 
5254
 
 
5255
/// AssignOrdering - Assign an order to the SDNode.
 
5256
void SelectionDAG::AssignOrdering(const SDNode *SD, unsigned Order) {
 
5257
  assert(SD && "Trying to assign an order to a null node!");
 
5258
  Ordering->add(SD, Order);
 
5259
}
 
5260
 
 
5261
/// GetOrdering - Get the order for the SDNode.
 
5262
unsigned SelectionDAG::GetOrdering(const SDNode *SD) const {
 
5263
  assert(SD && "Trying to get the order of a null node!");
 
5264
  return Ordering->getOrder(SD);
 
5265
}
 
5266
 
 
5267
 
 
5268
//===----------------------------------------------------------------------===//
 
5269
//                              SDNode Class
 
5270
//===----------------------------------------------------------------------===//
 
5271
 
 
5272
HandleSDNode::~HandleSDNode() {
 
5273
  DropOperands();
 
5274
}
 
5275
 
 
5276
GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
 
5277
                                         EVT VT, int64_t o, unsigned char TF)
 
5278
  : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
 
5279
    Offset(o), TargetFlags(TF) {
 
5280
  TheGlobal = const_cast<GlobalValue*>(GA);
 
5281
}
 
5282
 
 
5283
MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
 
5284
                     MachineMemOperand *mmo)
 
5285
 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
 
5286
  SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
 
5287
                                      MMO->isNonTemporal());
 
5288
  assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
 
5289
  assert(isNonTemporal() == MMO->isNonTemporal() &&
 
5290
         "Non-temporal encoding error!");
 
5291
  assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
 
5292
}
 
5293
 
 
5294
MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
 
5295
                     const SDValue *Ops, unsigned NumOps, EVT memvt, 
 
5296
                     MachineMemOperand *mmo)
 
5297
   : SDNode(Opc, dl, VTs, Ops, NumOps),
 
5298
     MemoryVT(memvt), MMO(mmo) {
 
5299
  SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
 
5300
                                      MMO->isNonTemporal());
 
5301
  assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
 
5302
  assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
 
5303
}
 
5304
 
 
5305
/// Profile - Gather unique data for the node.
 
5306
///
 
5307
void SDNode::Profile(FoldingSetNodeID &ID) const {
 
5308
  AddNodeIDNode(ID, this);
 
5309
}
 
5310
 
 
5311
namespace {
 
5312
  struct EVTArray {
 
5313
    std::vector<EVT> VTs;
 
5314
    
 
5315
    EVTArray() {
 
5316
      VTs.reserve(MVT::LAST_VALUETYPE);
 
5317
      for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
 
5318
        VTs.push_back(MVT((MVT::SimpleValueType)i));
 
5319
    }
 
5320
  };
 
5321
}
 
5322
 
 
5323
static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
 
5324
static ManagedStatic<EVTArray> SimpleVTArray;
 
5325
static ManagedStatic<sys::SmartMutex<true> > VTMutex;
 
5326
 
 
5327
/// getValueTypeList - Return a pointer to the specified value type.
 
5328
///
 
5329
const EVT *SDNode::getValueTypeList(EVT VT) {
 
5330
  if (VT.isExtended()) {
 
5331
    sys::SmartScopedLock<true> Lock(*VTMutex);
 
5332
    return &(*EVTs->insert(VT).first);
 
5333
  } else {
 
5334
    return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
 
5335
  }
 
5336
}
 
5337
 
 
5338
/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
 
5339
/// indicated value.  This method ignores uses of other values defined by this
 
5340
/// operation.
 
5341
bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
 
5342
  assert(Value < getNumValues() && "Bad value!");
 
5343
 
 
5344
  // TODO: Only iterate over uses of a given value of the node
 
5345
  for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
 
5346
    if (UI.getUse().getResNo() == Value) {
 
5347
      if (NUses == 0)
 
5348
        return false;
 
5349
      --NUses;
 
5350
    }
 
5351
  }
 
5352
 
 
5353
  // Found exactly the right number of uses?
 
5354
  return NUses == 0;
 
5355
}
 
5356
 
 
5357
 
 
5358
/// hasAnyUseOfValue - Return true if there are any use of the indicated
 
5359
/// value. This method ignores uses of other values defined by this operation.
 
5360
bool SDNode::hasAnyUseOfValue(unsigned Value) const {
 
5361
  assert(Value < getNumValues() && "Bad value!");
 
5362
 
 
5363
  for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
 
5364
    if (UI.getUse().getResNo() == Value)
 
5365
      return true;
 
5366
 
 
5367
  return false;
 
5368
}
 
5369
 
 
5370
 
 
5371
/// isOnlyUserOf - Return true if this node is the only use of N.
 
5372
///
 
5373
bool SDNode::isOnlyUserOf(SDNode *N) const {
 
5374
  bool Seen = false;
 
5375
  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
 
5376
    SDNode *User = *I;
 
5377
    if (User == this)
 
5378
      Seen = true;
 
5379
    else
 
5380
      return false;
 
5381
  }
 
5382
 
 
5383
  return Seen;
 
5384
}
 
5385
 
 
5386
/// isOperand - Return true if this node is an operand of N.
 
5387
///
 
5388
bool SDValue::isOperandOf(SDNode *N) const {
 
5389
  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
 
5390
    if (*this == N->getOperand(i))
 
5391
      return true;
 
5392
  return false;
 
5393
}
 
5394
 
 
5395
bool SDNode::isOperandOf(SDNode *N) const {
 
5396
  for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
 
5397
    if (this == N->OperandList[i].getNode())
 
5398
      return true;
 
5399
  return false;
 
5400
}
 
5401
 
 
5402
/// reachesChainWithoutSideEffects - Return true if this operand (which must
 
5403
/// be a chain) reaches the specified operand without crossing any
 
5404
/// side-effecting instructions.  In practice, this looks through token
 
5405
/// factors and non-volatile loads.  In order to remain efficient, this only
 
5406
/// looks a couple of nodes in, it does not do an exhaustive search.
 
5407
bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
 
5408
                                               unsigned Depth) const {
 
5409
  if (*this == Dest) return true;
 
5410
 
 
5411
  // Don't search too deeply, we just want to be able to see through
 
5412
  // TokenFactor's etc.
 
5413
  if (Depth == 0) return false;
 
5414
 
 
5415
  // If this is a token factor, all inputs to the TF happen in parallel.  If any
 
5416
  // of the operands of the TF reach dest, then we can do the xform.
 
5417
  if (getOpcode() == ISD::TokenFactor) {
 
5418
    for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
 
5419
      if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
 
5420
        return true;
 
5421
    return false;
 
5422
  }
 
5423
 
 
5424
  // Loads don't have side effects, look through them.
 
5425
  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
 
5426
    if (!Ld->isVolatile())
 
5427
      return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
 
5428
  }
 
5429
  return false;
 
5430
}
 
5431
 
 
5432
/// isPredecessorOf - Return true if this node is a predecessor of N. This node
 
5433
/// is either an operand of N or it can be reached by traversing up the operands.
 
5434
/// NOTE: this is an expensive method. Use it carefully.
 
5435
bool SDNode::isPredecessorOf(SDNode *N) const {
 
5436
  SmallPtrSet<SDNode *, 32> Visited;
 
5437
  SmallVector<SDNode *, 16> Worklist;
 
5438
  Worklist.push_back(N);
 
5439
 
 
5440
  do {
 
5441
    N = Worklist.pop_back_val();
 
5442
    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
 
5443
      SDNode *Op = N->getOperand(i).getNode();
 
5444
      if (Op == this)
 
5445
        return true;
 
5446
      if (Visited.insert(Op))
 
5447
        Worklist.push_back(Op);
 
5448
    }
 
5449
  } while (!Worklist.empty());
 
5450
 
 
5451
  return false;
 
5452
}
 
5453
 
 
5454
uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
 
5455
  assert(Num < NumOperands && "Invalid child # of SDNode!");
 
5456
  return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
 
5457
}
 
5458
 
 
5459
std::string SDNode::getOperationName(const SelectionDAG *G) const {
 
5460
  switch (getOpcode()) {
 
5461
  default:
 
5462
    if (getOpcode() < ISD::BUILTIN_OP_END)
 
5463
      return "<<Unknown DAG Node>>";
 
5464
    if (isMachineOpcode()) {
 
5465
      if (G)
 
5466
        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
 
5467
          if (getMachineOpcode() < TII->getNumOpcodes())
 
5468
            return TII->get(getMachineOpcode()).getName();
 
5469
      return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
 
5470
    }
 
5471
    if (G) {
 
5472
      const TargetLowering &TLI = G->getTargetLoweringInfo();
 
5473
      const char *Name = TLI.getTargetNodeName(getOpcode());
 
5474
      if (Name) return Name;
 
5475
      return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
 
5476
    }
 
5477
    return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
 
5478
 
 
5479
#ifndef NDEBUG
 
5480
  case ISD::DELETED_NODE:
 
5481
    return "<<Deleted Node!>>";
 
5482
#endif
 
5483
  case ISD::PREFETCH:      return "Prefetch";
 
5484
  case ISD::MEMBARRIER:    return "MemBarrier";
 
5485
  case ISD::ATOMIC_CMP_SWAP:    return "AtomicCmpSwap";
 
5486
  case ISD::ATOMIC_SWAP:        return "AtomicSwap";
 
5487
  case ISD::ATOMIC_LOAD_ADD:    return "AtomicLoadAdd";
 
5488
  case ISD::ATOMIC_LOAD_SUB:    return "AtomicLoadSub";
 
5489
  case ISD::ATOMIC_LOAD_AND:    return "AtomicLoadAnd";
 
5490
  case ISD::ATOMIC_LOAD_OR:     return "AtomicLoadOr";
 
5491
  case ISD::ATOMIC_LOAD_XOR:    return "AtomicLoadXor";
 
5492
  case ISD::ATOMIC_LOAD_NAND:   return "AtomicLoadNand";
 
5493
  case ISD::ATOMIC_LOAD_MIN:    return "AtomicLoadMin";
 
5494
  case ISD::ATOMIC_LOAD_MAX:    return "AtomicLoadMax";
 
5495
  case ISD::ATOMIC_LOAD_UMIN:   return "AtomicLoadUMin";
 
5496
  case ISD::ATOMIC_LOAD_UMAX:   return "AtomicLoadUMax";
 
5497
  case ISD::PCMARKER:      return "PCMarker";
 
5498
  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
 
5499
  case ISD::SRCVALUE:      return "SrcValue";
 
5500
  case ISD::EntryToken:    return "EntryToken";
 
5501
  case ISD::TokenFactor:   return "TokenFactor";
 
5502
  case ISD::AssertSext:    return "AssertSext";
 
5503
  case ISD::AssertZext:    return "AssertZext";
 
5504
 
 
5505
  case ISD::BasicBlock:    return "BasicBlock";
 
5506
  case ISD::VALUETYPE:     return "ValueType";
 
5507
  case ISD::Register:      return "Register";
 
5508
 
 
5509
  case ISD::Constant:      return "Constant";
 
5510
  case ISD::ConstantFP:    return "ConstantFP";
 
5511
  case ISD::GlobalAddress: return "GlobalAddress";
 
5512
  case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
 
5513
  case ISD::FrameIndex:    return "FrameIndex";
 
5514
  case ISD::JumpTable:     return "JumpTable";
 
5515
  case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
 
5516
  case ISD::RETURNADDR: return "RETURNADDR";
 
5517
  case ISD::FRAMEADDR: return "FRAMEADDR";
 
5518
  case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
 
5519
  case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
 
5520
  case ISD::LSDAADDR: return "LSDAADDR";
 
5521
  case ISD::EHSELECTION: return "EHSELECTION";
 
5522
  case ISD::EH_RETURN: return "EH_RETURN";
 
5523
  case ISD::ConstantPool:  return "ConstantPool";
 
5524
  case ISD::ExternalSymbol: return "ExternalSymbol";
 
5525
  case ISD::BlockAddress:  return "BlockAddress";
 
5526
  case ISD::INTRINSIC_WO_CHAIN:
 
5527
  case ISD::INTRINSIC_VOID:
 
5528
  case ISD::INTRINSIC_W_CHAIN: {
 
5529
    unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
 
5530
    unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
 
5531
    if (IID < Intrinsic::num_intrinsics)
 
5532
      return Intrinsic::getName((Intrinsic::ID)IID);
 
5533
    else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
 
5534
      return TII->getName(IID);
 
5535
    llvm_unreachable("Invalid intrinsic ID");
 
5536
  }
 
5537
 
 
5538
  case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
 
5539
  case ISD::TargetConstant: return "TargetConstant";
 
5540
  case ISD::TargetConstantFP:return "TargetConstantFP";
 
5541
  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
 
5542
  case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
 
5543
  case ISD::TargetFrameIndex: return "TargetFrameIndex";
 
5544
  case ISD::TargetJumpTable:  return "TargetJumpTable";
 
5545
  case ISD::TargetConstantPool:  return "TargetConstantPool";
 
5546
  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
 
5547
  case ISD::TargetBlockAddress: return "TargetBlockAddress";
 
5548
 
 
5549
  case ISD::CopyToReg:     return "CopyToReg";
 
5550
  case ISD::CopyFromReg:   return "CopyFromReg";
 
5551
  case ISD::UNDEF:         return "undef";
 
5552
  case ISD::MERGE_VALUES:  return "merge_values";
 
5553
  case ISD::INLINEASM:     return "inlineasm";
 
5554
  case ISD::EH_LABEL:      return "eh_label";
 
5555
  case ISD::HANDLENODE:    return "handlenode";
 
5556
 
 
5557
  // Unary operators
 
5558
  case ISD::FABS:   return "fabs";
 
5559
  case ISD::FNEG:   return "fneg";
 
5560
  case ISD::FSQRT:  return "fsqrt";
 
5561
  case ISD::FSIN:   return "fsin";
 
5562
  case ISD::FCOS:   return "fcos";
 
5563
  case ISD::FPOWI:  return "fpowi";
 
5564
  case ISD::FPOW:   return "fpow";
 
5565
  case ISD::FTRUNC: return "ftrunc";
 
5566
  case ISD::FFLOOR: return "ffloor";
 
5567
  case ISD::FCEIL:  return "fceil";
 
5568
  case ISD::FRINT:  return "frint";
 
5569
  case ISD::FNEARBYINT: return "fnearbyint";
 
5570
 
 
5571
  // Binary operators
 
5572
  case ISD::ADD:    return "add";
 
5573
  case ISD::SUB:    return "sub";
 
5574
  case ISD::MUL:    return "mul";
 
5575
  case ISD::MULHU:  return "mulhu";
 
5576
  case ISD::MULHS:  return "mulhs";
 
5577
  case ISD::SDIV:   return "sdiv";
 
5578
  case ISD::UDIV:   return "udiv";
 
5579
  case ISD::SREM:   return "srem";
 
5580
  case ISD::UREM:   return "urem";
 
5581
  case ISD::SMUL_LOHI:  return "smul_lohi";
 
5582
  case ISD::UMUL_LOHI:  return "umul_lohi";
 
5583
  case ISD::SDIVREM:    return "sdivrem";
 
5584
  case ISD::UDIVREM:    return "udivrem";
 
5585
  case ISD::AND:    return "and";
 
5586
  case ISD::OR:     return "or";
 
5587
  case ISD::XOR:    return "xor";
 
5588
  case ISD::SHL:    return "shl";
 
5589
  case ISD::SRA:    return "sra";
 
5590
  case ISD::SRL:    return "srl";
 
5591
  case ISD::ROTL:   return "rotl";
 
5592
  case ISD::ROTR:   return "rotr";
 
5593
  case ISD::FADD:   return "fadd";
 
5594
  case ISD::FSUB:   return "fsub";
 
5595
  case ISD::FMUL:   return "fmul";
 
5596
  case ISD::FDIV:   return "fdiv";
 
5597
  case ISD::FREM:   return "frem";
 
5598
  case ISD::FCOPYSIGN: return "fcopysign";
 
5599
  case ISD::FGETSIGN:  return "fgetsign";
 
5600
 
 
5601
  case ISD::SETCC:       return "setcc";
 
5602
  case ISD::VSETCC:      return "vsetcc";
 
5603
  case ISD::SELECT:      return "select";
 
5604
  case ISD::SELECT_CC:   return "select_cc";
 
5605
  case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
 
5606
  case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
 
5607
  case ISD::CONCAT_VECTORS:      return "concat_vectors";
 
5608
  case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
 
5609
  case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
 
5610
  case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
 
5611
  case ISD::CARRY_FALSE:         return "carry_false";
 
5612
  case ISD::ADDC:        return "addc";
 
5613
  case ISD::ADDE:        return "adde";
 
5614
  case ISD::SADDO:       return "saddo";
 
5615
  case ISD::UADDO:       return "uaddo";
 
5616
  case ISD::SSUBO:       return "ssubo";
 
5617
  case ISD::USUBO:       return "usubo";
 
5618
  case ISD::SMULO:       return "smulo";
 
5619
  case ISD::UMULO:       return "umulo";
 
5620
  case ISD::SUBC:        return "subc";
 
5621
  case ISD::SUBE:        return "sube";
 
5622
  case ISD::SHL_PARTS:   return "shl_parts";
 
5623
  case ISD::SRA_PARTS:   return "sra_parts";
 
5624
  case ISD::SRL_PARTS:   return "srl_parts";
 
5625
 
 
5626
  // Conversion operators.
 
5627
  case ISD::SIGN_EXTEND: return "sign_extend";
 
5628
  case ISD::ZERO_EXTEND: return "zero_extend";
 
5629
  case ISD::ANY_EXTEND:  return "any_extend";
 
5630
  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
 
5631
  case ISD::TRUNCATE:    return "truncate";
 
5632
  case ISD::FP_ROUND:    return "fp_round";
 
5633
  case ISD::FLT_ROUNDS_: return "flt_rounds";
 
5634
  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
 
5635
  case ISD::FP_EXTEND:   return "fp_extend";
 
5636
 
 
5637
  case ISD::SINT_TO_FP:  return "sint_to_fp";
 
5638
  case ISD::UINT_TO_FP:  return "uint_to_fp";
 
5639
  case ISD::FP_TO_SINT:  return "fp_to_sint";
 
5640
  case ISD::FP_TO_UINT:  return "fp_to_uint";
 
5641
  case ISD::BIT_CONVERT: return "bit_convert";
 
5642
 
 
5643
  case ISD::CONVERT_RNDSAT: {
 
5644
    switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
 
5645
    default: llvm_unreachable("Unknown cvt code!");
 
5646
    case ISD::CVT_FF:  return "cvt_ff";
 
5647
    case ISD::CVT_FS:  return "cvt_fs";
 
5648
    case ISD::CVT_FU:  return "cvt_fu";
 
5649
    case ISD::CVT_SF:  return "cvt_sf";
 
5650
    case ISD::CVT_UF:  return "cvt_uf";
 
5651
    case ISD::CVT_SS:  return "cvt_ss";
 
5652
    case ISD::CVT_SU:  return "cvt_su";
 
5653
    case ISD::CVT_US:  return "cvt_us";
 
5654
    case ISD::CVT_UU:  return "cvt_uu";
 
5655
    }
 
5656
  }
 
5657
 
 
5658
    // Control flow instructions
 
5659
  case ISD::BR:      return "br";
 
5660
  case ISD::BRIND:   return "brind";
 
5661
  case ISD::BR_JT:   return "br_jt";
 
5662
  case ISD::BRCOND:  return "brcond";
 
5663
  case ISD::BR_CC:   return "br_cc";
 
5664
  case ISD::CALLSEQ_START:  return "callseq_start";
 
5665
  case ISD::CALLSEQ_END:    return "callseq_end";
 
5666
 
 
5667
    // Other operators
 
5668
  case ISD::LOAD:               return "load";
 
5669
  case ISD::STORE:              return "store";
 
5670
  case ISD::VAARG:              return "vaarg";
 
5671
  case ISD::VACOPY:             return "vacopy";
 
5672
  case ISD::VAEND:              return "vaend";
 
5673
  case ISD::VASTART:            return "vastart";
 
5674
  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
 
5675
  case ISD::EXTRACT_ELEMENT:    return "extract_element";
 
5676
  case ISD::BUILD_PAIR:         return "build_pair";
 
5677
  case ISD::STACKSAVE:          return "stacksave";
 
5678
  case ISD::STACKRESTORE:       return "stackrestore";
 
5679
  case ISD::TRAP:               return "trap";
 
5680
 
 
5681
  // Bit manipulation
 
5682
  case ISD::BSWAP:   return "bswap";
 
5683
  case ISD::CTPOP:   return "ctpop";
 
5684
  case ISD::CTTZ:    return "cttz";
 
5685
  case ISD::CTLZ:    return "ctlz";
 
5686
 
 
5687
  // Trampolines
 
5688
  case ISD::TRAMPOLINE: return "trampoline";
 
5689
 
 
5690
  case ISD::CONDCODE:
 
5691
    switch (cast<CondCodeSDNode>(this)->get()) {
 
5692
    default: llvm_unreachable("Unknown setcc condition!");
 
5693
    case ISD::SETOEQ:  return "setoeq";
 
5694
    case ISD::SETOGT:  return "setogt";
 
5695
    case ISD::SETOGE:  return "setoge";
 
5696
    case ISD::SETOLT:  return "setolt";
 
5697
    case ISD::SETOLE:  return "setole";
 
5698
    case ISD::SETONE:  return "setone";
 
5699
 
 
5700
    case ISD::SETO:    return "seto";
 
5701
    case ISD::SETUO:   return "setuo";
 
5702
    case ISD::SETUEQ:  return "setue";
 
5703
    case ISD::SETUGT:  return "setugt";
 
5704
    case ISD::SETUGE:  return "setuge";
 
5705
    case ISD::SETULT:  return "setult";
 
5706
    case ISD::SETULE:  return "setule";
 
5707
    case ISD::SETUNE:  return "setune";
 
5708
 
 
5709
    case ISD::SETEQ:   return "seteq";
 
5710
    case ISD::SETGT:   return "setgt";
 
5711
    case ISD::SETGE:   return "setge";
 
5712
    case ISD::SETLT:   return "setlt";
 
5713
    case ISD::SETLE:   return "setle";
 
5714
    case ISD::SETNE:   return "setne";
 
5715
    }
 
5716
  }
 
5717
}
 
5718
 
 
5719
const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
 
5720
  switch (AM) {
 
5721
  default:
 
5722
    return "";
 
5723
  case ISD::PRE_INC:
 
5724
    return "<pre-inc>";
 
5725
  case ISD::PRE_DEC:
 
5726
    return "<pre-dec>";
 
5727
  case ISD::POST_INC:
 
5728
    return "<post-inc>";
 
5729
  case ISD::POST_DEC:
 
5730
    return "<post-dec>";
 
5731
  }
 
5732
}
 
5733
 
 
5734
std::string ISD::ArgFlagsTy::getArgFlagsString() {
 
5735
  std::string S = "< ";
 
5736
 
 
5737
  if (isZExt())
 
5738
    S += "zext ";
 
5739
  if (isSExt())
 
5740
    S += "sext ";
 
5741
  if (isInReg())
 
5742
    S += "inreg ";
 
5743
  if (isSRet())
 
5744
    S += "sret ";
 
5745
  if (isByVal())
 
5746
    S += "byval ";
 
5747
  if (isNest())
 
5748
    S += "nest ";
 
5749
  if (getByValAlign())
 
5750
    S += "byval-align:" + utostr(getByValAlign()) + " ";
 
5751
  if (getOrigAlign())
 
5752
    S += "orig-align:" + utostr(getOrigAlign()) + " ";
 
5753
  if (getByValSize())
 
5754
    S += "byval-size:" + utostr(getByValSize()) + " ";
 
5755
  return S + ">";
 
5756
}
 
5757
 
 
5758
void SDNode::dump() const { dump(0); }
 
5759
void SDNode::dump(const SelectionDAG *G) const {
 
5760
  print(dbgs(), G);
 
5761
}
 
5762
 
 
5763
void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
 
5764
  OS << (void*)this << ": ";
 
5765
 
 
5766
  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
 
5767
    if (i) OS << ",";
 
5768
    if (getValueType(i) == MVT::Other)
 
5769
      OS << "ch";
 
5770
    else
 
5771
      OS << getValueType(i).getEVTString();
 
5772
  }
 
5773
  OS << " = " << getOperationName(G);
 
5774
}
 
5775
 
 
5776
void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
 
5777
  if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
 
5778
    if (!MN->memoperands_empty()) {
 
5779
      OS << "<";
 
5780
      OS << "Mem:";
 
5781
      for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
 
5782
           e = MN->memoperands_end(); i != e; ++i) {
 
5783
        OS << **i;
 
5784
        if (next(i) != e)
 
5785
          OS << " ";
 
5786
      }
 
5787
      OS << ">";
 
5788
    }
 
5789
  } else if (const ShuffleVectorSDNode *SVN =
 
5790
               dyn_cast<ShuffleVectorSDNode>(this)) {
 
5791
    OS << "<";
 
5792
    for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
 
5793
      int Idx = SVN->getMaskElt(i);
 
5794
      if (i) OS << ",";
 
5795
      if (Idx < 0)
 
5796
        OS << "u";
 
5797
      else
 
5798
        OS << Idx;
 
5799
    }
 
5800
    OS << ">";
 
5801
  } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
 
5802
    OS << '<' << CSDN->getAPIntValue() << '>';
 
5803
  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
 
5804
    if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
 
5805
      OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
 
5806
    else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
 
5807
      OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
 
5808
    else {
 
5809
      OS << "<APFloat(";
 
5810
      CSDN->getValueAPF().bitcastToAPInt().dump();
 
5811
      OS << ")>";
 
5812
    }
 
5813
  } else if (const GlobalAddressSDNode *GADN =
 
5814
             dyn_cast<GlobalAddressSDNode>(this)) {
 
5815
    int64_t offset = GADN->getOffset();
 
5816
    OS << '<';
 
5817
    WriteAsOperand(OS, GADN->getGlobal());
 
5818
    OS << '>';
 
5819
    if (offset > 0)
 
5820
      OS << " + " << offset;
 
5821
    else
 
5822
      OS << " " << offset;
 
5823
    if (unsigned int TF = GADN->getTargetFlags())
 
5824
      OS << " [TF=" << TF << ']';
 
5825
  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
 
5826
    OS << "<" << FIDN->getIndex() << ">";
 
5827
  } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
 
5828
    OS << "<" << JTDN->getIndex() << ">";
 
5829
    if (unsigned int TF = JTDN->getTargetFlags())
 
5830
      OS << " [TF=" << TF << ']';
 
5831
  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
 
5832
    int offset = CP->getOffset();
 
5833
    if (CP->isMachineConstantPoolEntry())
 
5834
      OS << "<" << *CP->getMachineCPVal() << ">";
 
5835
    else
 
5836
      OS << "<" << *CP->getConstVal() << ">";
 
5837
    if (offset > 0)
 
5838
      OS << " + " << offset;
 
5839
    else
 
5840
      OS << " " << offset;
 
5841
    if (unsigned int TF = CP->getTargetFlags())
 
5842
      OS << " [TF=" << TF << ']';
 
5843
  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
 
5844
    OS << "<";
 
5845
    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
 
5846
    if (LBB)
 
5847
      OS << LBB->getName() << " ";
 
5848
    OS << (const void*)BBDN->getBasicBlock() << ">";
 
5849
  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
 
5850
    if (G && R->getReg() &&
 
5851
        TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
 
5852
      OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
 
5853
    } else {
 
5854
      OS << " %reg" << R->getReg();
 
5855
    }
 
5856
  } else if (const ExternalSymbolSDNode *ES =
 
5857
             dyn_cast<ExternalSymbolSDNode>(this)) {
 
5858
    OS << "'" << ES->getSymbol() << "'";
 
5859
    if (unsigned int TF = ES->getTargetFlags())
 
5860
      OS << " [TF=" << TF << ']';
 
5861
  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
 
5862
    if (M->getValue())
 
5863
      OS << "<" << M->getValue() << ">";
 
5864
    else
 
5865
      OS << "<null>";
 
5866
  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
 
5867
    OS << ":" << N->getVT().getEVTString();
 
5868
  }
 
5869
  else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
 
5870
    OS << "<" << *LD->getMemOperand();
 
5871
 
 
5872
    bool doExt = true;
 
5873
    switch (LD->getExtensionType()) {
 
5874
    default: doExt = false; break;
 
5875
    case ISD::EXTLOAD: OS << ", anyext"; break;
 
5876
    case ISD::SEXTLOAD: OS << ", sext"; break;
 
5877
    case ISD::ZEXTLOAD: OS << ", zext"; break;
 
5878
    }
 
5879
    if (doExt)
 
5880
      OS << " from " << LD->getMemoryVT().getEVTString();
 
5881
 
 
5882
    const char *AM = getIndexedModeName(LD->getAddressingMode());
 
5883
    if (*AM)
 
5884
      OS << ", " << AM;
 
5885
 
 
5886
    OS << ">";
 
5887
  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
 
5888
    OS << "<" << *ST->getMemOperand();
 
5889
 
 
5890
    if (ST->isTruncatingStore())
 
5891
      OS << ", trunc to " << ST->getMemoryVT().getEVTString();
 
5892
 
 
5893
    const char *AM = getIndexedModeName(ST->getAddressingMode());
 
5894
    if (*AM)
 
5895
      OS << ", " << AM;
 
5896
    
 
5897
    OS << ">";
 
5898
  } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
 
5899
    OS << "<" << *M->getMemOperand() << ">";
 
5900
  } else if (const BlockAddressSDNode *BA =
 
5901
               dyn_cast<BlockAddressSDNode>(this)) {
 
5902
    OS << "<";
 
5903
    WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
 
5904
    OS << ", ";
 
5905
    WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
 
5906
    OS << ">";
 
5907
    if (unsigned int TF = BA->getTargetFlags())
 
5908
      OS << " [TF=" << TF << ']';
 
5909
  }
 
5910
 
 
5911
  if (G)
 
5912
    if (unsigned Order = G->GetOrdering(this))
 
5913
      OS << " [ORD=" << Order << ']';
 
5914
  
 
5915
  if (getNodeId() != -1)
 
5916
    OS << " [ID=" << getNodeId() << ']';
 
5917
}
 
5918
 
 
5919
void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
 
5920
  print_types(OS, G);
 
5921
  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
 
5922
    if (i) OS << ", "; else OS << " ";
 
5923
    OS << (void*)getOperand(i).getNode();
 
5924
    if (unsigned RN = getOperand(i).getResNo())
 
5925
      OS << ":" << RN;
 
5926
  }
 
5927
  print_details(OS, G);
 
5928
}
 
5929
 
 
5930
static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
 
5931
                                  const SelectionDAG *G, unsigned depth,
 
5932
                                  unsigned indent) 
 
5933
{
 
5934
  if (depth == 0)
 
5935
    return;
 
5936
 
 
5937
  OS.indent(indent);
 
5938
 
 
5939
  N->print(OS, G);
 
5940
 
 
5941
  if (depth < 1)
 
5942
    return;
 
5943
 
 
5944
  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
 
5945
    OS << '\n';
 
5946
    printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, indent+2);
 
5947
  }
 
5948
}
 
5949
 
 
5950
void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
 
5951
                            unsigned depth) const {
 
5952
  printrWithDepthHelper(OS, this, G, depth, 0);
 
5953
 
5954
 
 
5955
void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
 
5956
  // Don't print impossibly deep things.
 
5957
  printrWithDepth(OS, G, 100);
 
5958
}
 
5959
 
 
5960
void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
 
5961
  printrWithDepth(dbgs(), G, depth);
 
5962
}
 
5963
 
 
5964
void SDNode::dumprFull(const SelectionDAG *G) const {
 
5965
  // Don't print impossibly deep things.
 
5966
  dumprWithDepth(G, 100);
 
5967
 
5968
 
 
5969
static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
 
5970
  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
 
5971
    if (N->getOperand(i).getNode()->hasOneUse())
 
5972
      DumpNodes(N->getOperand(i).getNode(), indent+2, G);
 
5973
    else
 
5974
      dbgs() << "\n" << std::string(indent+2, ' ')
 
5975
           << (void*)N->getOperand(i).getNode() << ": <multiple use>";
 
5976
 
 
5977
 
 
5978
  dbgs() << "\n";
 
5979
  dbgs().indent(indent);
 
5980
  N->dump(G);
 
5981
}
 
5982
 
 
5983
SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
 
5984
  assert(N->getNumValues() == 1 &&
 
5985
         "Can't unroll a vector with multiple results!");
 
5986
 
 
5987
  EVT VT = N->getValueType(0);
 
5988
  unsigned NE = VT.getVectorNumElements();
 
5989
  EVT EltVT = VT.getVectorElementType();
 
5990
  DebugLoc dl = N->getDebugLoc();
 
5991
 
 
5992
  SmallVector<SDValue, 8> Scalars;
 
5993
  SmallVector<SDValue, 4> Operands(N->getNumOperands());
 
5994
 
 
5995
  // If ResNE is 0, fully unroll the vector op.
 
5996
  if (ResNE == 0)
 
5997
    ResNE = NE;
 
5998
  else if (NE > ResNE)
 
5999
    NE = ResNE;
 
6000
 
 
6001
  unsigned i;
 
6002
  for (i= 0; i != NE; ++i) {
 
6003
    for (unsigned j = 0; j != N->getNumOperands(); ++j) {
 
6004
      SDValue Operand = N->getOperand(j);
 
6005
      EVT OperandVT = Operand.getValueType();
 
6006
      if (OperandVT.isVector()) {
 
6007
        // A vector operand; extract a single element.
 
6008
        EVT OperandEltVT = OperandVT.getVectorElementType();
 
6009
        Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
 
6010
                              OperandEltVT,
 
6011
                              Operand,
 
6012
                              getConstant(i, MVT::i32));
 
6013
      } else {
 
6014
        // A scalar operand; just use it as is.
 
6015
        Operands[j] = Operand;
 
6016
      }
 
6017
    }
 
6018
 
 
6019
    switch (N->getOpcode()) {
 
6020
    default:
 
6021
      Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
 
6022
                                &Operands[0], Operands.size()));
 
6023
      break;
 
6024
    case ISD::SHL:
 
6025
    case ISD::SRA:
 
6026
    case ISD::SRL:
 
6027
    case ISD::ROTL:
 
6028
    case ISD::ROTR:
 
6029
      Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
 
6030
                                getShiftAmountOperand(Operands[1])));
 
6031
      break;
 
6032
    case ISD::SIGN_EXTEND_INREG:
 
6033
    case ISD::FP_ROUND_INREG: {
 
6034
      EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
 
6035
      Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
 
6036
                                Operands[0],
 
6037
                                getValueType(ExtVT)));
 
6038
    }
 
6039
    }
 
6040
  }
 
6041
 
 
6042
  for (; i < ResNE; ++i)
 
6043
    Scalars.push_back(getUNDEF(EltVT));
 
6044
 
 
6045
  return getNode(ISD::BUILD_VECTOR, dl,
 
6046
                 EVT::getVectorVT(*getContext(), EltVT, ResNE),
 
6047
                 &Scalars[0], Scalars.size());
 
6048
}
 
6049
 
 
6050
 
 
6051
/// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a 
 
6052
/// location that is 'Dist' units away from the location that the 'Base' load 
 
6053
/// is loading from.
 
6054
bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base, 
 
6055
                                     unsigned Bytes, int Dist) const {
 
6056
  if (LD->getChain() != Base->getChain())
 
6057
    return false;
 
6058
  EVT VT = LD->getValueType(0);
 
6059
  if (VT.getSizeInBits() / 8 != Bytes)
 
6060
    return false;
 
6061
 
 
6062
  SDValue Loc = LD->getOperand(1);
 
6063
  SDValue BaseLoc = Base->getOperand(1);
 
6064
  if (Loc.getOpcode() == ISD::FrameIndex) {
 
6065
    if (BaseLoc.getOpcode() != ISD::FrameIndex)
 
6066
      return false;
 
6067
    const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
 
6068
    int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
 
6069
    int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
 
6070
    int FS  = MFI->getObjectSize(FI);
 
6071
    int BFS = MFI->getObjectSize(BFI);
 
6072
    if (FS != BFS || FS != (int)Bytes) return false;
 
6073
    return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
 
6074
  }
 
6075
  if (Loc.getOpcode() == ISD::ADD && Loc.getOperand(0) == BaseLoc) {
 
6076
    ConstantSDNode *V = dyn_cast<ConstantSDNode>(Loc.getOperand(1));
 
6077
    if (V && (V->getSExtValue() == Dist*Bytes))
 
6078
      return true;
 
6079
  }
 
6080
 
 
6081
  GlobalValue *GV1 = NULL;
 
6082
  GlobalValue *GV2 = NULL;
 
6083
  int64_t Offset1 = 0;
 
6084
  int64_t Offset2 = 0;
 
6085
  bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
 
6086
  bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
 
6087
  if (isGA1 && isGA2 && GV1 == GV2)
 
6088
    return Offset1 == (Offset2 + Dist*Bytes);
 
6089
  return false;
 
6090
}
 
6091
 
 
6092
 
 
6093
/// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
 
6094
/// it cannot be inferred.
 
6095
unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
 
6096
  // If this is a GlobalAddress + cst, return the alignment.
 
6097
  GlobalValue *GV;
 
6098
  int64_t GVOffset = 0;
 
6099
  if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset))
 
6100
    return MinAlign(GV->getAlignment(), GVOffset);
 
6101
 
 
6102
  // If this is a direct reference to a stack slot, use information about the
 
6103
  // stack slot's alignment.
 
6104
  int FrameIdx = 1 << 31;
 
6105
  int64_t FrameOffset = 0;
 
6106
  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
 
6107
    FrameIdx = FI->getIndex();
 
6108
  } else if (Ptr.getOpcode() == ISD::ADD &&
 
6109
             isa<ConstantSDNode>(Ptr.getOperand(1)) &&
 
6110
             isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
 
6111
    FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
 
6112
    FrameOffset = Ptr.getConstantOperandVal(1);
 
6113
  }
 
6114
 
 
6115
  if (FrameIdx != (1 << 31)) {
 
6116
    // FIXME: Handle FI+CST.
 
6117
    const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
 
6118
    unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
 
6119
                                    FrameOffset);
 
6120
    if (MFI.isFixedObjectIndex(FrameIdx)) {
 
6121
      int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
 
6122
 
 
6123
      // The alignment of the frame index can be determined from its offset from
 
6124
      // the incoming frame position.  If the frame object is at offset 32 and
 
6125
      // the stack is guaranteed to be 16-byte aligned, then we know that the
 
6126
      // object is 16-byte aligned.
 
6127
      unsigned StackAlign = getTarget().getFrameInfo()->getStackAlignment();
 
6128
      unsigned Align = MinAlign(ObjectOffset, StackAlign);
 
6129
 
 
6130
      // Finally, the frame object itself may have a known alignment.  Factor
 
6131
      // the alignment + offset into a new alignment.  For example, if we know
 
6132
      // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
 
6133
      // 4-byte alignment of the resultant pointer.  Likewise align 4 + 4-byte
 
6134
      // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
 
6135
      return std::max(Align, FIInfoAlign);
 
6136
    }
 
6137
    return FIInfoAlign;
 
6138
  }
 
6139
 
 
6140
  return 0;
 
6141
}
 
6142
 
 
6143
void SelectionDAG::dump() const {
 
6144
  dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
 
6145
 
 
6146
  for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
 
6147
       I != E; ++I) {
 
6148
    const SDNode *N = I;
 
6149
    if (!N->hasOneUse() && N != getRoot().getNode())
 
6150
      DumpNodes(N, 2, this);
 
6151
  }
 
6152
 
 
6153
  if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
 
6154
 
 
6155
  dbgs() << "\n\n";
 
6156
}
 
6157
 
 
6158
void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
 
6159
  print_types(OS, G);
 
6160
  print_details(OS, G);
 
6161
}
 
6162
 
 
6163
typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
 
6164
static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
 
6165
                       const SelectionDAG *G, VisitedSDNodeSet &once) {
 
6166
  if (!once.insert(N))          // If we've been here before, return now.
 
6167
    return;
 
6168
 
 
6169
  // Dump the current SDNode, but don't end the line yet.
 
6170
  OS << std::string(indent, ' ');
 
6171
  N->printr(OS, G);
 
6172
 
 
6173
  // Having printed this SDNode, walk the children:
 
6174
  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
 
6175
    const SDNode *child = N->getOperand(i).getNode();
 
6176
 
 
6177
    if (i) OS << ",";
 
6178
    OS << " ";
 
6179
 
 
6180
    if (child->getNumOperands() == 0) {
 
6181
      // This child has no grandchildren; print it inline right here.
 
6182
      child->printr(OS, G);
 
6183
      once.insert(child);
 
6184
    } else {         // Just the address. FIXME: also print the child's opcode.
 
6185
      OS << (void*)child;
 
6186
      if (unsigned RN = N->getOperand(i).getResNo())
 
6187
        OS << ":" << RN;
 
6188
    }
 
6189
  }
 
6190
 
 
6191
  OS << "\n";
 
6192
 
 
6193
  // Dump children that have grandchildren on their own line(s).
 
6194
  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
 
6195
    const SDNode *child = N->getOperand(i).getNode();
 
6196
    DumpNodesr(OS, child, indent+2, G, once);
 
6197
  }
 
6198
}
 
6199
 
 
6200
void SDNode::dumpr() const {
 
6201
  VisitedSDNodeSet once;
 
6202
  DumpNodesr(dbgs(), this, 0, 0, once);
 
6203
}
 
6204
 
 
6205
void SDNode::dumpr(const SelectionDAG *G) const {
 
6206
  VisitedSDNodeSet once;
 
6207
  DumpNodesr(dbgs(), this, 0, G, once);
 
6208
}
 
6209
 
 
6210
 
 
6211
// getAddressSpace - Return the address space this GlobalAddress belongs to.
 
6212
unsigned GlobalAddressSDNode::getAddressSpace() const {
 
6213
  return getGlobal()->getType()->getAddressSpace();
 
6214
}
 
6215
 
 
6216
 
 
6217
const Type *ConstantPoolSDNode::getType() const {
 
6218
  if (isMachineConstantPoolEntry())
 
6219
    return Val.MachineCPVal->getType();
 
6220
  return Val.ConstVal->getType();
 
6221
}
 
6222
 
 
6223
bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
 
6224
                                        APInt &SplatUndef,
 
6225
                                        unsigned &SplatBitSize,
 
6226
                                        bool &HasAnyUndefs,
 
6227
                                        unsigned MinSplatBits,
 
6228
                                        bool isBigEndian) {
 
6229
  EVT VT = getValueType(0);
 
6230
  assert(VT.isVector() && "Expected a vector type");
 
6231
  unsigned sz = VT.getSizeInBits();
 
6232
  if (MinSplatBits > sz)
 
6233
    return false;
 
6234
 
 
6235
  SplatValue = APInt(sz, 0);
 
6236
  SplatUndef = APInt(sz, 0);
 
6237
 
 
6238
  // Get the bits.  Bits with undefined values (when the corresponding element
 
6239
  // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
 
6240
  // in SplatValue.  If any of the values are not constant, give up and return
 
6241
  // false.
 
6242
  unsigned int nOps = getNumOperands();
 
6243
  assert(nOps > 0 && "isConstantSplat has 0-size build vector");
 
6244
  unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
 
6245
 
 
6246
  for (unsigned j = 0; j < nOps; ++j) {
 
6247
    unsigned i = isBigEndian ? nOps-1-j : j;
 
6248
    SDValue OpVal = getOperand(i);
 
6249
    unsigned BitPos = j * EltBitSize;
 
6250
 
 
6251
    if (OpVal.getOpcode() == ISD::UNDEF)
 
6252
      SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
 
6253
    else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
 
6254
      SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
 
6255
                     zextOrTrunc(sz) << BitPos);
 
6256
    else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
 
6257
      SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
 
6258
     else
 
6259
      return false;
 
6260
  }
 
6261
 
 
6262
  // The build_vector is all constants or undefs.  Find the smallest element
 
6263
  // size that splats the vector.
 
6264
 
 
6265
  HasAnyUndefs = (SplatUndef != 0);
 
6266
  while (sz > 8) {
 
6267
 
 
6268
    unsigned HalfSize = sz / 2;
 
6269
    APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
 
6270
    APInt LowValue = APInt(SplatValue).trunc(HalfSize);
 
6271
    APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
 
6272
    APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
 
6273
 
 
6274
    // If the two halves do not match (ignoring undef bits), stop here.
 
6275
    if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
 
6276
        MinSplatBits > HalfSize)
 
6277
      break;
 
6278
 
 
6279
    SplatValue = HighValue | LowValue;
 
6280
    SplatUndef = HighUndef & LowUndef;
 
6281
 
 
6282
    sz = HalfSize;
 
6283
  }
 
6284
 
 
6285
  SplatBitSize = sz;
 
6286
  return true;
 
6287
}
 
6288
 
 
6289
bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
 
6290
  // Find the first non-undef value in the shuffle mask.
 
6291
  unsigned i, e;
 
6292
  for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
 
6293
    /* search */;
 
6294
 
 
6295
  assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
 
6296
 
 
6297
  // Make sure all remaining elements are either undef or the same as the first
 
6298
  // non-undef value.
 
6299
  for (int Idx = Mask[i]; i != e; ++i)
 
6300
    if (Mask[i] >= 0 && Mask[i] != Idx)
 
6301
      return false;
 
6302
  return true;
 
6303
}
 
6304
 
 
6305
#ifdef XDEBUG
 
6306
static void checkForCyclesHelper(const SDNode *N,
 
6307
                                 SmallPtrSet<const SDNode*, 32> &Visited,
 
6308
                                 SmallPtrSet<const SDNode*, 32> &Checked) {
 
6309
  // If this node has already been checked, don't check it again.
 
6310
  if (Checked.count(N))
 
6311
    return;
 
6312
  
 
6313
  // If a node has already been visited on this depth-first walk, reject it as
 
6314
  // a cycle.
 
6315
  if (!Visited.insert(N)) {
 
6316
    dbgs() << "Offending node:\n";
 
6317
    N->dumprFull();
 
6318
    errs() << "Detected cycle in SelectionDAG\n";
 
6319
    abort();
 
6320
  }
 
6321
  
 
6322
  for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
 
6323
    checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
 
6324
  
 
6325
  Checked.insert(N);
 
6326
  Visited.erase(N);
 
6327
}
 
6328
#endif
 
6329
 
 
6330
void llvm::checkForCycles(const llvm::SDNode *N) {
 
6331
#ifdef XDEBUG
 
6332
  assert(N && "Checking nonexistant SDNode");
 
6333
  SmallPtrSet<const SDNode*, 32> visited;
 
6334
  SmallPtrSet<const SDNode*, 32> checked;
 
6335
  checkForCyclesHelper(N, visited, checked);
 
6336
#endif
 
6337
}
 
6338
 
 
6339
void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
 
6340
  checkForCycles(DAG->getRoot().getNode());
 
6341
}