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