1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SDNodeDbgValue.h"
16 #include "SelectionDAGBuilder.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/IntrinsicInst.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/Module.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/FastISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCStrategy.h"
37 #include "llvm/CodeGen/GCMetadata.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineJumpTableInfo.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/SelectionDAG.h"
45 #include "llvm/Analysis/DebugInfo.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetIntrinsicInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
60 /// LimitFloatPrecision - Generate low-precision inline sequences for
61 /// some float libcalls (6, 8 or 12 bits).
62 static unsigned LimitFloatPrecision;
64 static cl::opt<unsigned, true>
65 LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
71 // Limit the width of DAG chains. This is important in general to prevent
72 // prevent DAG-based analysis from blowing up. For example, alias analysis and
73 // load clustering may not complete in reasonable time. It is difficult to
74 // recognize and avoid this situation within each individual analysis, and
75 // future analyses are likely to have the same behavior. Limiting DAG width is
76 // the safe approach, and will be especially important with global DAGs.
78 // MaxParallelChains default is arbitrarily high to avoid affecting
79 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
80 // sequence over this should have been converted to llvm.memcpy by the
81 // frontend. It easy to induce this behavior with .ll code such as:
82 // %buffer = alloca [4096 x i8]
83 // %data = load [4096 x i8]* %argPtr
84 // store [4096 x i8] %data, [4096 x i8]* %buffer
85 static const unsigned MaxParallelChains = 64;
87 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
88 const SDValue *Parts, unsigned NumParts,
89 EVT PartVT, EVT ValueVT);
91 /// getCopyFromParts - Create a value that contains the specified legal parts
92 /// combined into the value they represent. If the parts combine to a type
93 /// larger then ValueVT then AssertOp can be used to specify whether the extra
94 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
95 /// (ISD::AssertSext).
96 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL,
98 unsigned NumParts, EVT PartVT, EVT ValueVT,
99 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
100 if (ValueVT.isVector())
101 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT);
103 assert(NumParts > 0 && "No parts to assemble!");
104 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
105 SDValue Val = Parts[0];
108 // Assemble the value from multiple parts.
109 if (ValueVT.isInteger()) {
110 unsigned PartBits = PartVT.getSizeInBits();
111 unsigned ValueBits = ValueVT.getSizeInBits();
113 // Assemble the power of 2 part.
114 unsigned RoundParts = NumParts & (NumParts - 1) ?
115 1 << Log2_32(NumParts) : NumParts;
116 unsigned RoundBits = PartBits * RoundParts;
117 EVT RoundVT = RoundBits == ValueBits ?
118 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
121 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
123 if (RoundParts > 2) {
124 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
126 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
127 RoundParts / 2, PartVT, HalfVT);
129 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
130 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
133 if (TLI.isBigEndian())
136 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
138 if (RoundParts < NumParts) {
139 // Assemble the trailing non-power-of-2 part.
140 unsigned OddParts = NumParts - RoundParts;
141 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
142 Hi = getCopyFromParts(DAG, DL,
143 Parts + RoundParts, OddParts, PartVT, OddVT);
145 // Combine the round and odd parts.
147 if (TLI.isBigEndian())
149 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
150 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
151 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
152 DAG.getConstant(Lo.getValueType().getSizeInBits(),
153 TLI.getPointerTy()));
154 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
155 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
157 } else if (PartVT.isFloatingPoint()) {
158 // FP split into multiple FP parts (for ppcf128)
159 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
162 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
163 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
164 if (TLI.isBigEndian())
166 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
168 // FP split into integer parts (soft fp)
169 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
170 !PartVT.isVector() && "Unexpected split");
171 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
172 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT);
176 // There is now one part, held in Val. Correct it to match ValueVT.
177 PartVT = Val.getValueType();
179 if (PartVT == ValueVT)
182 if (PartVT.isInteger() && ValueVT.isInteger()) {
183 if (ValueVT.bitsLT(PartVT)) {
184 // For a truncate, see if we have any information to
185 // indicate whether the truncated bits will always be
186 // zero or sign-extension.
187 if (AssertOp != ISD::DELETED_NODE)
188 Val = DAG.getNode(AssertOp, DL, PartVT, Val,
189 DAG.getValueType(ValueVT));
190 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
192 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
195 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
196 // FP_ROUND's are always exact here.
197 if (ValueVT.bitsLT(Val.getValueType()))
198 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
199 DAG.getIntPtrConstant(1));
201 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
204 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
205 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
207 llvm_unreachable("Unknown mismatch!");
211 /// getCopyFromParts - Create a value that contains the specified legal parts
212 /// combined into the value they represent. If the parts combine to a type
213 /// larger then ValueVT then AssertOp can be used to specify whether the extra
214 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
215 /// (ISD::AssertSext).
216 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
217 const SDValue *Parts, unsigned NumParts,
218 EVT PartVT, EVT ValueVT) {
219 assert(ValueVT.isVector() && "Not a vector value");
220 assert(NumParts > 0 && "No parts to assemble!");
221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
222 SDValue Val = Parts[0];
224 // Handle a multi-element vector.
226 EVT IntermediateVT, RegisterVT;
227 unsigned NumIntermediates;
229 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
230 NumIntermediates, RegisterVT);
231 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
232 NumParts = NumRegs; // Silence a compiler warning.
233 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
234 assert(RegisterVT == Parts[0].getValueType() &&
235 "Part type doesn't match part!");
237 // Assemble the parts into intermediate operands.
238 SmallVector<SDValue, 8> Ops(NumIntermediates);
239 if (NumIntermediates == NumParts) {
240 // If the register was not expanded, truncate or copy the value,
242 for (unsigned i = 0; i != NumParts; ++i)
243 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
244 PartVT, IntermediateVT);
245 } else if (NumParts > 0) {
246 // If the intermediate type was expanded, build the intermediate
247 // operands from the parts.
248 assert(NumParts % NumIntermediates == 0 &&
249 "Must expand into a divisible number of parts!");
250 unsigned Factor = NumParts / NumIntermediates;
251 for (unsigned i = 0; i != NumIntermediates; ++i)
252 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
253 PartVT, IntermediateVT);
256 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
257 // intermediate operands.
258 Val = DAG.getNode(IntermediateVT.isVector() ?
259 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
260 ValueVT, &Ops[0], NumIntermediates);
263 // There is now one part, held in Val. Correct it to match ValueVT.
264 PartVT = Val.getValueType();
266 if (PartVT == ValueVT)
269 if (PartVT.isVector()) {
270 // If the element type of the source/dest vectors are the same, but the
271 // parts vector has more elements than the value vector, then we have a
272 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
274 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
275 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
276 "Cannot narrow, it would be a lossy transformation");
277 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
278 DAG.getIntPtrConstant(0));
281 // Vector/Vector bitcast.
282 if (ValueVT.getSizeInBits() == PartVT.getSizeInBits())
283 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
285 assert(PartVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
286 "Cannot handle this kind of promotion");
287 // Promoted vector extract
288 bool Smaller = ValueVT.bitsLE(PartVT);
289 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
294 // Trivial bitcast if the types are the same size and the destination
295 // vector type is legal.
296 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits() &&
297 TLI.isTypeLegal(ValueVT))
298 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
300 // Handle cases such as i8 -> <1 x i1>
301 assert(ValueVT.getVectorNumElements() == 1 &&
302 "Only trivial scalar-to-vector conversions should get here!");
304 if (ValueVT.getVectorNumElements() == 1 &&
305 ValueVT.getVectorElementType() != PartVT) {
306 bool Smaller = ValueVT.bitsLE(PartVT);
307 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
308 DL, ValueVT.getScalarType(), Val);
311 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
317 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl,
318 SDValue Val, SDValue *Parts, unsigned NumParts,
321 /// getCopyToParts - Create a series of nodes that contain the specified value
322 /// split into legal parts. If the parts contain more bits than Val, then, for
323 /// integers, ExtendKind can be used to specify how to generate the extra bits.
324 static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL,
325 SDValue Val, SDValue *Parts, unsigned NumParts,
327 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
328 EVT ValueVT = Val.getValueType();
330 // Handle the vector case separately.
331 if (ValueVT.isVector())
332 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT);
334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
335 unsigned PartBits = PartVT.getSizeInBits();
336 unsigned OrigNumParts = NumParts;
337 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
342 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
343 if (PartVT == ValueVT) {
344 assert(NumParts == 1 && "No-op copy with multiple parts!");
349 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
350 // If the parts cover more bits than the value has, promote the value.
351 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
352 assert(NumParts == 1 && "Do not know what to promote to!");
353 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
355 assert(PartVT.isInteger() && ValueVT.isInteger() &&
356 "Unknown mismatch!");
357 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
358 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
360 } else if (PartBits == ValueVT.getSizeInBits()) {
361 // Different types of the same size.
362 assert(NumParts == 1 && PartVT != ValueVT);
363 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
364 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
365 // If the parts cover less bits than value has, truncate the value.
366 assert(PartVT.isInteger() && ValueVT.isInteger() &&
367 "Unknown mismatch!");
368 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
369 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
372 // The value may have changed - recompute ValueVT.
373 ValueVT = Val.getValueType();
374 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
375 "Failed to tile the value with PartVT!");
378 assert(PartVT == ValueVT && "Type conversion failed!");
383 // Expand the value into multiple parts.
384 if (NumParts & (NumParts - 1)) {
385 // The number of parts is not a power of 2. Split off and copy the tail.
386 assert(PartVT.isInteger() && ValueVT.isInteger() &&
387 "Do not know what to expand to!");
388 unsigned RoundParts = 1 << Log2_32(NumParts);
389 unsigned RoundBits = RoundParts * PartBits;
390 unsigned OddParts = NumParts - RoundParts;
391 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
392 DAG.getIntPtrConstant(RoundBits));
393 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT);
395 if (TLI.isBigEndian())
396 // The odd parts were reversed by getCopyToParts - unreverse them.
397 std::reverse(Parts + RoundParts, Parts + NumParts);
399 NumParts = RoundParts;
400 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
401 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
404 // The number of parts is a power of 2. Repeatedly bisect the value using
406 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
407 EVT::getIntegerVT(*DAG.getContext(),
408 ValueVT.getSizeInBits()),
411 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
412 for (unsigned i = 0; i < NumParts; i += StepSize) {
413 unsigned ThisBits = StepSize * PartBits / 2;
414 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
415 SDValue &Part0 = Parts[i];
416 SDValue &Part1 = Parts[i+StepSize/2];
418 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
419 ThisVT, Part0, DAG.getIntPtrConstant(1));
420 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
421 ThisVT, Part0, DAG.getIntPtrConstant(0));
423 if (ThisBits == PartBits && ThisVT != PartVT) {
424 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
425 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
430 if (TLI.isBigEndian())
431 std::reverse(Parts, Parts + OrigNumParts);
435 /// getCopyToPartsVector - Create a series of nodes that contain the specified
436 /// value split into legal parts.
437 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL,
438 SDValue Val, SDValue *Parts, unsigned NumParts,
440 EVT ValueVT = Val.getValueType();
441 assert(ValueVT.isVector() && "Not a vector");
442 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
445 if (PartVT == ValueVT) {
447 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
448 // Bitconvert vector->vector case.
449 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
450 } else if (PartVT.isVector() &&
451 PartVT.getVectorElementType() == ValueVT.getVectorElementType() &&
452 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
453 EVT ElementVT = PartVT.getVectorElementType();
454 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
456 SmallVector<SDValue, 16> Ops;
457 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
458 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
459 ElementVT, Val, DAG.getIntPtrConstant(i)));
461 for (unsigned i = ValueVT.getVectorNumElements(),
462 e = PartVT.getVectorNumElements(); i != e; ++i)
463 Ops.push_back(DAG.getUNDEF(ElementVT));
465 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
467 // FIXME: Use CONCAT for 2x -> 4x.
469 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
470 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
471 } else if (PartVT.isVector() &&
472 PartVT.getVectorElementType().bitsGE(
473 ValueVT.getVectorElementType()) &&
474 PartVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
476 // Promoted vector extract
477 bool Smaller = PartVT.bitsLE(ValueVT);
478 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
481 // Vector -> scalar conversion.
482 assert(ValueVT.getVectorNumElements() == 1 &&
483 "Only trivial vector-to-scalar conversions should get here!");
484 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
485 PartVT, Val, DAG.getIntPtrConstant(0));
487 bool Smaller = ValueVT.bitsLE(PartVT);
488 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
496 // Handle a multi-element vector.
497 EVT IntermediateVT, RegisterVT;
498 unsigned NumIntermediates;
499 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
501 NumIntermediates, RegisterVT);
502 unsigned NumElements = ValueVT.getVectorNumElements();
504 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
505 NumParts = NumRegs; // Silence a compiler warning.
506 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
508 // Split the vector into intermediate operands.
509 SmallVector<SDValue, 8> Ops(NumIntermediates);
510 for (unsigned i = 0; i != NumIntermediates; ++i) {
511 if (IntermediateVT.isVector())
512 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
514 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
516 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
517 IntermediateVT, Val, DAG.getIntPtrConstant(i));
520 // Split the intermediate operands into legal parts.
521 if (NumParts == NumIntermediates) {
522 // If the register was not expanded, promote or copy the value,
524 for (unsigned i = 0; i != NumParts; ++i)
525 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT);
526 } else if (NumParts > 0) {
527 // If the intermediate type was expanded, split each the value into
529 assert(NumParts % NumIntermediates == 0 &&
530 "Must expand into a divisible number of parts!");
531 unsigned Factor = NumParts / NumIntermediates;
532 for (unsigned i = 0; i != NumIntermediates; ++i)
533 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT);
541 /// RegsForValue - This struct represents the registers (physical or virtual)
542 /// that a particular set of values is assigned, and the type information
543 /// about the value. The most common situation is to represent one value at a
544 /// time, but struct or array values are handled element-wise as multiple
545 /// values. The splitting of aggregates is performed recursively, so that we
546 /// never have aggregate-typed registers. The values at this point do not
547 /// necessarily have legal types, so each value may require one or more
548 /// registers of some legal type.
550 struct RegsForValue {
551 /// ValueVTs - The value types of the values, which may not be legal, and
552 /// may need be promoted or synthesized from one or more registers.
554 SmallVector<EVT, 4> ValueVTs;
556 /// RegVTs - The value types of the registers. This is the same size as
557 /// ValueVTs and it records, for each value, what the type of the assigned
558 /// register or registers are. (Individual values are never synthesized
559 /// from more than one type of register.)
561 /// With virtual registers, the contents of RegVTs is redundant with TLI's
562 /// getRegisterType member function, however when with physical registers
563 /// it is necessary to have a separate record of the types.
565 SmallVector<EVT, 4> RegVTs;
567 /// Regs - This list holds the registers assigned to the values.
568 /// Each legal or promoted value requires one register, and each
569 /// expanded value requires multiple registers.
571 SmallVector<unsigned, 4> Regs;
575 RegsForValue(const SmallVector<unsigned, 4> ®s,
576 EVT regvt, EVT valuevt)
577 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
579 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
580 unsigned Reg, Type *Ty) {
581 ComputeValueVTs(tli, Ty, ValueVTs);
583 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
584 EVT ValueVT = ValueVTs[Value];
585 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
586 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
587 for (unsigned i = 0; i != NumRegs; ++i)
588 Regs.push_back(Reg + i);
589 RegVTs.push_back(RegisterVT);
594 /// areValueTypesLegal - Return true if types of all the values are legal.
595 bool areValueTypesLegal(const TargetLowering &TLI) {
596 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
597 EVT RegisterVT = RegVTs[Value];
598 if (!TLI.isTypeLegal(RegisterVT))
604 /// append - Add the specified values to this one.
605 void append(const RegsForValue &RHS) {
606 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
607 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
608 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
611 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
612 /// this value and returns the result as a ValueVTs value. This uses
613 /// Chain/Flag as the input and updates them for the output Chain/Flag.
614 /// If the Flag pointer is NULL, no flag is used.
615 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
617 SDValue &Chain, SDValue *Flag) const;
619 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
620 /// specified value into the registers specified by this object. This uses
621 /// Chain/Flag as the input and updates them for the output Chain/Flag.
622 /// If the Flag pointer is NULL, no flag is used.
623 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
624 SDValue &Chain, SDValue *Flag) const;
626 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
627 /// operand list. This adds the code marker, matching input operand index
628 /// (if applicable), and includes the number of values added into it.
629 void AddInlineAsmOperands(unsigned Kind,
630 bool HasMatching, unsigned MatchingIdx,
632 std::vector<SDValue> &Ops) const;
636 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
637 /// this value and returns the result as a ValueVT value. This uses
638 /// Chain/Flag as the input and updates them for the output Chain/Flag.
639 /// If the Flag pointer is NULL, no flag is used.
640 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
641 FunctionLoweringInfo &FuncInfo,
643 SDValue &Chain, SDValue *Flag) const {
644 // A Value with type {} or [0 x %t] needs no registers.
645 if (ValueVTs.empty())
648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
650 // Assemble the legal parts into the final values.
651 SmallVector<SDValue, 4> Values(ValueVTs.size());
652 SmallVector<SDValue, 8> Parts;
653 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
654 // Copy the legal parts from the registers.
655 EVT ValueVT = ValueVTs[Value];
656 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
657 EVT RegisterVT = RegVTs[Value];
659 Parts.resize(NumRegs);
660 for (unsigned i = 0; i != NumRegs; ++i) {
663 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
665 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
666 *Flag = P.getValue(2);
669 Chain = P.getValue(1);
672 // If the source register was virtual and if we know something about it,
673 // add an assert node.
674 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
675 !RegisterVT.isInteger() || RegisterVT.isVector())
678 const FunctionLoweringInfo::LiveOutInfo *LOI =
679 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
683 unsigned RegSize = RegisterVT.getSizeInBits();
684 unsigned NumSignBits = LOI->NumSignBits;
685 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
687 // FIXME: We capture more information than the dag can represent. For
688 // now, just use the tightest assertzext/assertsext possible.
690 EVT FromVT(MVT::Other);
691 if (NumSignBits == RegSize)
692 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
693 else if (NumZeroBits >= RegSize-1)
694 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
695 else if (NumSignBits > RegSize-8)
696 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
697 else if (NumZeroBits >= RegSize-8)
698 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
699 else if (NumSignBits > RegSize-16)
700 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
701 else if (NumZeroBits >= RegSize-16)
702 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
703 else if (NumSignBits > RegSize-32)
704 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
705 else if (NumZeroBits >= RegSize-32)
706 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
710 // Add an assertion node.
711 assert(FromVT != MVT::Other);
712 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
713 RegisterVT, P, DAG.getValueType(FromVT));
716 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
717 NumRegs, RegisterVT, ValueVT);
722 return DAG.getNode(ISD::MERGE_VALUES, dl,
723 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
724 &Values[0], ValueVTs.size());
727 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
728 /// specified value into the registers specified by this object. This uses
729 /// Chain/Flag as the input and updates them for the output Chain/Flag.
730 /// If the Flag pointer is NULL, no flag is used.
731 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
732 SDValue &Chain, SDValue *Flag) const {
733 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
735 // Get the list of the values's legal parts.
736 unsigned NumRegs = Regs.size();
737 SmallVector<SDValue, 8> Parts(NumRegs);
738 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
739 EVT ValueVT = ValueVTs[Value];
740 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
741 EVT RegisterVT = RegVTs[Value];
743 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
744 &Parts[Part], NumParts, RegisterVT);
748 // Copy the parts into the registers.
749 SmallVector<SDValue, 8> Chains(NumRegs);
750 for (unsigned i = 0; i != NumRegs; ++i) {
753 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
755 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
756 *Flag = Part.getValue(1);
759 Chains[i] = Part.getValue(0);
762 if (NumRegs == 1 || Flag)
763 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
764 // flagged to it. That is the CopyToReg nodes and the user are considered
765 // a single scheduling unit. If we create a TokenFactor and return it as
766 // chain, then the TokenFactor is both a predecessor (operand) of the
767 // user as well as a successor (the TF operands are flagged to the user).
768 // c1, f1 = CopyToReg
769 // c2, f2 = CopyToReg
770 // c3 = TokenFactor c1, c2
773 Chain = Chains[NumRegs-1];
775 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
778 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
779 /// operand list. This adds the code marker and includes the number of
780 /// values added into it.
781 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
782 unsigned MatchingIdx,
784 std::vector<SDValue> &Ops) const {
785 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
787 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
789 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
790 else if (!Regs.empty() &&
791 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
792 // Put the register class of the virtual registers in the flag word. That
793 // way, later passes can recompute register class constraints for inline
794 // assembly as well as normal instructions.
795 // Don't do this for tied operands that can use the regclass information
797 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
798 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
799 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
802 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
805 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
806 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
807 EVT RegisterVT = RegVTs[Value];
808 for (unsigned i = 0; i != NumRegs; ++i) {
809 assert(Reg < Regs.size() && "Mismatch in # registers expected");
810 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
815 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
818 TD = DAG.getTarget().getTargetData();
819 LPadToCallSiteMap.clear();
822 /// clear - Clear out the current SelectionDAG and the associated
823 /// state and prepare this SelectionDAGBuilder object to be used
824 /// for a new block. This doesn't clear out information about
825 /// additional blocks that are needed to complete switch lowering
826 /// or PHI node updating; that information is cleared out as it is
828 void SelectionDAGBuilder::clear() {
830 UnusedArgNodeMap.clear();
831 PendingLoads.clear();
832 PendingExports.clear();
833 CurDebugLoc = DebugLoc();
837 /// clearDanglingDebugInfo - Clear the dangling debug information
838 /// map. This function is seperated from the clear so that debug
839 /// information that is dangling in a basic block can be properly
840 /// resolved in a different basic block. This allows the
841 /// SelectionDAG to resolve dangling debug information attached
843 void SelectionDAGBuilder::clearDanglingDebugInfo() {
844 DanglingDebugInfoMap.clear();
847 /// getRoot - Return the current virtual root of the Selection DAG,
848 /// flushing any PendingLoad items. This must be done before emitting
849 /// a store or any other node that may need to be ordered after any
850 /// prior load instructions.
852 SDValue SelectionDAGBuilder::getRoot() {
853 if (PendingLoads.empty())
854 return DAG.getRoot();
856 if (PendingLoads.size() == 1) {
857 SDValue Root = PendingLoads[0];
859 PendingLoads.clear();
863 // Otherwise, we have to make a token factor node.
864 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
865 &PendingLoads[0], PendingLoads.size());
866 PendingLoads.clear();
871 /// getControlRoot - Similar to getRoot, but instead of flushing all the
872 /// PendingLoad items, flush all the PendingExports items. It is necessary
873 /// to do this before emitting a terminator instruction.
875 SDValue SelectionDAGBuilder::getControlRoot() {
876 SDValue Root = DAG.getRoot();
878 if (PendingExports.empty())
881 // Turn all of the CopyToReg chains into one factored node.
882 if (Root.getOpcode() != ISD::EntryToken) {
883 unsigned i = 0, e = PendingExports.size();
884 for (; i != e; ++i) {
885 assert(PendingExports[i].getNode()->getNumOperands() > 1);
886 if (PendingExports[i].getNode()->getOperand(0) == Root)
887 break; // Don't add the root if we already indirectly depend on it.
891 PendingExports.push_back(Root);
894 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
896 PendingExports.size());
897 PendingExports.clear();
902 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
903 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
904 DAG.AssignOrdering(Node, SDNodeOrder);
906 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
907 AssignOrderingToNode(Node->getOperand(I).getNode());
910 void SelectionDAGBuilder::visit(const Instruction &I) {
911 // Set up outgoing PHI node register values before emitting the terminator.
912 if (isa<TerminatorInst>(&I))
913 HandlePHINodesInSuccessorBlocks(I.getParent());
915 CurDebugLoc = I.getDebugLoc();
917 visit(I.getOpcode(), I);
919 if (!isa<TerminatorInst>(&I) && !HasTailCall)
920 CopyToExportRegsIfNeeded(&I);
922 CurDebugLoc = DebugLoc();
925 void SelectionDAGBuilder::visitPHI(const PHINode &) {
926 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
929 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
930 // Note: this doesn't use InstVisitor, because it has to work with
931 // ConstantExpr's in addition to instructions.
933 default: llvm_unreachable("Unknown instruction type encountered!");
934 // Build the switch statement using the Instruction.def file.
935 #define HANDLE_INST(NUM, OPCODE, CLASS) \
936 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
937 #include "llvm/Instruction.def"
940 // Assign the ordering to the freshly created DAG nodes.
941 if (NodeMap.count(&I)) {
943 AssignOrderingToNode(getValue(&I).getNode());
947 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
948 // generate the debug data structures now that we've seen its definition.
949 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
951 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
953 const DbgValueInst *DI = DDI.getDI();
954 DebugLoc dl = DDI.getdl();
955 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
956 MDNode *Variable = DI->getVariable();
957 uint64_t Offset = DI->getOffset();
960 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
961 SDV = DAG.getDbgValue(Variable, Val.getNode(),
962 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
963 DAG.AddDbgValue(SDV, Val.getNode(), false);
966 DEBUG(dbgs() << "Dropping debug info for " << DI);
967 DanglingDebugInfoMap[V] = DanglingDebugInfo();
971 /// getValue - Return an SDValue for the given Value.
972 SDValue SelectionDAGBuilder::getValue(const Value *V) {
973 // If we already have an SDValue for this value, use it. It's important
974 // to do this first, so that we don't create a CopyFromReg if we already
975 // have a regular SDValue.
976 SDValue &N = NodeMap[V];
977 if (N.getNode()) return N;
979 // If there's a virtual register allocated and initialized for this
981 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
982 if (It != FuncInfo.ValueMap.end()) {
983 unsigned InReg = It->second;
984 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
985 SDValue Chain = DAG.getEntryNode();
986 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
987 resolveDanglingDebugInfo(V, N);
991 // Otherwise create a new SDValue and remember it.
992 SDValue Val = getValueImpl(V);
994 resolveDanglingDebugInfo(V, Val);
998 /// getNonRegisterValue - Return an SDValue for the given Value, but
999 /// don't look in FuncInfo.ValueMap for a virtual register.
1000 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1001 // If we already have an SDValue for this value, use it.
1002 SDValue &N = NodeMap[V];
1003 if (N.getNode()) return N;
1005 // Otherwise create a new SDValue and remember it.
1006 SDValue Val = getValueImpl(V);
1008 resolveDanglingDebugInfo(V, Val);
1012 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1013 /// Create an SDValue for the given value.
1014 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1015 if (const Constant *C = dyn_cast<Constant>(V)) {
1016 EVT VT = TLI.getValueType(V->getType(), true);
1018 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1019 return DAG.getConstant(*CI, VT);
1021 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1022 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
1024 if (isa<ConstantPointerNull>(C))
1025 return DAG.getConstant(0, TLI.getPointerTy());
1027 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1028 return DAG.getConstantFP(*CFP, VT);
1030 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1031 return DAG.getUNDEF(VT);
1033 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1034 visit(CE->getOpcode(), *CE);
1035 SDValue N1 = NodeMap[V];
1036 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1040 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1041 SmallVector<SDValue, 4> Constants;
1042 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1044 SDNode *Val = getValue(*OI).getNode();
1045 // If the operand is an empty aggregate, there are no values.
1047 // Add each leaf value from the operand to the Constants list
1048 // to form a flattened list of all the values.
1049 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1050 Constants.push_back(SDValue(Val, i));
1053 return DAG.getMergeValues(&Constants[0], Constants.size(),
1057 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1058 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1059 "Unknown struct or array constant!");
1061 SmallVector<EVT, 4> ValueVTs;
1062 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1063 unsigned NumElts = ValueVTs.size();
1065 return SDValue(); // empty struct
1066 SmallVector<SDValue, 4> Constants(NumElts);
1067 for (unsigned i = 0; i != NumElts; ++i) {
1068 EVT EltVT = ValueVTs[i];
1069 if (isa<UndefValue>(C))
1070 Constants[i] = DAG.getUNDEF(EltVT);
1071 else if (EltVT.isFloatingPoint())
1072 Constants[i] = DAG.getConstantFP(0, EltVT);
1074 Constants[i] = DAG.getConstant(0, EltVT);
1077 return DAG.getMergeValues(&Constants[0], NumElts,
1081 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1082 return DAG.getBlockAddress(BA, VT);
1084 VectorType *VecTy = cast<VectorType>(V->getType());
1085 unsigned NumElements = VecTy->getNumElements();
1087 // Now that we know the number and type of the elements, get that number of
1088 // elements into the Ops array based on what kind of constant it is.
1089 SmallVector<SDValue, 16> Ops;
1090 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1091 for (unsigned i = 0; i != NumElements; ++i)
1092 Ops.push_back(getValue(CP->getOperand(i)));
1094 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1095 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1098 if (EltVT.isFloatingPoint())
1099 Op = DAG.getConstantFP(0, EltVT);
1101 Op = DAG.getConstant(0, EltVT);
1102 Ops.assign(NumElements, Op);
1105 // Create a BUILD_VECTOR node.
1106 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1107 VT, &Ops[0], Ops.size());
1110 // If this is a static alloca, generate it as the frameindex instead of
1112 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1113 DenseMap<const AllocaInst*, int>::iterator SI =
1114 FuncInfo.StaticAllocaMap.find(AI);
1115 if (SI != FuncInfo.StaticAllocaMap.end())
1116 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1119 // If this is an instruction which fast-isel has deferred, select it now.
1120 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1121 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1122 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1123 SDValue Chain = DAG.getEntryNode();
1124 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
1127 llvm_unreachable("Can't get register for value!");
1131 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1132 SDValue Chain = getControlRoot();
1133 SmallVector<ISD::OutputArg, 8> Outs;
1134 SmallVector<SDValue, 8> OutVals;
1136 if (!FuncInfo.CanLowerReturn) {
1137 unsigned DemoteReg = FuncInfo.DemoteRegister;
1138 const Function *F = I.getParent()->getParent();
1140 // Emit a store of the return value through the virtual register.
1141 // Leave Outs empty so that LowerReturn won't try to load return
1142 // registers the usual way.
1143 SmallVector<EVT, 1> PtrValueVTs;
1144 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1147 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1148 SDValue RetOp = getValue(I.getOperand(0));
1150 SmallVector<EVT, 4> ValueVTs;
1151 SmallVector<uint64_t, 4> Offsets;
1152 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1153 unsigned NumValues = ValueVTs.size();
1155 SmallVector<SDValue, 4> Chains(NumValues);
1156 for (unsigned i = 0; i != NumValues; ++i) {
1157 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
1158 RetPtr.getValueType(), RetPtr,
1159 DAG.getIntPtrConstant(Offsets[i]));
1161 DAG.getStore(Chain, getCurDebugLoc(),
1162 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1163 // FIXME: better loc info would be nice.
1164 Add, MachinePointerInfo(), false, false, 0);
1167 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1168 MVT::Other, &Chains[0], NumValues);
1169 } else if (I.getNumOperands() != 0) {
1170 SmallVector<EVT, 4> ValueVTs;
1171 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1172 unsigned NumValues = ValueVTs.size();
1174 SDValue RetOp = getValue(I.getOperand(0));
1175 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1176 EVT VT = ValueVTs[j];
1178 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1180 const Function *F = I.getParent()->getParent();
1181 if (F->paramHasAttr(0, Attribute::SExt))
1182 ExtendKind = ISD::SIGN_EXTEND;
1183 else if (F->paramHasAttr(0, Attribute::ZExt))
1184 ExtendKind = ISD::ZERO_EXTEND;
1186 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1187 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1189 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1190 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1191 SmallVector<SDValue, 4> Parts(NumParts);
1192 getCopyToParts(DAG, getCurDebugLoc(),
1193 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1194 &Parts[0], NumParts, PartVT, ExtendKind);
1196 // 'inreg' on function refers to return value
1197 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1198 if (F->paramHasAttr(0, Attribute::InReg))
1201 // Propagate extension type if any
1202 if (ExtendKind == ISD::SIGN_EXTEND)
1204 else if (ExtendKind == ISD::ZERO_EXTEND)
1207 for (unsigned i = 0; i < NumParts; ++i) {
1208 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1210 OutVals.push_back(Parts[i]);
1216 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1217 CallingConv::ID CallConv =
1218 DAG.getMachineFunction().getFunction()->getCallingConv();
1219 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1220 Outs, OutVals, getCurDebugLoc(), DAG);
1222 // Verify that the target's LowerReturn behaved as expected.
1223 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1224 "LowerReturn didn't return a valid chain!");
1226 // Update the DAG with the new chain value resulting from return lowering.
1230 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1231 /// created for it, emit nodes to copy the value into the virtual
1233 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1235 if (V->getType()->isEmptyTy())
1238 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1239 if (VMI != FuncInfo.ValueMap.end()) {
1240 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1241 CopyValueToVirtualRegister(V, VMI->second);
1245 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1246 /// the current basic block, add it to ValueMap now so that we'll get a
1248 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1249 // No need to export constants.
1250 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1252 // Already exported?
1253 if (FuncInfo.isExportedInst(V)) return;
1255 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1256 CopyValueToVirtualRegister(V, Reg);
1259 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1260 const BasicBlock *FromBB) {
1261 // The operands of the setcc have to be in this block. We don't know
1262 // how to export them from some other block.
1263 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1264 // Can export from current BB.
1265 if (VI->getParent() == FromBB)
1268 // Is already exported, noop.
1269 return FuncInfo.isExportedInst(V);
1272 // If this is an argument, we can export it if the BB is the entry block or
1273 // if it is already exported.
1274 if (isa<Argument>(V)) {
1275 if (FromBB == &FromBB->getParent()->getEntryBlock())
1278 // Otherwise, can only export this if it is already exported.
1279 return FuncInfo.isExportedInst(V);
1282 // Otherwise, constants can always be exported.
1286 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1287 uint32_t SelectionDAGBuilder::getEdgeWeight(MachineBasicBlock *Src,
1288 MachineBasicBlock *Dst) {
1289 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1292 const BasicBlock *SrcBB = Src->getBasicBlock();
1293 const BasicBlock *DstBB = Dst->getBasicBlock();
1294 return BPI->getEdgeWeight(SrcBB, DstBB);
1297 void SelectionDAGBuilder::
1298 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1299 uint32_t Weight /* = 0 */) {
1301 Weight = getEdgeWeight(Src, Dst);
1302 Src->addSuccessor(Dst, Weight);
1306 static bool InBlock(const Value *V, const BasicBlock *BB) {
1307 if (const Instruction *I = dyn_cast<Instruction>(V))
1308 return I->getParent() == BB;
1312 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1313 /// This function emits a branch and is used at the leaves of an OR or an
1314 /// AND operator tree.
1317 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1318 MachineBasicBlock *TBB,
1319 MachineBasicBlock *FBB,
1320 MachineBasicBlock *CurBB,
1321 MachineBasicBlock *SwitchBB) {
1322 const BasicBlock *BB = CurBB->getBasicBlock();
1324 // If the leaf of the tree is a comparison, merge the condition into
1326 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1327 // The operands of the cmp have to be in this block. We don't know
1328 // how to export them from some other block. If this is the first block
1329 // of the sequence, no exporting is needed.
1330 if (CurBB == SwitchBB ||
1331 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1332 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1333 ISD::CondCode Condition;
1334 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1335 Condition = getICmpCondCode(IC->getPredicate());
1336 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1337 Condition = getFCmpCondCode(FC->getPredicate());
1339 Condition = ISD::SETEQ; // silence warning.
1340 llvm_unreachable("Unknown compare instruction");
1343 CaseBlock CB(Condition, BOp->getOperand(0),
1344 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1345 SwitchCases.push_back(CB);
1350 // Create a CaseBlock record representing this branch.
1351 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1352 NULL, TBB, FBB, CurBB);
1353 SwitchCases.push_back(CB);
1356 /// FindMergedConditions - If Cond is an expression like
1357 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1358 MachineBasicBlock *TBB,
1359 MachineBasicBlock *FBB,
1360 MachineBasicBlock *CurBB,
1361 MachineBasicBlock *SwitchBB,
1363 // If this node is not part of the or/and tree, emit it as a branch.
1364 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1365 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1366 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1367 BOp->getParent() != CurBB->getBasicBlock() ||
1368 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1369 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1370 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1374 // Create TmpBB after CurBB.
1375 MachineFunction::iterator BBI = CurBB;
1376 MachineFunction &MF = DAG.getMachineFunction();
1377 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1378 CurBB->getParent()->insert(++BBI, TmpBB);
1380 if (Opc == Instruction::Or) {
1381 // Codegen X | Y as:
1389 // Emit the LHS condition.
1390 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1392 // Emit the RHS condition into TmpBB.
1393 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1395 assert(Opc == Instruction::And && "Unknown merge op!");
1396 // Codegen X & Y as:
1403 // This requires creation of TmpBB after CurBB.
1405 // Emit the LHS condition.
1406 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1408 // Emit the RHS condition into TmpBB.
1409 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1413 /// If the set of cases should be emitted as a series of branches, return true.
1414 /// If we should emit this as a bunch of and/or'd together conditions, return
1417 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1418 if (Cases.size() != 2) return true;
1420 // If this is two comparisons of the same values or'd or and'd together, they
1421 // will get folded into a single comparison, so don't emit two blocks.
1422 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1423 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1424 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1425 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1429 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1430 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1431 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1432 Cases[0].CC == Cases[1].CC &&
1433 isa<Constant>(Cases[0].CmpRHS) &&
1434 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1435 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1437 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1444 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1445 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1447 // Update machine-CFG edges.
1448 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1450 // Figure out which block is immediately after the current one.
1451 MachineBasicBlock *NextBlock = 0;
1452 MachineFunction::iterator BBI = BrMBB;
1453 if (++BBI != FuncInfo.MF->end())
1456 if (I.isUnconditional()) {
1457 // Update machine-CFG edges.
1458 BrMBB->addSuccessor(Succ0MBB);
1460 // If this is not a fall-through branch, emit the branch.
1461 if (Succ0MBB != NextBlock)
1462 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1463 MVT::Other, getControlRoot(),
1464 DAG.getBasicBlock(Succ0MBB)));
1469 // If this condition is one of the special cases we handle, do special stuff
1471 const Value *CondVal = I.getCondition();
1472 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1474 // If this is a series of conditions that are or'd or and'd together, emit
1475 // this as a sequence of branches instead of setcc's with and/or operations.
1476 // As long as jumps are not expensive, this should improve performance.
1477 // For example, instead of something like:
1490 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1491 if (!TLI.isJumpExpensive() &&
1493 (BOp->getOpcode() == Instruction::And ||
1494 BOp->getOpcode() == Instruction::Or)) {
1495 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1497 // If the compares in later blocks need to use values not currently
1498 // exported from this block, export them now. This block should always
1499 // be the first entry.
1500 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1502 // Allow some cases to be rejected.
1503 if (ShouldEmitAsBranches(SwitchCases)) {
1504 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1505 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1506 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1509 // Emit the branch for this block.
1510 visitSwitchCase(SwitchCases[0], BrMBB);
1511 SwitchCases.erase(SwitchCases.begin());
1515 // Okay, we decided not to do this, remove any inserted MBB's and clear
1517 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1518 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1520 SwitchCases.clear();
1524 // Create a CaseBlock record representing this branch.
1525 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1526 NULL, Succ0MBB, Succ1MBB, BrMBB);
1528 // Use visitSwitchCase to actually insert the fast branch sequence for this
1530 visitSwitchCase(CB, BrMBB);
1533 /// visitSwitchCase - Emits the necessary code to represent a single node in
1534 /// the binary search tree resulting from lowering a switch instruction.
1535 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1536 MachineBasicBlock *SwitchBB) {
1538 SDValue CondLHS = getValue(CB.CmpLHS);
1539 DebugLoc dl = getCurDebugLoc();
1541 // Build the setcc now.
1542 if (CB.CmpMHS == NULL) {
1543 // Fold "(X == true)" to X and "(X == false)" to !X to
1544 // handle common cases produced by branch lowering.
1545 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1546 CB.CC == ISD::SETEQ)
1548 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1549 CB.CC == ISD::SETEQ) {
1550 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1551 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1553 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1555 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1557 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1558 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1560 SDValue CmpOp = getValue(CB.CmpMHS);
1561 EVT VT = CmpOp.getValueType();
1563 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1564 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1567 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1568 VT, CmpOp, DAG.getConstant(Low, VT));
1569 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1570 DAG.getConstant(High-Low, VT), ISD::SETULE);
1574 // Update successor info
1575 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1576 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1578 // Set NextBlock to be the MBB immediately after the current one, if any.
1579 // This is used to avoid emitting unnecessary branches to the next block.
1580 MachineBasicBlock *NextBlock = 0;
1581 MachineFunction::iterator BBI = SwitchBB;
1582 if (++BBI != FuncInfo.MF->end())
1585 // If the lhs block is the next block, invert the condition so that we can
1586 // fall through to the lhs instead of the rhs block.
1587 if (CB.TrueBB == NextBlock) {
1588 std::swap(CB.TrueBB, CB.FalseBB);
1589 SDValue True = DAG.getConstant(1, Cond.getValueType());
1590 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1593 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1594 MVT::Other, getControlRoot(), Cond,
1595 DAG.getBasicBlock(CB.TrueBB));
1597 // Insert the false branch. Do this even if it's a fall through branch,
1598 // this makes it easier to do DAG optimizations which require inverting
1599 // the branch condition.
1600 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1601 DAG.getBasicBlock(CB.FalseBB));
1603 DAG.setRoot(BrCond);
1606 /// visitJumpTable - Emit JumpTable node in the current MBB
1607 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1608 // Emit the code for the jump table
1609 assert(JT.Reg != -1U && "Should lower JT Header first!");
1610 EVT PTy = TLI.getPointerTy();
1611 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1613 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1614 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1615 MVT::Other, Index.getValue(1),
1617 DAG.setRoot(BrJumpTable);
1620 /// visitJumpTableHeader - This function emits necessary code to produce index
1621 /// in the JumpTable from switch case.
1622 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1623 JumpTableHeader &JTH,
1624 MachineBasicBlock *SwitchBB) {
1625 // Subtract the lowest switch case value from the value being switched on and
1626 // conditional branch to default mbb if the result is greater than the
1627 // difference between smallest and largest cases.
1628 SDValue SwitchOp = getValue(JTH.SValue);
1629 EVT VT = SwitchOp.getValueType();
1630 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1631 DAG.getConstant(JTH.First, VT));
1633 // The SDNode we just created, which holds the value being switched on minus
1634 // the smallest case value, needs to be copied to a virtual register so it
1635 // can be used as an index into the jump table in a subsequent basic block.
1636 // This value may be smaller or larger than the target's pointer type, and
1637 // therefore require extension or truncating.
1638 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1640 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1641 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1642 JumpTableReg, SwitchOp);
1643 JT.Reg = JumpTableReg;
1645 // Emit the range check for the jump table, and branch to the default block
1646 // for the switch statement if the value being switched on exceeds the largest
1647 // case in the switch.
1648 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1649 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1650 DAG.getConstant(JTH.Last-JTH.First,VT),
1653 // Set NextBlock to be the MBB immediately after the current one, if any.
1654 // This is used to avoid emitting unnecessary branches to the next block.
1655 MachineBasicBlock *NextBlock = 0;
1656 MachineFunction::iterator BBI = SwitchBB;
1658 if (++BBI != FuncInfo.MF->end())
1661 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1662 MVT::Other, CopyTo, CMP,
1663 DAG.getBasicBlock(JT.Default));
1665 if (JT.MBB != NextBlock)
1666 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1667 DAG.getBasicBlock(JT.MBB));
1669 DAG.setRoot(BrCond);
1672 /// visitBitTestHeader - This function emits necessary code to produce value
1673 /// suitable for "bit tests"
1674 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1675 MachineBasicBlock *SwitchBB) {
1676 // Subtract the minimum value
1677 SDValue SwitchOp = getValue(B.SValue);
1678 EVT VT = SwitchOp.getValueType();
1679 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1680 DAG.getConstant(B.First, VT));
1683 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1684 TLI.getSetCCResultType(Sub.getValueType()),
1685 Sub, DAG.getConstant(B.Range, VT),
1688 // Determine the type of the test operands.
1689 bool UsePtrType = false;
1690 if (!TLI.isTypeLegal(VT))
1693 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1694 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1695 // Switch table case range are encoded into series of masks.
1696 // Just use pointer type, it's guaranteed to fit.
1702 VT = TLI.getPointerTy();
1703 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1707 B.Reg = FuncInfo.CreateReg(VT);
1708 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1711 // Set NextBlock to be the MBB immediately after the current one, if any.
1712 // This is used to avoid emitting unnecessary branches to the next block.
1713 MachineBasicBlock *NextBlock = 0;
1714 MachineFunction::iterator BBI = SwitchBB;
1715 if (++BBI != FuncInfo.MF->end())
1718 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1720 addSuccessorWithWeight(SwitchBB, B.Default);
1721 addSuccessorWithWeight(SwitchBB, MBB);
1723 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1724 MVT::Other, CopyTo, RangeCmp,
1725 DAG.getBasicBlock(B.Default));
1727 if (MBB != NextBlock)
1728 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1729 DAG.getBasicBlock(MBB));
1731 DAG.setRoot(BrRange);
1734 /// visitBitTestCase - this function produces one "bit test"
1735 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1736 MachineBasicBlock* NextMBB,
1739 MachineBasicBlock *SwitchBB) {
1741 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1744 unsigned PopCount = CountPopulation_64(B.Mask);
1745 if (PopCount == 1) {
1746 // Testing for a single bit; just compare the shift count with what it
1747 // would need to be to shift a 1 bit in that position.
1748 Cmp = DAG.getSetCC(getCurDebugLoc(),
1749 TLI.getSetCCResultType(VT),
1751 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
1753 } else if (PopCount == BB.Range) {
1754 // There is only one zero bit in the range, test for it directly.
1755 Cmp = DAG.getSetCC(getCurDebugLoc(),
1756 TLI.getSetCCResultType(VT),
1758 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1761 // Make desired shift
1762 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1763 DAG.getConstant(1, VT), ShiftOp);
1765 // Emit bit tests and jumps
1766 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1767 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1768 Cmp = DAG.getSetCC(getCurDebugLoc(),
1769 TLI.getSetCCResultType(VT),
1770 AndOp, DAG.getConstant(0, VT),
1774 addSuccessorWithWeight(SwitchBB, B.TargetBB);
1775 addSuccessorWithWeight(SwitchBB, NextMBB);
1777 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1778 MVT::Other, getControlRoot(),
1779 Cmp, DAG.getBasicBlock(B.TargetBB));
1781 // Set NextBlock to be the MBB immediately after the current one, if any.
1782 // This is used to avoid emitting unnecessary branches to the next block.
1783 MachineBasicBlock *NextBlock = 0;
1784 MachineFunction::iterator BBI = SwitchBB;
1785 if (++BBI != FuncInfo.MF->end())
1788 if (NextMBB != NextBlock)
1789 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1790 DAG.getBasicBlock(NextMBB));
1795 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1796 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1798 // Retrieve successors.
1799 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1800 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1802 const Value *Callee(I.getCalledValue());
1803 if (isa<InlineAsm>(Callee))
1806 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1808 // If the value of the invoke is used outside of its defining block, make it
1809 // available as a virtual register.
1810 CopyToExportRegsIfNeeded(&I);
1812 // Update successor info
1813 addSuccessorWithWeight(InvokeMBB, Return);
1814 addSuccessorWithWeight(InvokeMBB, LandingPad);
1816 // Drop into normal successor.
1817 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1818 MVT::Other, getControlRoot(),
1819 DAG.getBasicBlock(Return)));
1822 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1825 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1826 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1829 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1830 assert(FuncInfo.MBB->isLandingPad() &&
1831 "Call to landingpad not in landing pad!");
1833 MachineBasicBlock *MBB = FuncInfo.MBB;
1834 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1835 AddLandingPadInfo(LP, MMI, MBB);
1837 SmallVector<EVT, 2> ValueVTs;
1838 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
1840 // Insert the EXCEPTIONADDR instruction.
1841 assert(FuncInfo.MBB->isLandingPad() &&
1842 "Call to eh.exception not in landing pad!");
1843 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1845 Ops[0] = DAG.getRoot();
1846 SDValue Op1 = DAG.getNode(ISD::EXCEPTIONADDR, getCurDebugLoc(), VTs, Ops, 1);
1847 SDValue Chain = Op1.getValue(1);
1849 // Insert the EHSELECTION instruction.
1850 VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1853 SDValue Op2 = DAG.getNode(ISD::EHSELECTION, getCurDebugLoc(), VTs, Ops, 2);
1854 Chain = Op2.getValue(1);
1855 Op2 = DAG.getSExtOrTrunc(Op2, getCurDebugLoc(), MVT::i32);
1859 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
1860 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1863 std::pair<SDValue, SDValue> RetPair = std::make_pair(Res, Chain);
1864 setValue(&LP, RetPair.first);
1865 DAG.setRoot(RetPair.second);
1868 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1869 /// small case ranges).
1870 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1871 CaseRecVector& WorkList,
1873 MachineBasicBlock *Default,
1874 MachineBasicBlock *SwitchBB) {
1875 Case& BackCase = *(CR.Range.second-1);
1877 // Size is the number of Cases represented by this range.
1878 size_t Size = CR.Range.second - CR.Range.first;
1882 // Get the MachineFunction which holds the current MBB. This is used when
1883 // inserting any additional MBBs necessary to represent the switch.
1884 MachineFunction *CurMF = FuncInfo.MF;
1886 // Figure out which block is immediately after the current one.
1887 MachineBasicBlock *NextBlock = 0;
1888 MachineFunction::iterator BBI = CR.CaseBB;
1890 if (++BBI != FuncInfo.MF->end())
1893 // If any two of the cases has the same destination, and if one value
1894 // is the same as the other, but has one bit unset that the other has set,
1895 // use bit manipulation to do two compares at once. For example:
1896 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1897 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1898 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1899 if (Size == 2 && CR.CaseBB == SwitchBB) {
1900 Case &Small = *CR.Range.first;
1901 Case &Big = *(CR.Range.second-1);
1903 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1904 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1905 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1907 // Check that there is only one bit different.
1908 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1909 (SmallValue | BigValue) == BigValue) {
1910 // Isolate the common bit.
1911 APInt CommonBit = BigValue & ~SmallValue;
1912 assert((SmallValue | CommonBit) == BigValue &&
1913 CommonBit.countPopulation() == 1 && "Not a common bit?");
1915 SDValue CondLHS = getValue(SV);
1916 EVT VT = CondLHS.getValueType();
1917 DebugLoc DL = getCurDebugLoc();
1919 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1920 DAG.getConstant(CommonBit, VT));
1921 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1922 Or, DAG.getConstant(BigValue, VT),
1925 // Update successor info.
1926 addSuccessorWithWeight(SwitchBB, Small.BB);
1927 addSuccessorWithWeight(SwitchBB, Default);
1929 // Insert the true branch.
1930 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1931 getControlRoot(), Cond,
1932 DAG.getBasicBlock(Small.BB));
1934 // Insert the false branch.
1935 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
1936 DAG.getBasicBlock(Default));
1938 DAG.setRoot(BrCond);
1944 // Rearrange the case blocks so that the last one falls through if possible.
1945 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1946 // The last case block won't fall through into 'NextBlock' if we emit the
1947 // branches in this order. See if rearranging a case value would help.
1948 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1949 if (I->BB == NextBlock) {
1950 std::swap(*I, BackCase);
1956 // Create a CaseBlock record representing a conditional branch to
1957 // the Case's target mbb if the value being switched on SV is equal
1959 MachineBasicBlock *CurBlock = CR.CaseBB;
1960 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1961 MachineBasicBlock *FallThrough;
1963 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1964 CurMF->insert(BBI, FallThrough);
1966 // Put SV in a virtual register to make it available from the new blocks.
1967 ExportFromCurrentBlock(SV);
1969 // If the last case doesn't match, go to the default block.
1970 FallThrough = Default;
1973 const Value *RHS, *LHS, *MHS;
1975 if (I->High == I->Low) {
1976 // This is just small small case range :) containing exactly 1 case
1978 LHS = SV; RHS = I->High; MHS = NULL;
1981 LHS = I->Low; MHS = SV; RHS = I->High;
1984 uint32_t ExtraWeight = I->ExtraWeight;
1985 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
1987 /* trueweight */ ExtraWeight / 2, /* falseweight */ ExtraWeight / 2);
1989 // If emitting the first comparison, just call visitSwitchCase to emit the
1990 // code into the current block. Otherwise, push the CaseBlock onto the
1991 // vector to be later processed by SDISel, and insert the node's MBB
1992 // before the next MBB.
1993 if (CurBlock == SwitchBB)
1994 visitSwitchCase(CB, SwitchBB);
1996 SwitchCases.push_back(CB);
1998 CurBlock = FallThrough;
2004 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2005 return !DisableJumpTables &&
2006 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2007 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
2010 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2011 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2012 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2013 return (LastExt - FirstExt + 1ULL);
2016 /// handleJTSwitchCase - Emit jumptable for current switch case range
2017 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2018 CaseRecVector &WorkList,
2020 MachineBasicBlock *Default,
2021 MachineBasicBlock *SwitchBB) {
2022 Case& FrontCase = *CR.Range.first;
2023 Case& BackCase = *(CR.Range.second-1);
2025 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2026 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2028 APInt TSize(First.getBitWidth(), 0);
2029 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2032 if (!areJTsAllowed(TLI) || TSize.ult(4))
2035 APInt Range = ComputeRange(First, Last);
2036 // The density is TSize / Range. Require at least 40%.
2037 // It should not be possible for IntTSize to saturate for sane code, but make
2038 // sure we handle Range saturation correctly.
2039 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2040 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2041 if (IntTSize * 10 < IntRange * 4)
2044 DEBUG(dbgs() << "Lowering jump table\n"
2045 << "First entry: " << First << ". Last entry: " << Last << '\n'
2046 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2048 // Get the MachineFunction which holds the current MBB. This is used when
2049 // inserting any additional MBBs necessary to represent the switch.
2050 MachineFunction *CurMF = FuncInfo.MF;
2052 // Figure out which block is immediately after the current one.
2053 MachineFunction::iterator BBI = CR.CaseBB;
2056 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2058 // Create a new basic block to hold the code for loading the address
2059 // of the jump table, and jumping to it. Update successor information;
2060 // we will either branch to the default case for the switch, or the jump
2062 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2063 CurMF->insert(BBI, JumpTableBB);
2065 addSuccessorWithWeight(CR.CaseBB, Default);
2066 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2068 // Build a vector of destination BBs, corresponding to each target
2069 // of the jump table. If the value of the jump table slot corresponds to
2070 // a case statement, push the case's BB onto the vector, otherwise, push
2072 std::vector<MachineBasicBlock*> DestBBs;
2074 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2075 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2076 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2078 if (Low.sle(TEI) && TEI.sle(High)) {
2079 DestBBs.push_back(I->BB);
2083 DestBBs.push_back(Default);
2087 // Update successor info. Add one edge to each unique successor.
2088 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2089 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2090 E = DestBBs.end(); I != E; ++I) {
2091 if (!SuccsHandled[(*I)->getNumber()]) {
2092 SuccsHandled[(*I)->getNumber()] = true;
2093 addSuccessorWithWeight(JumpTableBB, *I);
2097 // Create a jump table index for this jump table.
2098 unsigned JTEncoding = TLI.getJumpTableEncoding();
2099 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2100 ->createJumpTableIndex(DestBBs);
2102 // Set the jump table information so that we can codegen it as a second
2103 // MachineBasicBlock
2104 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2105 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2106 if (CR.CaseBB == SwitchBB)
2107 visitJumpTableHeader(JT, JTH, SwitchBB);
2109 JTCases.push_back(JumpTableBlock(JTH, JT));
2113 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2115 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2116 CaseRecVector& WorkList,
2118 MachineBasicBlock *Default,
2119 MachineBasicBlock *SwitchBB) {
2120 // Get the MachineFunction which holds the current MBB. This is used when
2121 // inserting any additional MBBs necessary to represent the switch.
2122 MachineFunction *CurMF = FuncInfo.MF;
2124 // Figure out which block is immediately after the current one.
2125 MachineFunction::iterator BBI = CR.CaseBB;
2128 Case& FrontCase = *CR.Range.first;
2129 Case& BackCase = *(CR.Range.second-1);
2130 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2132 // Size is the number of Cases represented by this range.
2133 unsigned Size = CR.Range.second - CR.Range.first;
2135 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2136 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2138 CaseItr Pivot = CR.Range.first + Size/2;
2140 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2141 // (heuristically) allow us to emit JumpTable's later.
2142 APInt TSize(First.getBitWidth(), 0);
2143 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2147 APInt LSize = FrontCase.size();
2148 APInt RSize = TSize-LSize;
2149 DEBUG(dbgs() << "Selecting best pivot: \n"
2150 << "First: " << First << ", Last: " << Last <<'\n'
2151 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2152 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2154 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2155 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2156 APInt Range = ComputeRange(LEnd, RBegin);
2157 assert((Range - 2ULL).isNonNegative() &&
2158 "Invalid case distance");
2159 // Use volatile double here to avoid excess precision issues on some hosts,
2160 // e.g. that use 80-bit X87 registers.
2161 volatile double LDensity =
2162 (double)LSize.roundToDouble() /
2163 (LEnd - First + 1ULL).roundToDouble();
2164 volatile double RDensity =
2165 (double)RSize.roundToDouble() /
2166 (Last - RBegin + 1ULL).roundToDouble();
2167 double Metric = Range.logBase2()*(LDensity+RDensity);
2168 // Should always split in some non-trivial place
2169 DEBUG(dbgs() <<"=>Step\n"
2170 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2171 << "LDensity: " << LDensity
2172 << ", RDensity: " << RDensity << '\n'
2173 << "Metric: " << Metric << '\n');
2174 if (FMetric < Metric) {
2177 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2183 if (areJTsAllowed(TLI)) {
2184 // If our case is dense we *really* should handle it earlier!
2185 assert((FMetric > 0) && "Should handle dense range earlier!");
2187 Pivot = CR.Range.first + Size/2;
2190 CaseRange LHSR(CR.Range.first, Pivot);
2191 CaseRange RHSR(Pivot, CR.Range.second);
2192 Constant *C = Pivot->Low;
2193 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2195 // We know that we branch to the LHS if the Value being switched on is
2196 // less than the Pivot value, C. We use this to optimize our binary
2197 // tree a bit, by recognizing that if SV is greater than or equal to the
2198 // LHS's Case Value, and that Case Value is exactly one less than the
2199 // Pivot's Value, then we can branch directly to the LHS's Target,
2200 // rather than creating a leaf node for it.
2201 if ((LHSR.second - LHSR.first) == 1 &&
2202 LHSR.first->High == CR.GE &&
2203 cast<ConstantInt>(C)->getValue() ==
2204 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2205 TrueBB = LHSR.first->BB;
2207 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2208 CurMF->insert(BBI, TrueBB);
2209 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2211 // Put SV in a virtual register to make it available from the new blocks.
2212 ExportFromCurrentBlock(SV);
2215 // Similar to the optimization above, if the Value being switched on is
2216 // known to be less than the Constant CR.LT, and the current Case Value
2217 // is CR.LT - 1, then we can branch directly to the target block for
2218 // the current Case Value, rather than emitting a RHS leaf node for it.
2219 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2220 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2221 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2222 FalseBB = RHSR.first->BB;
2224 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2225 CurMF->insert(BBI, FalseBB);
2226 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2228 // Put SV in a virtual register to make it available from the new blocks.
2229 ExportFromCurrentBlock(SV);
2232 // Create a CaseBlock record representing a conditional branch to
2233 // the LHS node if the value being switched on SV is less than C.
2234 // Otherwise, branch to LHS.
2235 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2237 if (CR.CaseBB == SwitchBB)
2238 visitSwitchCase(CB, SwitchBB);
2240 SwitchCases.push_back(CB);
2245 /// handleBitTestsSwitchCase - if current case range has few destination and
2246 /// range span less, than machine word bitwidth, encode case range into series
2247 /// of masks and emit bit tests with these masks.
2248 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2249 CaseRecVector& WorkList,
2251 MachineBasicBlock* Default,
2252 MachineBasicBlock *SwitchBB){
2253 EVT PTy = TLI.getPointerTy();
2254 unsigned IntPtrBits = PTy.getSizeInBits();
2256 Case& FrontCase = *CR.Range.first;
2257 Case& BackCase = *(CR.Range.second-1);
2259 // Get the MachineFunction which holds the current MBB. This is used when
2260 // inserting any additional MBBs necessary to represent the switch.
2261 MachineFunction *CurMF = FuncInfo.MF;
2263 // If target does not have legal shift left, do not emit bit tests at all.
2264 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2268 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2270 // Single case counts one, case range - two.
2271 numCmps += (I->Low == I->High ? 1 : 2);
2274 // Count unique destinations
2275 SmallSet<MachineBasicBlock*, 4> Dests;
2276 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2277 Dests.insert(I->BB);
2278 if (Dests.size() > 3)
2279 // Don't bother the code below, if there are too much unique destinations
2282 DEBUG(dbgs() << "Total number of unique destinations: "
2283 << Dests.size() << '\n'
2284 << "Total number of comparisons: " << numCmps << '\n');
2286 // Compute span of values.
2287 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2288 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2289 APInt cmpRange = maxValue - minValue;
2291 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2292 << "Low bound: " << minValue << '\n'
2293 << "High bound: " << maxValue << '\n');
2295 if (cmpRange.uge(IntPtrBits) ||
2296 (!(Dests.size() == 1 && numCmps >= 3) &&
2297 !(Dests.size() == 2 && numCmps >= 5) &&
2298 !(Dests.size() >= 3 && numCmps >= 6)))
2301 DEBUG(dbgs() << "Emitting bit tests\n");
2302 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2304 // Optimize the case where all the case values fit in a
2305 // word without having to subtract minValue. In this case,
2306 // we can optimize away the subtraction.
2307 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2308 cmpRange = maxValue;
2310 lowBound = minValue;
2313 CaseBitsVector CasesBits;
2314 unsigned i, count = 0;
2316 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2317 MachineBasicBlock* Dest = I->BB;
2318 for (i = 0; i < count; ++i)
2319 if (Dest == CasesBits[i].BB)
2323 assert((count < 3) && "Too much destinations to test!");
2324 CasesBits.push_back(CaseBits(0, Dest, 0));
2328 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2329 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2331 uint64_t lo = (lowValue - lowBound).getZExtValue();
2332 uint64_t hi = (highValue - lowBound).getZExtValue();
2334 for (uint64_t j = lo; j <= hi; j++) {
2335 CasesBits[i].Mask |= 1ULL << j;
2336 CasesBits[i].Bits++;
2340 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2344 // Figure out which block is immediately after the current one.
2345 MachineFunction::iterator BBI = CR.CaseBB;
2348 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2350 DEBUG(dbgs() << "Cases:\n");
2351 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2352 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2353 << ", Bits: " << CasesBits[i].Bits
2354 << ", BB: " << CasesBits[i].BB << '\n');
2356 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2357 CurMF->insert(BBI, CaseBB);
2358 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2362 // Put SV in a virtual register to make it available from the new blocks.
2363 ExportFromCurrentBlock(SV);
2366 BitTestBlock BTB(lowBound, cmpRange, SV,
2367 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2368 CR.CaseBB, Default, BTC);
2370 if (CR.CaseBB == SwitchBB)
2371 visitBitTestHeader(BTB, SwitchBB);
2373 BitTestCases.push_back(BTB);
2378 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2379 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2380 const SwitchInst& SI) {
2383 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2384 // Start with "simple" cases
2385 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2386 BasicBlock *SuccBB = SI.getSuccessor(i);
2387 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2389 uint32_t ExtraWeight = BPI ? BPI->getEdgeWeight(SI.getParent(), SuccBB) : 0;
2391 Cases.push_back(Case(SI.getSuccessorValue(i),
2392 SI.getSuccessorValue(i),
2393 SMBB, ExtraWeight));
2395 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2397 // Merge case into clusters
2398 if (Cases.size() >= 2)
2399 // Must recompute end() each iteration because it may be
2400 // invalidated by erase if we hold on to it
2401 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2402 J != Cases.end(); ) {
2403 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2404 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2405 MachineBasicBlock* nextBB = J->BB;
2406 MachineBasicBlock* currentBB = I->BB;
2408 // If the two neighboring cases go to the same destination, merge them
2409 // into a single case.
2410 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2414 if (BranchProbabilityInfo *BPI = FuncInfo.BPI) {
2415 uint32_t CurWeight = currentBB->getBasicBlock() ?
2416 BPI->getEdgeWeight(SI.getParent(), currentBB->getBasicBlock()) : 16;
2417 uint32_t NextWeight = nextBB->getBasicBlock() ?
2418 BPI->getEdgeWeight(SI.getParent(), nextBB->getBasicBlock()) : 16;
2420 BPI->setEdgeWeight(SI.getParent(), currentBB->getBasicBlock(),
2421 CurWeight + NextWeight);
2428 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2429 if (I->Low != I->High)
2430 // A range counts double, since it requires two compares.
2437 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2438 MachineBasicBlock *Last) {
2440 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2441 if (JTCases[i].first.HeaderBB == First)
2442 JTCases[i].first.HeaderBB = Last;
2444 // Update BitTestCases.
2445 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2446 if (BitTestCases[i].Parent == First)
2447 BitTestCases[i].Parent = Last;
2450 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2451 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2453 // Figure out which block is immediately after the current one.
2454 MachineBasicBlock *NextBlock = 0;
2455 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2457 // If there is only the default destination, branch to it if it is not the
2458 // next basic block. Otherwise, just fall through.
2459 if (SI.getNumCases() == 1) {
2460 // Update machine-CFG edges.
2462 // If this is not a fall-through branch, emit the branch.
2463 SwitchMBB->addSuccessor(Default);
2464 if (Default != NextBlock)
2465 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2466 MVT::Other, getControlRoot(),
2467 DAG.getBasicBlock(Default)));
2472 // If there are any non-default case statements, create a vector of Cases
2473 // representing each one, and sort the vector so that we can efficiently
2474 // create a binary search tree from them.
2476 size_t numCmps = Clusterify(Cases, SI);
2477 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2478 << ". Total compares: " << numCmps << '\n');
2481 // Get the Value to be switched on and default basic blocks, which will be
2482 // inserted into CaseBlock records, representing basic blocks in the binary
2484 const Value *SV = SI.getCondition();
2486 // Push the initial CaseRec onto the worklist
2487 CaseRecVector WorkList;
2488 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2489 CaseRange(Cases.begin(),Cases.end())));
2491 while (!WorkList.empty()) {
2492 // Grab a record representing a case range to process off the worklist
2493 CaseRec CR = WorkList.back();
2494 WorkList.pop_back();
2496 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2499 // If the range has few cases (two or less) emit a series of specific
2501 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2504 // If the switch has more than 5 blocks, and at least 40% dense, and the
2505 // target supports indirect branches, then emit a jump table rather than
2506 // lowering the switch to a binary tree of conditional branches.
2507 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2510 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2511 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2512 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2516 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2517 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2519 // Update machine-CFG edges with unique successors.
2520 SmallVector<BasicBlock*, 32> succs;
2521 succs.reserve(I.getNumSuccessors());
2522 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2523 succs.push_back(I.getSuccessor(i));
2524 array_pod_sort(succs.begin(), succs.end());
2525 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2526 for (unsigned i = 0, e = succs.size(); i != e; ++i) {
2527 MachineBasicBlock *Succ = FuncInfo.MBBMap[succs[i]];
2528 addSuccessorWithWeight(IndirectBrMBB, Succ);
2531 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2532 MVT::Other, getControlRoot(),
2533 getValue(I.getAddress())));
2536 void SelectionDAGBuilder::visitFSub(const User &I) {
2537 // -0.0 - X --> fneg
2538 Type *Ty = I.getType();
2539 if (isa<Constant>(I.getOperand(0)) &&
2540 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2541 SDValue Op2 = getValue(I.getOperand(1));
2542 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2543 Op2.getValueType(), Op2));
2547 visitBinary(I, ISD::FSUB);
2550 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2551 SDValue Op1 = getValue(I.getOperand(0));
2552 SDValue Op2 = getValue(I.getOperand(1));
2553 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2554 Op1.getValueType(), Op1, Op2));
2557 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2558 SDValue Op1 = getValue(I.getOperand(0));
2559 SDValue Op2 = getValue(I.getOperand(1));
2561 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2563 // Coerce the shift amount to the right type if we can.
2564 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2565 unsigned ShiftSize = ShiftTy.getSizeInBits();
2566 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2567 DebugLoc DL = getCurDebugLoc();
2569 // If the operand is smaller than the shift count type, promote it.
2570 if (ShiftSize > Op2Size)
2571 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2573 // If the operand is larger than the shift count type but the shift
2574 // count type has enough bits to represent any shift value, truncate
2575 // it now. This is a common case and it exposes the truncate to
2576 // optimization early.
2577 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2578 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2579 // Otherwise we'll need to temporarily settle for some other convenient
2580 // type. Type legalization will make adjustments once the shiftee is split.
2582 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2585 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2586 Op1.getValueType(), Op1, Op2));
2589 void SelectionDAGBuilder::visitSDiv(const User &I) {
2590 SDValue Op1 = getValue(I.getOperand(0));
2591 SDValue Op2 = getValue(I.getOperand(1));
2593 // Turn exact SDivs into multiplications.
2594 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2596 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2597 !isa<ConstantSDNode>(Op1) &&
2598 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2599 setValue(&I, TLI.BuildExactSDIV(Op1, Op2, getCurDebugLoc(), DAG));
2601 setValue(&I, DAG.getNode(ISD::SDIV, getCurDebugLoc(), Op1.getValueType(),
2605 void SelectionDAGBuilder::visitICmp(const User &I) {
2606 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2607 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2608 predicate = IC->getPredicate();
2609 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2610 predicate = ICmpInst::Predicate(IC->getPredicate());
2611 SDValue Op1 = getValue(I.getOperand(0));
2612 SDValue Op2 = getValue(I.getOperand(1));
2613 ISD::CondCode Opcode = getICmpCondCode(predicate);
2615 EVT DestVT = TLI.getValueType(I.getType());
2616 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2619 void SelectionDAGBuilder::visitFCmp(const User &I) {
2620 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2621 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2622 predicate = FC->getPredicate();
2623 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2624 predicate = FCmpInst::Predicate(FC->getPredicate());
2625 SDValue Op1 = getValue(I.getOperand(0));
2626 SDValue Op2 = getValue(I.getOperand(1));
2627 ISD::CondCode Condition = getFCmpCondCode(predicate);
2628 EVT DestVT = TLI.getValueType(I.getType());
2629 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2632 void SelectionDAGBuilder::visitSelect(const User &I) {
2633 SmallVector<EVT, 4> ValueVTs;
2634 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2635 unsigned NumValues = ValueVTs.size();
2636 if (NumValues == 0) return;
2638 SmallVector<SDValue, 4> Values(NumValues);
2639 SDValue Cond = getValue(I.getOperand(0));
2640 SDValue TrueVal = getValue(I.getOperand(1));
2641 SDValue FalseVal = getValue(I.getOperand(2));
2642 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2643 ISD::VSELECT : ISD::SELECT;
2645 for (unsigned i = 0; i != NumValues; ++i)
2646 Values[i] = DAG.getNode(OpCode, getCurDebugLoc(),
2647 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2649 SDValue(TrueVal.getNode(),
2650 TrueVal.getResNo() + i),
2651 SDValue(FalseVal.getNode(),
2652 FalseVal.getResNo() + i));
2654 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2655 DAG.getVTList(&ValueVTs[0], NumValues),
2656 &Values[0], NumValues));
2659 void SelectionDAGBuilder::visitTrunc(const User &I) {
2660 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2661 SDValue N = getValue(I.getOperand(0));
2662 EVT DestVT = TLI.getValueType(I.getType());
2663 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2666 void SelectionDAGBuilder::visitZExt(const User &I) {
2667 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2668 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2669 SDValue N = getValue(I.getOperand(0));
2670 EVT DestVT = TLI.getValueType(I.getType());
2671 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2674 void SelectionDAGBuilder::visitSExt(const User &I) {
2675 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2676 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2677 SDValue N = getValue(I.getOperand(0));
2678 EVT DestVT = TLI.getValueType(I.getType());
2679 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2682 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2683 // FPTrunc is never a no-op cast, no need to check
2684 SDValue N = getValue(I.getOperand(0));
2685 EVT DestVT = TLI.getValueType(I.getType());
2686 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2687 DestVT, N, DAG.getIntPtrConstant(0)));
2690 void SelectionDAGBuilder::visitFPExt(const User &I){
2691 // FPExt is never a no-op cast, no need to check
2692 SDValue N = getValue(I.getOperand(0));
2693 EVT DestVT = TLI.getValueType(I.getType());
2694 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2697 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2698 // FPToUI is never a no-op cast, no need to check
2699 SDValue N = getValue(I.getOperand(0));
2700 EVT DestVT = TLI.getValueType(I.getType());
2701 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2704 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2705 // FPToSI is never a no-op cast, no need to check
2706 SDValue N = getValue(I.getOperand(0));
2707 EVT DestVT = TLI.getValueType(I.getType());
2708 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2711 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2712 // UIToFP is never a no-op cast, no need to check
2713 SDValue N = getValue(I.getOperand(0));
2714 EVT DestVT = TLI.getValueType(I.getType());
2715 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2718 void SelectionDAGBuilder::visitSIToFP(const User &I){
2719 // SIToFP is never a no-op cast, no need to check
2720 SDValue N = getValue(I.getOperand(0));
2721 EVT DestVT = TLI.getValueType(I.getType());
2722 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2725 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2726 // What to do depends on the size of the integer and the size of the pointer.
2727 // We can either truncate, zero extend, or no-op, accordingly.
2728 SDValue N = getValue(I.getOperand(0));
2729 EVT DestVT = TLI.getValueType(I.getType());
2730 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2733 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2734 // What to do depends on the size of the integer and the size of the pointer.
2735 // We can either truncate, zero extend, or no-op, accordingly.
2736 SDValue N = getValue(I.getOperand(0));
2737 EVT DestVT = TLI.getValueType(I.getType());
2738 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2741 void SelectionDAGBuilder::visitBitCast(const User &I) {
2742 SDValue N = getValue(I.getOperand(0));
2743 EVT DestVT = TLI.getValueType(I.getType());
2745 // BitCast assures us that source and destination are the same size so this is
2746 // either a BITCAST or a no-op.
2747 if (DestVT != N.getValueType())
2748 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
2749 DestVT, N)); // convert types.
2751 setValue(&I, N); // noop cast.
2754 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2755 SDValue InVec = getValue(I.getOperand(0));
2756 SDValue InVal = getValue(I.getOperand(1));
2757 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2759 getValue(I.getOperand(2)));
2760 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2761 TLI.getValueType(I.getType()),
2762 InVec, InVal, InIdx));
2765 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2766 SDValue InVec = getValue(I.getOperand(0));
2767 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2769 getValue(I.getOperand(1)));
2770 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2771 TLI.getValueType(I.getType()), InVec, InIdx));
2774 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2775 // from SIndx and increasing to the element length (undefs are allowed).
2776 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2777 unsigned MaskNumElts = Mask.size();
2778 for (unsigned i = 0; i != MaskNumElts; ++i)
2779 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2784 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2785 SmallVector<int, 8> Mask;
2786 SDValue Src1 = getValue(I.getOperand(0));
2787 SDValue Src2 = getValue(I.getOperand(1));
2789 // Convert the ConstantVector mask operand into an array of ints, with -1
2790 // representing undef values.
2791 SmallVector<Constant*, 8> MaskElts;
2792 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2793 unsigned MaskNumElts = MaskElts.size();
2794 for (unsigned i = 0; i != MaskNumElts; ++i) {
2795 if (isa<UndefValue>(MaskElts[i]))
2798 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2801 EVT VT = TLI.getValueType(I.getType());
2802 EVT SrcVT = Src1.getValueType();
2803 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2805 if (SrcNumElts == MaskNumElts) {
2806 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2811 // Normalize the shuffle vector since mask and vector length don't match.
2812 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2813 // Mask is longer than the source vectors and is a multiple of the source
2814 // vectors. We can use concatenate vector to make the mask and vectors
2816 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2817 // The shuffle is concatenating two vectors together.
2818 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2823 // Pad both vectors with undefs to make them the same length as the mask.
2824 unsigned NumConcat = MaskNumElts / SrcNumElts;
2825 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2826 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2827 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2829 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2830 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2834 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2835 getCurDebugLoc(), VT,
2836 &MOps1[0], NumConcat);
2837 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2838 getCurDebugLoc(), VT,
2839 &MOps2[0], NumConcat);
2841 // Readjust mask for new input vector length.
2842 SmallVector<int, 8> MappedOps;
2843 for (unsigned i = 0; i != MaskNumElts; ++i) {
2845 if (Idx < (int)SrcNumElts)
2846 MappedOps.push_back(Idx);
2848 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2851 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2856 if (SrcNumElts > MaskNumElts) {
2857 // Analyze the access pattern of the vector to see if we can extract
2858 // two subvectors and do the shuffle. The analysis is done by calculating
2859 // the range of elements the mask access on both vectors.
2860 int MinRange[2] = { static_cast<int>(SrcNumElts+1),
2861 static_cast<int>(SrcNumElts+1)};
2862 int MaxRange[2] = {-1, -1};
2864 for (unsigned i = 0; i != MaskNumElts; ++i) {
2870 if (Idx >= (int)SrcNumElts) {
2874 if (Idx > MaxRange[Input])
2875 MaxRange[Input] = Idx;
2876 if (Idx < MinRange[Input])
2877 MinRange[Input] = Idx;
2880 // Check if the access is smaller than the vector size and can we find
2881 // a reasonable extract index.
2882 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2884 int StartIdx[2]; // StartIdx to extract from
2885 for (int Input=0; Input < 2; ++Input) {
2886 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2887 RangeUse[Input] = 0; // Unused
2888 StartIdx[Input] = 0;
2889 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2890 // Fits within range but we should see if we can find a good
2891 // start index that is a multiple of the mask length.
2892 if (MaxRange[Input] < (int)MaskNumElts) {
2893 RangeUse[Input] = 1; // Extract from beginning of the vector
2894 StartIdx[Input] = 0;
2896 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2897 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2898 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2899 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2904 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2905 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2908 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2909 // Extract appropriate subvector and generate a vector shuffle
2910 for (int Input=0; Input < 2; ++Input) {
2911 SDValue &Src = Input == 0 ? Src1 : Src2;
2912 if (RangeUse[Input] == 0)
2913 Src = DAG.getUNDEF(VT);
2915 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2916 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2919 // Calculate new mask.
2920 SmallVector<int, 8> MappedOps;
2921 for (unsigned i = 0; i != MaskNumElts; ++i) {
2924 MappedOps.push_back(Idx);
2925 else if (Idx < (int)SrcNumElts)
2926 MappedOps.push_back(Idx - StartIdx[0]);
2928 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2931 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2937 // We can't use either concat vectors or extract subvectors so fall back to
2938 // replacing the shuffle with extract and build vector.
2939 // to insert and build vector.
2940 EVT EltVT = VT.getVectorElementType();
2941 EVT PtrVT = TLI.getPointerTy();
2942 SmallVector<SDValue,8> Ops;
2943 for (unsigned i = 0; i != MaskNumElts; ++i) {
2945 Ops.push_back(DAG.getUNDEF(EltVT));
2950 if (Idx < (int)SrcNumElts)
2951 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2952 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2954 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2956 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2962 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2963 VT, &Ops[0], Ops.size()));
2966 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2967 const Value *Op0 = I.getOperand(0);
2968 const Value *Op1 = I.getOperand(1);
2969 Type *AggTy = I.getType();
2970 Type *ValTy = Op1->getType();
2971 bool IntoUndef = isa<UndefValue>(Op0);
2972 bool FromUndef = isa<UndefValue>(Op1);
2974 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2976 SmallVector<EVT, 4> AggValueVTs;
2977 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2978 SmallVector<EVT, 4> ValValueVTs;
2979 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2981 unsigned NumAggValues = AggValueVTs.size();
2982 unsigned NumValValues = ValValueVTs.size();
2983 SmallVector<SDValue, 4> Values(NumAggValues);
2985 SDValue Agg = getValue(Op0);
2987 // Copy the beginning value(s) from the original aggregate.
2988 for (; i != LinearIndex; ++i)
2989 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2990 SDValue(Agg.getNode(), Agg.getResNo() + i);
2991 // Copy values from the inserted value(s).
2993 SDValue Val = getValue(Op1);
2994 for (; i != LinearIndex + NumValValues; ++i)
2995 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2996 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2998 // Copy remaining value(s) from the original aggregate.
2999 for (; i != NumAggValues; ++i)
3000 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3001 SDValue(Agg.getNode(), Agg.getResNo() + i);
3003 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3004 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3005 &Values[0], NumAggValues));
3008 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3009 const Value *Op0 = I.getOperand(0);
3010 Type *AggTy = Op0->getType();
3011 Type *ValTy = I.getType();
3012 bool OutOfUndef = isa<UndefValue>(Op0);
3014 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3016 SmallVector<EVT, 4> ValValueVTs;
3017 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3019 unsigned NumValValues = ValValueVTs.size();
3021 // Ignore a extractvalue that produces an empty object
3022 if (!NumValValues) {
3023 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3027 SmallVector<SDValue, 4> Values(NumValValues);
3029 SDValue Agg = getValue(Op0);
3030 // Copy out the selected value(s).
3031 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3032 Values[i - LinearIndex] =
3034 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3035 SDValue(Agg.getNode(), Agg.getResNo() + i);
3037 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3038 DAG.getVTList(&ValValueVTs[0], NumValValues),
3039 &Values[0], NumValValues));
3042 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3043 SDValue N = getValue(I.getOperand(0));
3044 Type *Ty = I.getOperand(0)->getType();
3046 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3048 const Value *Idx = *OI;
3049 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3050 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3053 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
3054 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
3055 DAG.getIntPtrConstant(Offset));
3058 Ty = StTy->getElementType(Field);
3060 Ty = cast<SequentialType>(Ty)->getElementType();
3062 // If this is a constant subscript, handle it quickly.
3063 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3064 if (CI->isZero()) continue;
3066 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3068 EVT PTy = TLI.getPointerTy();
3069 unsigned PtrBits = PTy.getSizeInBits();
3071 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
3073 DAG.getConstant(Offs, MVT::i64));
3075 OffsVal = DAG.getIntPtrConstant(Offs);
3077 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
3082 // N = N + Idx * ElementSize;
3083 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
3084 TD->getTypeAllocSize(Ty));
3085 SDValue IdxN = getValue(Idx);
3087 // If the index is smaller or larger than intptr_t, truncate or extend
3089 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
3091 // If this is a multiply by a power of two, turn it into a shl
3092 // immediately. This is a very common case.
3093 if (ElementSize != 1) {
3094 if (ElementSize.isPowerOf2()) {
3095 unsigned Amt = ElementSize.logBase2();
3096 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
3097 N.getValueType(), IdxN,
3098 DAG.getConstant(Amt, TLI.getPointerTy()));
3100 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
3101 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
3102 N.getValueType(), IdxN, Scale);
3106 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3107 N.getValueType(), N, IdxN);
3114 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3115 // If this is a fixed sized alloca in the entry block of the function,
3116 // allocate it statically on the stack.
3117 if (FuncInfo.StaticAllocaMap.count(&I))
3118 return; // getValue will auto-populate this.
3120 Type *Ty = I.getAllocatedType();
3121 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
3123 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
3126 SDValue AllocSize = getValue(I.getArraySize());
3128 EVT IntPtr = TLI.getPointerTy();
3129 if (AllocSize.getValueType() != IntPtr)
3130 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
3132 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
3134 DAG.getConstant(TySize, IntPtr));
3136 // Handle alignment. If the requested alignment is less than or equal to
3137 // the stack alignment, ignore it. If the size is greater than or equal to
3138 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3139 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3140 if (Align <= StackAlign)
3143 // Round the size of the allocation up to the stack alignment size
3144 // by add SA-1 to the size.
3145 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3146 AllocSize.getValueType(), AllocSize,
3147 DAG.getIntPtrConstant(StackAlign-1));
3149 // Mask out the low bits for alignment purposes.
3150 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
3151 AllocSize.getValueType(), AllocSize,
3152 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3154 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3155 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3156 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
3159 DAG.setRoot(DSA.getValue(1));
3161 // Inform the Frame Information that we have just allocated a variable-sized
3163 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3166 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3168 return visitAtomicLoad(I);
3170 const Value *SV = I.getOperand(0);
3171 SDValue Ptr = getValue(SV);
3173 Type *Ty = I.getType();
3175 bool isVolatile = I.isVolatile();
3176 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3177 bool isInvariant = I.getMetadata("invariant.load") != 0;
3178 unsigned Alignment = I.getAlignment();
3179 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3181 SmallVector<EVT, 4> ValueVTs;
3182 SmallVector<uint64_t, 4> Offsets;
3183 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3184 unsigned NumValues = ValueVTs.size();
3189 bool ConstantMemory = false;
3190 if (I.isVolatile() || NumValues > MaxParallelChains)
3191 // Serialize volatile loads with other side effects.
3193 else if (AA->pointsToConstantMemory(
3194 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3195 // Do not serialize (non-volatile) loads of constant memory with anything.
3196 Root = DAG.getEntryNode();
3197 ConstantMemory = true;
3199 // Do not serialize non-volatile loads against each other.
3200 Root = DAG.getRoot();
3203 SmallVector<SDValue, 4> Values(NumValues);
3204 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3206 EVT PtrVT = Ptr.getValueType();
3207 unsigned ChainI = 0;
3208 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3209 // Serializing loads here may result in excessive register pressure, and
3210 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3211 // could recover a bit by hoisting nodes upward in the chain by recognizing
3212 // they are side-effect free or do not alias. The optimizer should really
3213 // avoid this case by converting large object/array copies to llvm.memcpy
3214 // (MaxParallelChains should always remain as failsafe).
3215 if (ChainI == MaxParallelChains) {
3216 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3217 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3218 MVT::Other, &Chains[0], ChainI);
3222 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3224 DAG.getConstant(Offsets[i], PtrVT));
3225 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3226 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3227 isNonTemporal, isInvariant, Alignment, TBAAInfo);
3230 Chains[ChainI] = L.getValue(1);
3233 if (!ConstantMemory) {
3234 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3235 MVT::Other, &Chains[0], ChainI);
3239 PendingLoads.push_back(Chain);
3242 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3243 DAG.getVTList(&ValueVTs[0], NumValues),
3244 &Values[0], NumValues));
3247 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3249 return visitAtomicStore(I);
3251 const Value *SrcV = I.getOperand(0);
3252 const Value *PtrV = I.getOperand(1);
3254 SmallVector<EVT, 4> ValueVTs;
3255 SmallVector<uint64_t, 4> Offsets;
3256 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3257 unsigned NumValues = ValueVTs.size();
3261 // Get the lowered operands. Note that we do this after
3262 // checking if NumResults is zero, because with zero results
3263 // the operands won't have values in the map.
3264 SDValue Src = getValue(SrcV);
3265 SDValue Ptr = getValue(PtrV);
3267 SDValue Root = getRoot();
3268 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3270 EVT PtrVT = Ptr.getValueType();
3271 bool isVolatile = I.isVolatile();
3272 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3273 unsigned Alignment = I.getAlignment();
3274 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3276 unsigned ChainI = 0;
3277 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3278 // See visitLoad comments.
3279 if (ChainI == MaxParallelChains) {
3280 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3281 MVT::Other, &Chains[0], ChainI);
3285 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3286 DAG.getConstant(Offsets[i], PtrVT));
3287 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3288 SDValue(Src.getNode(), Src.getResNo() + i),
3289 Add, MachinePointerInfo(PtrV, Offsets[i]),
3290 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3291 Chains[ChainI] = St;
3294 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3295 MVT::Other, &Chains[0], ChainI);
3297 AssignOrderingToNode(StoreNode.getNode());
3298 DAG.setRoot(StoreNode);
3301 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
3302 SynchronizationScope Scope,
3303 bool Before, DebugLoc dl,
3305 const TargetLowering &TLI) {
3306 // Fence, if necessary
3308 if (Order == AcquireRelease || Order == SequentiallyConsistent)
3310 else if (Order == Acquire || Order == Monotonic)
3313 if (Order == AcquireRelease)
3315 else if (Order == Release || Order == Monotonic)
3320 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3321 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
3322 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3325 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3326 DebugLoc dl = getCurDebugLoc();
3327 AtomicOrdering Order = I.getOrdering();
3328 SynchronizationScope Scope = I.getSynchScope();
3330 SDValue InChain = getRoot();
3332 if (TLI.getInsertFencesForAtomic())
3333 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3337 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
3338 getValue(I.getCompareOperand()).getValueType().getSimpleVT(),
3340 getValue(I.getPointerOperand()),
3341 getValue(I.getCompareOperand()),
3342 getValue(I.getNewValOperand()),
3343 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
3344 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3347 SDValue OutChain = L.getValue(1);
3349 if (TLI.getInsertFencesForAtomic())
3350 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3354 DAG.setRoot(OutChain);
3357 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3358 DebugLoc dl = getCurDebugLoc();
3360 switch (I.getOperation()) {
3361 default: llvm_unreachable("Unknown atomicrmw operation"); return;
3362 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3363 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3364 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3365 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3366 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3367 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3368 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3369 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3370 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3371 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3372 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3374 AtomicOrdering Order = I.getOrdering();
3375 SynchronizationScope Scope = I.getSynchScope();
3377 SDValue InChain = getRoot();
3379 if (TLI.getInsertFencesForAtomic())
3380 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3384 DAG.getAtomic(NT, dl,
3385 getValue(I.getValOperand()).getValueType().getSimpleVT(),
3387 getValue(I.getPointerOperand()),
3388 getValue(I.getValOperand()),
3389 I.getPointerOperand(), 0 /* Alignment */,
3390 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3393 SDValue OutChain = L.getValue(1);
3395 if (TLI.getInsertFencesForAtomic())
3396 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3400 DAG.setRoot(OutChain);
3403 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3404 DebugLoc dl = getCurDebugLoc();
3407 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3408 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3409 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
3412 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3413 DebugLoc dl = getCurDebugLoc();
3414 AtomicOrdering Order = I.getOrdering();
3415 SynchronizationScope Scope = I.getSynchScope();
3417 SDValue InChain = getRoot();
3419 EVT VT = EVT::getEVT(I.getType());
3421 if (I.getAlignment() * 8 < VT.getSizeInBits())
3422 report_fatal_error("Cannot generate unaligned atomic load");
3425 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3426 getValue(I.getPointerOperand()),
3427 I.getPointerOperand(), I.getAlignment(),
3428 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3431 SDValue OutChain = L.getValue(1);
3433 if (TLI.getInsertFencesForAtomic())
3434 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3438 DAG.setRoot(OutChain);
3441 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3442 DebugLoc dl = getCurDebugLoc();
3444 AtomicOrdering Order = I.getOrdering();
3445 SynchronizationScope Scope = I.getSynchScope();
3447 SDValue InChain = getRoot();
3449 EVT VT = EVT::getEVT(I.getValueOperand()->getType());
3451 if (I.getAlignment() * 8 < VT.getSizeInBits())
3452 report_fatal_error("Cannot generate unaligned atomic store");
3454 if (TLI.getInsertFencesForAtomic())
3455 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3459 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3461 getValue(I.getPointerOperand()),
3462 getValue(I.getValueOperand()),
3463 I.getPointerOperand(), I.getAlignment(),
3464 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3467 if (TLI.getInsertFencesForAtomic())
3468 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3471 DAG.setRoot(OutChain);
3474 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3476 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3477 unsigned Intrinsic) {
3478 bool HasChain = !I.doesNotAccessMemory();
3479 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3481 // Build the operand list.
3482 SmallVector<SDValue, 8> Ops;
3483 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3485 // We don't need to serialize loads against other loads.
3486 Ops.push_back(DAG.getRoot());
3488 Ops.push_back(getRoot());
3492 // Info is set by getTgtMemInstrinsic
3493 TargetLowering::IntrinsicInfo Info;
3494 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3496 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3497 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3498 Info.opc == ISD::INTRINSIC_W_CHAIN)
3499 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3501 // Add all operands of the call to the operand list.
3502 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3503 SDValue Op = getValue(I.getArgOperand(i));
3504 assert(TLI.isTypeLegal(Op.getValueType()) &&
3505 "Intrinsic uses a non-legal type?");
3509 SmallVector<EVT, 4> ValueVTs;
3510 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3512 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3513 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3514 "Intrinsic uses a non-legal type?");
3519 ValueVTs.push_back(MVT::Other);
3521 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3525 if (IsTgtIntrinsic) {
3526 // This is target intrinsic that touches memory
3527 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3528 VTs, &Ops[0], Ops.size(),
3530 MachinePointerInfo(Info.ptrVal, Info.offset),
3531 Info.align, Info.vol,
3532 Info.readMem, Info.writeMem);
3533 } else if (!HasChain) {
3534 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3535 VTs, &Ops[0], Ops.size());
3536 } else if (!I.getType()->isVoidTy()) {
3537 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3538 VTs, &Ops[0], Ops.size());
3540 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3541 VTs, &Ops[0], Ops.size());
3545 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3547 PendingLoads.push_back(Chain);
3552 if (!I.getType()->isVoidTy()) {
3553 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3554 EVT VT = TLI.getValueType(PTy);
3555 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
3558 setValue(&I, Result);
3562 /// GetSignificand - Get the significand and build it into a floating-point
3563 /// number with exponent of 1:
3565 /// Op = (Op & 0x007fffff) | 0x3f800000;
3567 /// where Op is the hexidecimal representation of floating point value.
3569 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3570 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3571 DAG.getConstant(0x007fffff, MVT::i32));
3572 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3573 DAG.getConstant(0x3f800000, MVT::i32));
3574 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3577 /// GetExponent - Get the exponent:
3579 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3581 /// where Op is the hexidecimal representation of floating point value.
3583 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3585 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3586 DAG.getConstant(0x7f800000, MVT::i32));
3587 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3588 DAG.getConstant(23, TLI.getPointerTy()));
3589 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3590 DAG.getConstant(127, MVT::i32));
3591 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3594 /// getF32Constant - Get 32-bit floating point constant.
3596 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3597 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3600 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3602 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3603 SDValue Op1 = getValue(I.getArgOperand(0));
3604 SDValue Op2 = getValue(I.getArgOperand(1));
3606 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3607 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3611 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3612 /// limited-precision mode.
3614 SelectionDAGBuilder::visitExp(const CallInst &I) {
3616 DebugLoc dl = getCurDebugLoc();
3618 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3619 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3620 SDValue Op = getValue(I.getArgOperand(0));
3622 // Put the exponent in the right bit position for later addition to the
3625 // #define LOG2OFe 1.4426950f
3626 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3627 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3628 getF32Constant(DAG, 0x3fb8aa3b));
3629 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3631 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3632 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3633 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3635 // IntegerPartOfX <<= 23;
3636 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3637 DAG.getConstant(23, TLI.getPointerTy()));
3639 if (LimitFloatPrecision <= 6) {
3640 // For floating-point precision of 6:
3642 // TwoToFractionalPartOfX =
3644 // (0.735607626f + 0.252464424f * x) * x;
3646 // error 0.0144103317, which is 6 bits
3647 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3648 getF32Constant(DAG, 0x3e814304));
3649 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3650 getF32Constant(DAG, 0x3f3c50c8));
3651 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3652 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3653 getF32Constant(DAG, 0x3f7f5e7e));
3654 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
3656 // Add the exponent into the result in integer domain.
3657 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3658 TwoToFracPartOfX, IntegerPartOfX);
3660 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
3661 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3662 // For floating-point precision of 12:
3664 // TwoToFractionalPartOfX =
3667 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3669 // 0.000107046256 error, which is 13 to 14 bits
3670 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3671 getF32Constant(DAG, 0x3da235e3));
3672 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3673 getF32Constant(DAG, 0x3e65b8f3));
3674 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3675 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3676 getF32Constant(DAG, 0x3f324b07));
3677 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3678 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3679 getF32Constant(DAG, 0x3f7ff8fd));
3680 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
3682 // Add the exponent into the result in integer domain.
3683 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3684 TwoToFracPartOfX, IntegerPartOfX);
3686 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
3687 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3688 // For floating-point precision of 18:
3690 // TwoToFractionalPartOfX =
3694 // (0.554906021e-1f +
3695 // (0.961591928e-2f +
3696 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3698 // error 2.47208000*10^(-7), which is better than 18 bits
3699 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3700 getF32Constant(DAG, 0x3924b03e));
3701 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3702 getF32Constant(DAG, 0x3ab24b87));
3703 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3704 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3705 getF32Constant(DAG, 0x3c1d8c17));
3706 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3707 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3708 getF32Constant(DAG, 0x3d634a1d));
3709 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3710 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3711 getF32Constant(DAG, 0x3e75fe14));
3712 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3713 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3714 getF32Constant(DAG, 0x3f317234));
3715 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3716 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3717 getF32Constant(DAG, 0x3f800000));
3718 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
3721 // Add the exponent into the result in integer domain.
3722 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3723 TwoToFracPartOfX, IntegerPartOfX);
3725 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
3728 // No special expansion.
3729 result = DAG.getNode(ISD::FEXP, dl,
3730 getValue(I.getArgOperand(0)).getValueType(),
3731 getValue(I.getArgOperand(0)));
3734 setValue(&I, result);
3737 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3738 /// limited-precision mode.
3740 SelectionDAGBuilder::visitLog(const CallInst &I) {
3742 DebugLoc dl = getCurDebugLoc();
3744 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3745 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3746 SDValue Op = getValue(I.getArgOperand(0));
3747 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3749 // Scale the exponent by log(2) [0.69314718f].
3750 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3751 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3752 getF32Constant(DAG, 0x3f317218));
3754 // Get the significand and build it into a floating-point number with
3756 SDValue X = GetSignificand(DAG, Op1, dl);
3758 if (LimitFloatPrecision <= 6) {
3759 // For floating-point precision of 6:
3763 // (1.4034025f - 0.23903021f * x) * x;
3765 // error 0.0034276066, which is better than 8 bits
3766 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3767 getF32Constant(DAG, 0xbe74c456));
3768 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3769 getF32Constant(DAG, 0x3fb3a2b1));
3770 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3771 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3772 getF32Constant(DAG, 0x3f949a29));
3774 result = DAG.getNode(ISD::FADD, dl,
3775 MVT::f32, LogOfExponent, LogOfMantissa);
3776 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3777 // For floating-point precision of 12:
3783 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3785 // error 0.000061011436, which is 14 bits
3786 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3787 getF32Constant(DAG, 0xbd67b6d6));
3788 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3789 getF32Constant(DAG, 0x3ee4f4b8));
3790 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3791 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3792 getF32Constant(DAG, 0x3fbc278b));
3793 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3794 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3795 getF32Constant(DAG, 0x40348e95));
3796 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3797 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3798 getF32Constant(DAG, 0x3fdef31a));
3800 result = DAG.getNode(ISD::FADD, dl,
3801 MVT::f32, LogOfExponent, LogOfMantissa);
3802 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3803 // For floating-point precision of 18:
3811 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3813 // error 0.0000023660568, which is better than 18 bits
3814 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3815 getF32Constant(DAG, 0xbc91e5ac));
3816 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3817 getF32Constant(DAG, 0x3e4350aa));
3818 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3819 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3820 getF32Constant(DAG, 0x3f60d3e3));
3821 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3822 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3823 getF32Constant(DAG, 0x4011cdf0));
3824 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3825 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3826 getF32Constant(DAG, 0x406cfd1c));
3827 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3828 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3829 getF32Constant(DAG, 0x408797cb));
3830 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3831 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3832 getF32Constant(DAG, 0x4006dcab));
3834 result = DAG.getNode(ISD::FADD, dl,
3835 MVT::f32, LogOfExponent, LogOfMantissa);
3838 // No special expansion.
3839 result = DAG.getNode(ISD::FLOG, dl,
3840 getValue(I.getArgOperand(0)).getValueType(),
3841 getValue(I.getArgOperand(0)));
3844 setValue(&I, result);
3847 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3848 /// limited-precision mode.
3850 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3852 DebugLoc dl = getCurDebugLoc();
3854 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3855 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3856 SDValue Op = getValue(I.getArgOperand(0));
3857 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3859 // Get the exponent.
3860 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3862 // Get the significand and build it into a floating-point number with
3864 SDValue X = GetSignificand(DAG, Op1, dl);
3866 // Different possible minimax approximations of significand in
3867 // floating-point for various degrees of accuracy over [1,2].
3868 if (LimitFloatPrecision <= 6) {
3869 // For floating-point precision of 6:
3871 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3873 // error 0.0049451742, which is more than 7 bits
3874 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3875 getF32Constant(DAG, 0xbeb08fe0));
3876 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3877 getF32Constant(DAG, 0x40019463));
3878 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3879 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3880 getF32Constant(DAG, 0x3fd6633d));
3882 result = DAG.getNode(ISD::FADD, dl,
3883 MVT::f32, LogOfExponent, Log2ofMantissa);
3884 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3885 // For floating-point precision of 12:
3891 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3893 // error 0.0000876136000, which is better than 13 bits
3894 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3895 getF32Constant(DAG, 0xbda7262e));
3896 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3897 getF32Constant(DAG, 0x3f25280b));
3898 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3899 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3900 getF32Constant(DAG, 0x4007b923));
3901 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3902 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3903 getF32Constant(DAG, 0x40823e2f));
3904 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3905 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3906 getF32Constant(DAG, 0x4020d29c));
3908 result = DAG.getNode(ISD::FADD, dl,
3909 MVT::f32, LogOfExponent, Log2ofMantissa);
3910 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3911 // For floating-point precision of 18:
3920 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3922 // error 0.0000018516, which is better than 18 bits
3923 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3924 getF32Constant(DAG, 0xbcd2769e));
3925 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3926 getF32Constant(DAG, 0x3e8ce0b9));
3927 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3928 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3929 getF32Constant(DAG, 0x3fa22ae7));
3930 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3931 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3932 getF32Constant(DAG, 0x40525723));
3933 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3934 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3935 getF32Constant(DAG, 0x40aaf200));
3936 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3937 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3938 getF32Constant(DAG, 0x40c39dad));
3939 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3940 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3941 getF32Constant(DAG, 0x4042902c));
3943 result = DAG.getNode(ISD::FADD, dl,
3944 MVT::f32, LogOfExponent, Log2ofMantissa);
3947 // No special expansion.
3948 result = DAG.getNode(ISD::FLOG2, dl,
3949 getValue(I.getArgOperand(0)).getValueType(),
3950 getValue(I.getArgOperand(0)));
3953 setValue(&I, result);
3956 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3957 /// limited-precision mode.
3959 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3961 DebugLoc dl = getCurDebugLoc();
3963 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3964 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3965 SDValue Op = getValue(I.getArgOperand(0));
3966 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3968 // Scale the exponent by log10(2) [0.30102999f].
3969 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3970 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3971 getF32Constant(DAG, 0x3e9a209a));
3973 // Get the significand and build it into a floating-point number with
3975 SDValue X = GetSignificand(DAG, Op1, dl);
3977 if (LimitFloatPrecision <= 6) {
3978 // For floating-point precision of 6:
3980 // Log10ofMantissa =
3982 // (0.60948995f - 0.10380950f * x) * x;
3984 // error 0.0014886165, which is 6 bits
3985 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3986 getF32Constant(DAG, 0xbdd49a13));
3987 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3988 getF32Constant(DAG, 0x3f1c0789));
3989 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3990 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3991 getF32Constant(DAG, 0x3f011300));
3993 result = DAG.getNode(ISD::FADD, dl,
3994 MVT::f32, LogOfExponent, Log10ofMantissa);
3995 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3996 // For floating-point precision of 12:
3998 // Log10ofMantissa =
4001 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4003 // error 0.00019228036, which is better than 12 bits
4004 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4005 getF32Constant(DAG, 0x3d431f31));
4006 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4007 getF32Constant(DAG, 0x3ea21fb2));
4008 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4009 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4010 getF32Constant(DAG, 0x3f6ae232));
4011 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4012 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4013 getF32Constant(DAG, 0x3f25f7c3));
4015 result = DAG.getNode(ISD::FADD, dl,
4016 MVT::f32, LogOfExponent, Log10ofMantissa);
4017 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4018 // For floating-point precision of 18:
4020 // Log10ofMantissa =
4025 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4027 // error 0.0000037995730, which is better than 18 bits
4028 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4029 getF32Constant(DAG, 0x3c5d51ce));
4030 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4031 getF32Constant(DAG, 0x3e00685a));
4032 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4033 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4034 getF32Constant(DAG, 0x3efb6798));
4035 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4036 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4037 getF32Constant(DAG, 0x3f88d192));
4038 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4039 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4040 getF32Constant(DAG, 0x3fc4316c));
4041 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4042 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4043 getF32Constant(DAG, 0x3f57ce70));
4045 result = DAG.getNode(ISD::FADD, dl,
4046 MVT::f32, LogOfExponent, Log10ofMantissa);
4049 // No special expansion.
4050 result = DAG.getNode(ISD::FLOG10, dl,
4051 getValue(I.getArgOperand(0)).getValueType(),
4052 getValue(I.getArgOperand(0)));
4055 setValue(&I, result);
4058 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4059 /// limited-precision mode.
4061 SelectionDAGBuilder::visitExp2(const CallInst &I) {
4063 DebugLoc dl = getCurDebugLoc();
4065 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
4066 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4067 SDValue Op = getValue(I.getArgOperand(0));
4069 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4071 // FractionalPartOfX = x - (float)IntegerPartOfX;
4072 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4073 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4075 // IntegerPartOfX <<= 23;
4076 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4077 DAG.getConstant(23, TLI.getPointerTy()));
4079 if (LimitFloatPrecision <= 6) {
4080 // For floating-point precision of 6:
4082 // TwoToFractionalPartOfX =
4084 // (0.735607626f + 0.252464424f * x) * x;
4086 // error 0.0144103317, which is 6 bits
4087 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4088 getF32Constant(DAG, 0x3e814304));
4089 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4090 getF32Constant(DAG, 0x3f3c50c8));
4091 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4092 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4093 getF32Constant(DAG, 0x3f7f5e7e));
4094 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
4095 SDValue TwoToFractionalPartOfX =
4096 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4098 result = DAG.getNode(ISD::BITCAST, dl,
4099 MVT::f32, TwoToFractionalPartOfX);
4100 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4101 // For floating-point precision of 12:
4103 // TwoToFractionalPartOfX =
4106 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4108 // error 0.000107046256, which is 13 to 14 bits
4109 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4110 getF32Constant(DAG, 0x3da235e3));
4111 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4112 getF32Constant(DAG, 0x3e65b8f3));
4113 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4114 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4115 getF32Constant(DAG, 0x3f324b07));
4116 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4117 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4118 getF32Constant(DAG, 0x3f7ff8fd));
4119 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
4120 SDValue TwoToFractionalPartOfX =
4121 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4123 result = DAG.getNode(ISD::BITCAST, dl,
4124 MVT::f32, TwoToFractionalPartOfX);
4125 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4126 // For floating-point precision of 18:
4128 // TwoToFractionalPartOfX =
4132 // (0.554906021e-1f +
4133 // (0.961591928e-2f +
4134 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4135 // error 2.47208000*10^(-7), which is better than 18 bits
4136 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4137 getF32Constant(DAG, 0x3924b03e));
4138 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4139 getF32Constant(DAG, 0x3ab24b87));
4140 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4141 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4142 getF32Constant(DAG, 0x3c1d8c17));
4143 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4144 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4145 getF32Constant(DAG, 0x3d634a1d));
4146 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4147 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4148 getF32Constant(DAG, 0x3e75fe14));
4149 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4150 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4151 getF32Constant(DAG, 0x3f317234));
4152 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4153 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4154 getF32Constant(DAG, 0x3f800000));
4155 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
4156 SDValue TwoToFractionalPartOfX =
4157 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4159 result = DAG.getNode(ISD::BITCAST, dl,
4160 MVT::f32, TwoToFractionalPartOfX);
4163 // No special expansion.
4164 result = DAG.getNode(ISD::FEXP2, dl,
4165 getValue(I.getArgOperand(0)).getValueType(),
4166 getValue(I.getArgOperand(0)));
4169 setValue(&I, result);
4172 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4173 /// limited-precision mode with x == 10.0f.
4175 SelectionDAGBuilder::visitPow(const CallInst &I) {
4177 const Value *Val = I.getArgOperand(0);
4178 DebugLoc dl = getCurDebugLoc();
4179 bool IsExp10 = false;
4181 if (getValue(Val).getValueType() == MVT::f32 &&
4182 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
4183 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4184 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4185 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4187 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4192 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4193 SDValue Op = getValue(I.getArgOperand(1));
4195 // Put the exponent in the right bit position for later addition to the
4198 // #define LOG2OF10 3.3219281f
4199 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4200 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4201 getF32Constant(DAG, 0x40549a78));
4202 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4204 // FractionalPartOfX = x - (float)IntegerPartOfX;
4205 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4206 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4208 // IntegerPartOfX <<= 23;
4209 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4210 DAG.getConstant(23, TLI.getPointerTy()));
4212 if (LimitFloatPrecision <= 6) {
4213 // For floating-point precision of 6:
4215 // twoToFractionalPartOfX =
4217 // (0.735607626f + 0.252464424f * x) * x;
4219 // error 0.0144103317, which is 6 bits
4220 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4221 getF32Constant(DAG, 0x3e814304));
4222 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4223 getF32Constant(DAG, 0x3f3c50c8));
4224 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4225 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4226 getF32Constant(DAG, 0x3f7f5e7e));
4227 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
4228 SDValue TwoToFractionalPartOfX =
4229 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4231 result = DAG.getNode(ISD::BITCAST, dl,
4232 MVT::f32, TwoToFractionalPartOfX);
4233 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4234 // For floating-point precision of 12:
4236 // TwoToFractionalPartOfX =
4239 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4241 // error 0.000107046256, which is 13 to 14 bits
4242 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4243 getF32Constant(DAG, 0x3da235e3));
4244 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4245 getF32Constant(DAG, 0x3e65b8f3));
4246 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4247 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4248 getF32Constant(DAG, 0x3f324b07));
4249 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4250 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4251 getF32Constant(DAG, 0x3f7ff8fd));
4252 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
4253 SDValue TwoToFractionalPartOfX =
4254 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4256 result = DAG.getNode(ISD::BITCAST, dl,
4257 MVT::f32, TwoToFractionalPartOfX);
4258 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4259 // For floating-point precision of 18:
4261 // TwoToFractionalPartOfX =
4265 // (0.554906021e-1f +
4266 // (0.961591928e-2f +
4267 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4268 // error 2.47208000*10^(-7), which is better than 18 bits
4269 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4270 getF32Constant(DAG, 0x3924b03e));
4271 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4272 getF32Constant(DAG, 0x3ab24b87));
4273 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4274 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4275 getF32Constant(DAG, 0x3c1d8c17));
4276 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4277 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4278 getF32Constant(DAG, 0x3d634a1d));
4279 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4280 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4281 getF32Constant(DAG, 0x3e75fe14));
4282 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4283 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4284 getF32Constant(DAG, 0x3f317234));
4285 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4286 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4287 getF32Constant(DAG, 0x3f800000));
4288 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
4289 SDValue TwoToFractionalPartOfX =
4290 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4292 result = DAG.getNode(ISD::BITCAST, dl,
4293 MVT::f32, TwoToFractionalPartOfX);
4296 // No special expansion.
4297 result = DAG.getNode(ISD::FPOW, dl,
4298 getValue(I.getArgOperand(0)).getValueType(),
4299 getValue(I.getArgOperand(0)),
4300 getValue(I.getArgOperand(1)));
4303 setValue(&I, result);
4307 /// ExpandPowI - Expand a llvm.powi intrinsic.
4308 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4309 SelectionDAG &DAG) {
4310 // If RHS is a constant, we can expand this out to a multiplication tree,
4311 // otherwise we end up lowering to a call to __powidf2 (for example). When
4312 // optimizing for size, we only want to do this if the expansion would produce
4313 // a small number of multiplies, otherwise we do the full expansion.
4314 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4315 // Get the exponent as a positive value.
4316 unsigned Val = RHSC->getSExtValue();
4317 if ((int)Val < 0) Val = -Val;
4319 // powi(x, 0) -> 1.0
4321 return DAG.getConstantFP(1.0, LHS.getValueType());
4323 const Function *F = DAG.getMachineFunction().getFunction();
4324 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
4325 // If optimizing for size, don't insert too many multiplies. This
4326 // inserts up to 5 multiplies.
4327 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4328 // We use the simple binary decomposition method to generate the multiply
4329 // sequence. There are more optimal ways to do this (for example,
4330 // powi(x,15) generates one more multiply than it should), but this has
4331 // the benefit of being both really simple and much better than a libcall.
4332 SDValue Res; // Logically starts equal to 1.0
4333 SDValue CurSquare = LHS;
4337 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4339 Res = CurSquare; // 1.0*CurSquare.
4342 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4343 CurSquare, CurSquare);
4347 // If the original was negative, invert the result, producing 1/(x*x*x).
4348 if (RHSC->getSExtValue() < 0)
4349 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4350 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4355 // Otherwise, expand to a libcall.
4356 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4359 // getTruncatedArgReg - Find underlying register used for an truncated
4361 static unsigned getTruncatedArgReg(const SDValue &N) {
4362 if (N.getOpcode() != ISD::TRUNCATE)
4365 const SDValue &Ext = N.getOperand(0);
4366 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4367 const SDValue &CFR = Ext.getOperand(0);
4368 if (CFR.getOpcode() == ISD::CopyFromReg)
4369 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4371 if (CFR.getOpcode() == ISD::TRUNCATE)
4372 return getTruncatedArgReg(CFR);
4377 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4378 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4379 /// At the end of instruction selection, they will be inserted to the entry BB.
4381 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4384 const Argument *Arg = dyn_cast<Argument>(V);
4388 MachineFunction &MF = DAG.getMachineFunction();
4389 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4390 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4392 // Ignore inlined function arguments here.
4393 DIVariable DV(Variable);
4394 if (DV.isInlinedFnArgument(MF.getFunction()))
4398 // Some arguments' frame index is recorded during argument lowering.
4399 Offset = FuncInfo.getArgumentFrameIndex(Arg);
4401 Reg = TRI->getFrameRegister(MF);
4403 if (!Reg && N.getNode()) {
4404 if (N.getOpcode() == ISD::CopyFromReg)
4405 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4407 Reg = getTruncatedArgReg(N);
4408 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4409 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4410 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4417 // Check if ValueMap has reg number.
4418 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4419 if (VMI != FuncInfo.ValueMap.end())
4423 if (!Reg && N.getNode()) {
4424 // Check if frame index is available.
4425 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4426 if (FrameIndexSDNode *FINode =
4427 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4428 Reg = TRI->getFrameRegister(MF);
4429 Offset = FINode->getIndex();
4436 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4437 TII->get(TargetOpcode::DBG_VALUE))
4438 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
4439 FuncInfo.ArgDbgValues.push_back(&*MIB);
4443 // VisualStudio defines setjmp as _setjmp
4444 #if defined(_MSC_VER) && defined(setjmp) && \
4445 !defined(setjmp_undefined_for_msvc)
4446 # pragma push_macro("setjmp")
4448 # define setjmp_undefined_for_msvc
4451 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4452 /// we want to emit this as a call to a named external function, return the name
4453 /// otherwise lower it and return null.
4455 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4456 DebugLoc dl = getCurDebugLoc();
4459 switch (Intrinsic) {
4461 // By default, turn this into a target intrinsic node.
4462 visitTargetIntrinsic(I, Intrinsic);
4464 case Intrinsic::vastart: visitVAStart(I); return 0;
4465 case Intrinsic::vaend: visitVAEnd(I); return 0;
4466 case Intrinsic::vacopy: visitVACopy(I); return 0;
4467 case Intrinsic::returnaddress:
4468 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4469 getValue(I.getArgOperand(0))));
4471 case Intrinsic::frameaddress:
4472 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4473 getValue(I.getArgOperand(0))));
4475 case Intrinsic::setjmp:
4476 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4477 case Intrinsic::longjmp:
4478 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4479 case Intrinsic::memcpy: {
4480 // Assert for address < 256 since we support only user defined address
4482 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4484 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4486 "Unknown address space");
4487 SDValue Op1 = getValue(I.getArgOperand(0));
4488 SDValue Op2 = getValue(I.getArgOperand(1));
4489 SDValue Op3 = getValue(I.getArgOperand(2));
4490 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4491 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4492 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
4493 MachinePointerInfo(I.getArgOperand(0)),
4494 MachinePointerInfo(I.getArgOperand(1))));
4497 case Intrinsic::memset: {
4498 // Assert for address < 256 since we support only user defined address
4500 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4502 "Unknown address space");
4503 SDValue Op1 = getValue(I.getArgOperand(0));
4504 SDValue Op2 = getValue(I.getArgOperand(1));
4505 SDValue Op3 = getValue(I.getArgOperand(2));
4506 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4507 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4508 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4509 MachinePointerInfo(I.getArgOperand(0))));
4512 case Intrinsic::memmove: {
4513 // Assert for address < 256 since we support only user defined address
4515 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4517 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4519 "Unknown address space");
4520 SDValue Op1 = getValue(I.getArgOperand(0));
4521 SDValue Op2 = getValue(I.getArgOperand(1));
4522 SDValue Op3 = getValue(I.getArgOperand(2));
4523 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4524 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4525 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4526 MachinePointerInfo(I.getArgOperand(0)),
4527 MachinePointerInfo(I.getArgOperand(1))));
4530 case Intrinsic::dbg_declare: {
4531 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4532 MDNode *Variable = DI.getVariable();
4533 const Value *Address = DI.getAddress();
4534 if (!Address || !DIVariable(Variable).Verify())
4537 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4538 // but do not always have a corresponding SDNode built. The SDNodeOrder
4539 // absolute, but not relative, values are different depending on whether
4540 // debug info exists.
4543 // Check if address has undef value.
4544 if (isa<UndefValue>(Address) ||
4545 (Address->use_empty() && !isa<Argument>(Address))) {
4546 DEBUG(dbgs() << "Dropping debug info for " << DI);
4550 SDValue &N = NodeMap[Address];
4551 if (!N.getNode() && isa<Argument>(Address))
4552 // Check unused arguments map.
4553 N = UnusedArgNodeMap[Address];
4556 // Parameters are handled specially.
4558 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
4559 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4560 Address = BCI->getOperand(0);
4561 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4563 if (isParameter && !AI) {
4564 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4566 // Byval parameter. We have a frame index at this point.
4567 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4568 0, dl, SDNodeOrder);
4570 // Address is an argument, so try to emit its dbg value using
4571 // virtual register info from the FuncInfo.ValueMap.
4572 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4576 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4577 0, dl, SDNodeOrder);
4579 // Can't do anything with other non-AI cases yet.
4580 DEBUG(dbgs() << "Dropping debug info for " << DI);
4583 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4585 // If Address is an argument then try to emit its dbg value using
4586 // virtual register info from the FuncInfo.ValueMap.
4587 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4588 // If variable is pinned by a alloca in dominating bb then
4589 // use StaticAllocaMap.
4590 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4591 if (AI->getParent() != DI.getParent()) {
4592 DenseMap<const AllocaInst*, int>::iterator SI =
4593 FuncInfo.StaticAllocaMap.find(AI);
4594 if (SI != FuncInfo.StaticAllocaMap.end()) {
4595 SDV = DAG.getDbgValue(Variable, SI->second,
4596 0, dl, SDNodeOrder);
4597 DAG.AddDbgValue(SDV, 0, false);
4602 DEBUG(dbgs() << "Dropping debug info for " << DI);
4607 case Intrinsic::dbg_value: {
4608 const DbgValueInst &DI = cast<DbgValueInst>(I);
4609 if (!DIVariable(DI.getVariable()).Verify())
4612 MDNode *Variable = DI.getVariable();
4613 uint64_t Offset = DI.getOffset();
4614 const Value *V = DI.getValue();
4618 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4619 // but do not always have a corresponding SDNode built. The SDNodeOrder
4620 // absolute, but not relative, values are different depending on whether
4621 // debug info exists.
4624 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4625 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4626 DAG.AddDbgValue(SDV, 0, false);
4628 // Do not use getValue() in here; we don't want to generate code at
4629 // this point if it hasn't been done yet.
4630 SDValue N = NodeMap[V];
4631 if (!N.getNode() && isa<Argument>(V))
4632 // Check unused arguments map.
4633 N = UnusedArgNodeMap[V];
4635 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4636 SDV = DAG.getDbgValue(Variable, N.getNode(),
4637 N.getResNo(), Offset, dl, SDNodeOrder);
4638 DAG.AddDbgValue(SDV, N.getNode(), false);
4640 } else if (!V->use_empty() ) {
4641 // Do not call getValue(V) yet, as we don't want to generate code.
4642 // Remember it for later.
4643 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4644 DanglingDebugInfoMap[V] = DDI;
4646 // We may expand this to cover more cases. One case where we have no
4647 // data available is an unreferenced parameter.
4648 DEBUG(dbgs() << "Dropping debug info for " << DI);
4652 // Build a debug info table entry.
4653 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4654 V = BCI->getOperand(0);
4655 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4656 // Don't handle byval struct arguments or VLAs, for example.
4659 DenseMap<const AllocaInst*, int>::iterator SI =
4660 FuncInfo.StaticAllocaMap.find(AI);
4661 if (SI == FuncInfo.StaticAllocaMap.end())
4663 int FI = SI->second;
4665 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4666 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4667 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4670 case Intrinsic::eh_exception: {
4671 // Insert the EXCEPTIONADDR instruction.
4672 assert(FuncInfo.MBB->isLandingPad() &&
4673 "Call to eh.exception not in landing pad!");
4674 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4676 Ops[0] = DAG.getRoot();
4677 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4679 DAG.setRoot(Op.getValue(1));
4683 case Intrinsic::eh_selector: {
4684 MachineBasicBlock *CallMBB = FuncInfo.MBB;
4685 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4686 if (CallMBB->isLandingPad())
4687 AddCatchInfo(I, &MMI, CallMBB);
4690 FuncInfo.CatchInfoLost.insert(&I);
4692 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4693 unsigned Reg = TLI.getExceptionSelectorRegister();
4694 if (Reg) FuncInfo.MBB->addLiveIn(Reg);
4697 // Insert the EHSELECTION instruction.
4698 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4700 Ops[0] = getValue(I.getArgOperand(0));
4702 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4703 DAG.setRoot(Op.getValue(1));
4704 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4708 case Intrinsic::eh_typeid_for: {
4709 // Find the type id for the given typeinfo.
4710 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4711 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4712 Res = DAG.getConstant(TypeID, MVT::i32);
4717 case Intrinsic::eh_return_i32:
4718 case Intrinsic::eh_return_i64:
4719 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4720 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4723 getValue(I.getArgOperand(0)),
4724 getValue(I.getArgOperand(1))));
4726 case Intrinsic::eh_unwind_init:
4727 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4729 case Intrinsic::eh_dwarf_cfa: {
4730 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4731 TLI.getPointerTy());
4732 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4734 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4735 TLI.getPointerTy()),
4737 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4739 DAG.getConstant(0, TLI.getPointerTy()));
4740 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4744 case Intrinsic::eh_sjlj_callsite: {
4745 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4746 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4747 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4748 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4750 MMI.setCurrentCallSite(CI->getZExtValue());
4753 case Intrinsic::eh_sjlj_functioncontext: {
4754 // Get and store the index of the function context.
4755 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4757 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4758 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4759 MFI->setFunctionContextIndex(FI);
4762 case Intrinsic::eh_sjlj_setjmp: {
4765 Ops[1] = getValue(I.getArgOperand(0));
4766 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, dl,
4767 DAG.getVTList(MVT::i32, MVT::Other),
4769 setValue(&I, Op.getValue(0));
4770 DAG.setRoot(Op.getValue(1));
4773 case Intrinsic::eh_sjlj_longjmp: {
4774 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4775 getRoot(), getValue(I.getArgOperand(0))));
4778 case Intrinsic::eh_sjlj_dispatch_setup: {
4779 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
4780 getRoot(), getValue(I.getArgOperand(0))));
4784 case Intrinsic::x86_mmx_pslli_w:
4785 case Intrinsic::x86_mmx_pslli_d:
4786 case Intrinsic::x86_mmx_pslli_q:
4787 case Intrinsic::x86_mmx_psrli_w:
4788 case Intrinsic::x86_mmx_psrli_d:
4789 case Intrinsic::x86_mmx_psrli_q:
4790 case Intrinsic::x86_mmx_psrai_w:
4791 case Intrinsic::x86_mmx_psrai_d: {
4792 SDValue ShAmt = getValue(I.getArgOperand(1));
4793 if (isa<ConstantSDNode>(ShAmt)) {
4794 visitTargetIntrinsic(I, Intrinsic);
4797 unsigned NewIntrinsic = 0;
4798 EVT ShAmtVT = MVT::v2i32;
4799 switch (Intrinsic) {
4800 case Intrinsic::x86_mmx_pslli_w:
4801 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4803 case Intrinsic::x86_mmx_pslli_d:
4804 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4806 case Intrinsic::x86_mmx_pslli_q:
4807 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4809 case Intrinsic::x86_mmx_psrli_w:
4810 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4812 case Intrinsic::x86_mmx_psrli_d:
4813 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4815 case Intrinsic::x86_mmx_psrli_q:
4816 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4818 case Intrinsic::x86_mmx_psrai_w:
4819 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4821 case Intrinsic::x86_mmx_psrai_d:
4822 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4824 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4827 // The vector shift intrinsics with scalars uses 32b shift amounts but
4828 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4830 // We must do this early because v2i32 is not a legal type.
4831 DebugLoc dl = getCurDebugLoc();
4834 ShOps[1] = DAG.getConstant(0, MVT::i32);
4835 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4836 EVT DestVT = TLI.getValueType(I.getType());
4837 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
4838 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4839 DAG.getConstant(NewIntrinsic, MVT::i32),
4840 getValue(I.getArgOperand(0)), ShAmt);
4844 case Intrinsic::convertff:
4845 case Intrinsic::convertfsi:
4846 case Intrinsic::convertfui:
4847 case Intrinsic::convertsif:
4848 case Intrinsic::convertuif:
4849 case Intrinsic::convertss:
4850 case Intrinsic::convertsu:
4851 case Intrinsic::convertus:
4852 case Intrinsic::convertuu: {
4853 ISD::CvtCode Code = ISD::CVT_INVALID;
4854 switch (Intrinsic) {
4855 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4856 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4857 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4858 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4859 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4860 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4861 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4862 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4863 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4865 EVT DestVT = TLI.getValueType(I.getType());
4866 const Value *Op1 = I.getArgOperand(0);
4867 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4868 DAG.getValueType(DestVT),
4869 DAG.getValueType(getValue(Op1).getValueType()),
4870 getValue(I.getArgOperand(1)),
4871 getValue(I.getArgOperand(2)),
4876 case Intrinsic::sqrt:
4877 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4878 getValue(I.getArgOperand(0)).getValueType(),
4879 getValue(I.getArgOperand(0))));
4881 case Intrinsic::powi:
4882 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4883 getValue(I.getArgOperand(1)), DAG));
4885 case Intrinsic::sin:
4886 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4887 getValue(I.getArgOperand(0)).getValueType(),
4888 getValue(I.getArgOperand(0))));
4890 case Intrinsic::cos:
4891 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4892 getValue(I.getArgOperand(0)).getValueType(),
4893 getValue(I.getArgOperand(0))));
4895 case Intrinsic::log:
4898 case Intrinsic::log2:
4901 case Intrinsic::log10:
4904 case Intrinsic::exp:
4907 case Intrinsic::exp2:
4910 case Intrinsic::pow:
4913 case Intrinsic::fma:
4914 setValue(&I, DAG.getNode(ISD::FMA, dl,
4915 getValue(I.getArgOperand(0)).getValueType(),
4916 getValue(I.getArgOperand(0)),
4917 getValue(I.getArgOperand(1)),
4918 getValue(I.getArgOperand(2))));
4920 case Intrinsic::convert_to_fp16:
4921 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4922 MVT::i16, getValue(I.getArgOperand(0))));
4924 case Intrinsic::convert_from_fp16:
4925 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4926 MVT::f32, getValue(I.getArgOperand(0))));
4928 case Intrinsic::pcmarker: {
4929 SDValue Tmp = getValue(I.getArgOperand(0));
4930 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4933 case Intrinsic::readcyclecounter: {
4934 SDValue Op = getRoot();
4935 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4936 DAG.getVTList(MVT::i64, MVT::Other),
4939 DAG.setRoot(Res.getValue(1));
4942 case Intrinsic::bswap:
4943 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4944 getValue(I.getArgOperand(0)).getValueType(),
4945 getValue(I.getArgOperand(0))));
4947 case Intrinsic::cttz: {
4948 SDValue Arg = getValue(I.getArgOperand(0));
4949 EVT Ty = Arg.getValueType();
4950 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4953 case Intrinsic::ctlz: {
4954 SDValue Arg = getValue(I.getArgOperand(0));
4955 EVT Ty = Arg.getValueType();
4956 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4959 case Intrinsic::ctpop: {
4960 SDValue Arg = getValue(I.getArgOperand(0));
4961 EVT Ty = Arg.getValueType();
4962 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4965 case Intrinsic::stacksave: {
4966 SDValue Op = getRoot();
4967 Res = DAG.getNode(ISD::STACKSAVE, dl,
4968 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4970 DAG.setRoot(Res.getValue(1));
4973 case Intrinsic::stackrestore: {
4974 Res = getValue(I.getArgOperand(0));
4975 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4978 case Intrinsic::stackprotector: {
4979 // Emit code into the DAG to store the stack guard onto the stack.
4980 MachineFunction &MF = DAG.getMachineFunction();
4981 MachineFrameInfo *MFI = MF.getFrameInfo();
4982 EVT PtrTy = TLI.getPointerTy();
4984 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4985 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4987 int FI = FuncInfo.StaticAllocaMap[Slot];
4988 MFI->setStackProtectorIndex(FI);
4990 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4992 // Store the stack protector onto the stack.
4993 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4994 MachinePointerInfo::getFixedStack(FI),
5000 case Intrinsic::objectsize: {
5001 // If we don't know by now, we're never going to know.
5002 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5004 assert(CI && "Non-constant type in __builtin_object_size?");
5006 SDValue Arg = getValue(I.getCalledValue());
5007 EVT Ty = Arg.getValueType();
5010 Res = DAG.getConstant(-1ULL, Ty);
5012 Res = DAG.getConstant(0, Ty);
5017 case Intrinsic::var_annotation:
5018 // Discard annotate attributes
5021 case Intrinsic::init_trampoline: {
5022 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5026 Ops[1] = getValue(I.getArgOperand(0));
5027 Ops[2] = getValue(I.getArgOperand(1));
5028 Ops[3] = getValue(I.getArgOperand(2));
5029 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5030 Ops[5] = DAG.getSrcValue(F);
5032 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, dl, MVT::Other, Ops, 6);
5037 case Intrinsic::adjust_trampoline: {
5038 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, dl,
5040 getValue(I.getArgOperand(0))));
5043 case Intrinsic::gcroot:
5045 const Value *Alloca = I.getArgOperand(0);
5046 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5048 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5049 GFI->addStackRoot(FI->getIndex(), TypeMap);
5052 case Intrinsic::gcread:
5053 case Intrinsic::gcwrite:
5054 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5056 case Intrinsic::flt_rounds:
5057 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
5060 case Intrinsic::expect: {
5061 // Just replace __builtin_expect(exp, c) with EXP.
5062 setValue(&I, getValue(I.getArgOperand(0)));
5066 case Intrinsic::trap: {
5067 StringRef TrapFuncName = getTrapFunctionName();
5068 if (TrapFuncName.empty()) {
5069 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
5072 TargetLowering::ArgListTy Args;
5073 std::pair<SDValue, SDValue> Result =
5074 TLI.LowerCallTo(getRoot(), I.getType(),
5075 false, false, false, false, 0, CallingConv::C,
5076 /*isTailCall=*/false, /*isReturnValueUsed=*/true,
5077 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
5078 Args, DAG, getCurDebugLoc());
5079 DAG.setRoot(Result.second);
5082 case Intrinsic::uadd_with_overflow:
5083 return implVisitAluOverflow(I, ISD::UADDO);
5084 case Intrinsic::sadd_with_overflow:
5085 return implVisitAluOverflow(I, ISD::SADDO);
5086 case Intrinsic::usub_with_overflow:
5087 return implVisitAluOverflow(I, ISD::USUBO);
5088 case Intrinsic::ssub_with_overflow:
5089 return implVisitAluOverflow(I, ISD::SSUBO);
5090 case Intrinsic::umul_with_overflow:
5091 return implVisitAluOverflow(I, ISD::UMULO);
5092 case Intrinsic::smul_with_overflow:
5093 return implVisitAluOverflow(I, ISD::SMULO);
5095 case Intrinsic::prefetch: {
5097 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5099 Ops[1] = getValue(I.getArgOperand(0));
5100 Ops[2] = getValue(I.getArgOperand(1));
5101 Ops[3] = getValue(I.getArgOperand(2));
5102 Ops[4] = getValue(I.getArgOperand(3));
5103 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
5104 DAG.getVTList(MVT::Other),
5106 EVT::getIntegerVT(*Context, 8),
5107 MachinePointerInfo(I.getArgOperand(0)),
5109 false, /* volatile */
5111 rw==1)); /* write */
5115 case Intrinsic::invariant_start:
5116 case Intrinsic::lifetime_start:
5117 // Discard region information.
5118 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
5120 case Intrinsic::invariant_end:
5121 case Intrinsic::lifetime_end:
5122 // Discard region information.
5127 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5129 MachineBasicBlock *LandingPad) {
5130 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5131 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5132 Type *RetTy = FTy->getReturnType();
5133 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5134 MCSymbol *BeginLabel = 0;
5136 TargetLowering::ArgListTy Args;
5137 TargetLowering::ArgListEntry Entry;
5138 Args.reserve(CS.arg_size());
5140 // Check whether the function can return without sret-demotion.
5141 SmallVector<ISD::OutputArg, 4> Outs;
5142 SmallVector<uint64_t, 4> Offsets;
5143 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
5144 Outs, TLI, &Offsets);
5146 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
5147 DAG.getMachineFunction(),
5148 FTy->isVarArg(), Outs,
5151 SDValue DemoteStackSlot;
5152 int DemoteStackIdx = -100;
5154 if (!CanLowerReturn) {
5155 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
5156 FTy->getReturnType());
5157 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
5158 FTy->getReturnType());
5159 MachineFunction &MF = DAG.getMachineFunction();
5160 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5161 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
5163 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
5164 Entry.Node = DemoteStackSlot;
5165 Entry.Ty = StackSlotPtrType;
5166 Entry.isSExt = false;
5167 Entry.isZExt = false;
5168 Entry.isInReg = false;
5169 Entry.isSRet = true;
5170 Entry.isNest = false;
5171 Entry.isByVal = false;
5172 Entry.Alignment = Align;
5173 Args.push_back(Entry);
5174 RetTy = Type::getVoidTy(FTy->getContext());
5177 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5179 const Value *V = *i;
5182 if (V->getType()->isEmptyTy())
5185 SDValue ArgNode = getValue(V);
5186 Entry.Node = ArgNode; Entry.Ty = V->getType();
5188 unsigned attrInd = i - CS.arg_begin() + 1;
5189 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
5190 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
5191 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
5192 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
5193 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
5194 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
5195 Entry.Alignment = CS.getParamAlignment(attrInd);
5196 Args.push_back(Entry);
5200 // Insert a label before the invoke call to mark the try range. This can be
5201 // used to detect deletion of the invoke via the MachineModuleInfo.
5202 BeginLabel = MMI.getContext().CreateTempSymbol();
5204 // For SjLj, keep track of which landing pads go with which invokes
5205 // so as to maintain the ordering of pads in the LSDA.
5206 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5207 if (CallSiteIndex) {
5208 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5209 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5211 // Now that the call site is handled, stop tracking it.
5212 MMI.setCurrentCallSite(0);
5215 // Both PendingLoads and PendingExports must be flushed here;
5216 // this call might not return.
5218 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
5221 // Check if target-independent constraints permit a tail call here.
5222 // Target-dependent constraints are checked within TLI.LowerCallTo.
5224 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
5227 // If there's a possibility that fast-isel has already selected some amount
5228 // of the current basic block, don't emit a tail call.
5229 if (isTailCall && EnableFastISel)
5232 std::pair<SDValue,SDValue> Result =
5233 TLI.LowerCallTo(getRoot(), RetTy,
5234 CS.paramHasAttr(0, Attribute::SExt),
5235 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
5236 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
5237 CS.getCallingConv(),
5239 !CS.getInstruction()->use_empty(),
5240 Callee, Args, DAG, getCurDebugLoc());
5241 assert((isTailCall || Result.second.getNode()) &&
5242 "Non-null chain expected with non-tail call!");
5243 assert((Result.second.getNode() || !Result.first.getNode()) &&
5244 "Null value expected with tail call!");
5245 if (Result.first.getNode()) {
5246 setValue(CS.getInstruction(), Result.first);
5247 } else if (!CanLowerReturn && Result.second.getNode()) {
5248 // The instruction result is the result of loading from the
5249 // hidden sret parameter.
5250 SmallVector<EVT, 1> PVTs;
5251 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5253 ComputeValueVTs(TLI, PtrRetTy, PVTs);
5254 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5255 EVT PtrVT = PVTs[0];
5256 unsigned NumValues = Outs.size();
5257 SmallVector<SDValue, 4> Values(NumValues);
5258 SmallVector<SDValue, 4> Chains(NumValues);
5260 for (unsigned i = 0; i < NumValues; ++i) {
5261 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5263 DAG.getConstant(Offsets[i], PtrVT));
5264 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second,
5266 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5267 false, false, false, 1);
5269 Chains[i] = L.getValue(1);
5272 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5273 MVT::Other, &Chains[0], NumValues);
5274 PendingLoads.push_back(Chain);
5276 // Collect the legal value parts into potentially illegal values
5277 // that correspond to the original function's return values.
5278 SmallVector<EVT, 4> RetTys;
5279 RetTy = FTy->getReturnType();
5280 ComputeValueVTs(TLI, RetTy, RetTys);
5281 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5282 SmallVector<SDValue, 4> ReturnValues;
5283 unsigned CurReg = 0;
5284 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5286 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
5287 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
5289 SDValue ReturnValue =
5290 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
5291 RegisterVT, VT, AssertOp);
5292 ReturnValues.push_back(ReturnValue);
5296 setValue(CS.getInstruction(),
5297 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
5298 DAG.getVTList(&RetTys[0], RetTys.size()),
5299 &ReturnValues[0], ReturnValues.size()));
5302 // Assign order to nodes here. If the call does not produce a result, it won't
5303 // be mapped to a SDNode and visit() will not assign it an order number.
5304 if (!Result.second.getNode()) {
5305 // As a special case, a null chain means that a tail call has been emitted and
5306 // the DAG root is already updated.
5309 AssignOrderingToNode(DAG.getRoot().getNode());
5311 DAG.setRoot(Result.second);
5313 AssignOrderingToNode(Result.second.getNode());
5317 // Insert a label at the end of the invoke call to mark the try range. This
5318 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5319 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5320 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
5322 // Inform MachineModuleInfo of range.
5323 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5327 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5328 /// value is equal or not-equal to zero.
5329 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5330 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5332 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5333 if (IC->isEquality())
5334 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5335 if (C->isNullValue())
5337 // Unknown instruction.
5343 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5345 SelectionDAGBuilder &Builder) {
5347 // Check to see if this load can be trivially constant folded, e.g. if the
5348 // input is from a string literal.
5349 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5350 // Cast pointer to the type we really want to load.
5351 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5352 PointerType::getUnqual(LoadTy));
5354 if (const Constant *LoadCst =
5355 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5357 return Builder.getValue(LoadCst);
5360 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5361 // still constant memory, the input chain can be the entry node.
5363 bool ConstantMemory = false;
5365 // Do not serialize (non-volatile) loads of constant memory with anything.
5366 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5367 Root = Builder.DAG.getEntryNode();
5368 ConstantMemory = true;
5370 // Do not serialize non-volatile loads against each other.
5371 Root = Builder.DAG.getRoot();
5374 SDValue Ptr = Builder.getValue(PtrVal);
5375 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
5376 Ptr, MachinePointerInfo(PtrVal),
5378 false /*nontemporal*/,
5379 false /*isinvariant*/, 1 /* align=1 */);
5381 if (!ConstantMemory)
5382 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5387 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5388 /// If so, return true and lower it, otherwise return false and it will be
5389 /// lowered like a normal call.
5390 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5391 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5392 if (I.getNumArgOperands() != 3)
5395 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5396 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5397 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5398 !I.getType()->isIntegerTy())
5401 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
5403 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5404 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5405 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5406 bool ActuallyDoIt = true;
5409 switch (Size->getZExtValue()) {
5411 LoadVT = MVT::Other;
5413 ActuallyDoIt = false;
5417 LoadTy = Type::getInt16Ty(Size->getContext());
5421 LoadTy = Type::getInt32Ty(Size->getContext());
5425 LoadTy = Type::getInt64Ty(Size->getContext());
5429 LoadVT = MVT::v4i32;
5430 LoadTy = Type::getInt32Ty(Size->getContext());
5431 LoadTy = VectorType::get(LoadTy, 4);
5436 // This turns into unaligned loads. We only do this if the target natively
5437 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5438 // we'll only produce a small number of byte loads.
5440 // Require that we can find a legal MVT, and only do this if the target
5441 // supports unaligned loads of that type. Expanding into byte loads would
5443 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5444 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5445 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5446 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5447 ActuallyDoIt = false;
5451 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5452 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5454 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5456 EVT CallVT = TLI.getValueType(I.getType(), true);
5457 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5467 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5468 // Handle inline assembly differently.
5469 if (isa<InlineAsm>(I.getCalledValue())) {
5474 // See if any floating point values are being passed to this function. This is
5475 // used to emit an undefined reference to fltused on Windows.
5477 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
5478 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5479 if (FT->isVarArg() &&
5480 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
5481 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
5482 Type* T = I.getArgOperand(i)->getType();
5483 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
5485 if (!i->isFloatingPointTy()) continue;
5486 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
5492 const char *RenameFn = 0;
5493 if (Function *F = I.getCalledFunction()) {
5494 if (F->isDeclaration()) {
5495 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5496 if (unsigned IID = II->getIntrinsicID(F)) {
5497 RenameFn = visitIntrinsicCall(I, IID);
5502 if (unsigned IID = F->getIntrinsicID()) {
5503 RenameFn = visitIntrinsicCall(I, IID);
5509 // Check for well-known libc/libm calls. If the function is internal, it
5510 // can't be a library call.
5511 if (!F->hasLocalLinkage() && F->hasName()) {
5512 StringRef Name = F->getName();
5513 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
5514 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5515 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5516 I.getType() == I.getArgOperand(0)->getType() &&
5517 I.getType() == I.getArgOperand(1)->getType()) {
5518 SDValue LHS = getValue(I.getArgOperand(0));
5519 SDValue RHS = getValue(I.getArgOperand(1));
5520 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5521 LHS.getValueType(), LHS, RHS));
5524 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5525 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5526 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5527 I.getType() == I.getArgOperand(0)->getType()) {
5528 SDValue Tmp = getValue(I.getArgOperand(0));
5529 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
5530 Tmp.getValueType(), Tmp));
5533 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5534 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5535 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5536 I.getType() == I.getArgOperand(0)->getType() &&
5537 I.onlyReadsMemory()) {
5538 SDValue Tmp = getValue(I.getArgOperand(0));
5539 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5540 Tmp.getValueType(), Tmp));
5543 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5544 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5545 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5546 I.getType() == I.getArgOperand(0)->getType() &&
5547 I.onlyReadsMemory()) {
5548 SDValue Tmp = getValue(I.getArgOperand(0));
5549 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5550 Tmp.getValueType(), Tmp));
5553 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5554 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5555 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5556 I.getType() == I.getArgOperand(0)->getType() &&
5557 I.onlyReadsMemory()) {
5558 SDValue Tmp = getValue(I.getArgOperand(0));
5559 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5560 Tmp.getValueType(), Tmp));
5563 } else if (Name == "memcmp") {
5564 if (visitMemCmpCall(I))
5572 Callee = getValue(I.getCalledValue());
5574 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5576 // Check if we can potentially perform a tail call. More detailed checking is
5577 // be done within LowerCallTo, after more information about the call is known.
5578 LowerCallTo(&I, Callee, I.isTailCall());
5583 /// AsmOperandInfo - This contains information for each constraint that we are
5585 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5587 /// CallOperand - If this is the result output operand or a clobber
5588 /// this is null, otherwise it is the incoming operand to the CallInst.
5589 /// This gets modified as the asm is processed.
5590 SDValue CallOperand;
5592 /// AssignedRegs - If this is a register or register class operand, this
5593 /// contains the set of register corresponding to the operand.
5594 RegsForValue AssignedRegs;
5596 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5597 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5600 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5601 /// busy in OutputRegs/InputRegs.
5602 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5603 std::set<unsigned> &OutputRegs,
5604 std::set<unsigned> &InputRegs,
5605 const TargetRegisterInfo &TRI) const {
5607 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5608 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5611 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5612 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5616 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5617 /// corresponds to. If there is no Value* for this operand, it returns
5619 EVT getCallOperandValEVT(LLVMContext &Context,
5620 const TargetLowering &TLI,
5621 const TargetData *TD) const {
5622 if (CallOperandVal == 0) return MVT::Other;
5624 if (isa<BasicBlock>(CallOperandVal))
5625 return TLI.getPointerTy();
5627 llvm::Type *OpTy = CallOperandVal->getType();
5629 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5630 // If this is an indirect operand, the operand is a pointer to the
5633 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5635 report_fatal_error("Indirect operand for inline asm not a pointer!");
5636 OpTy = PtrTy->getElementType();
5639 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5640 if (StructType *STy = dyn_cast<StructType>(OpTy))
5641 if (STy->getNumElements() == 1)
5642 OpTy = STy->getElementType(0);
5644 // If OpTy is not a single value, it may be a struct/union that we
5645 // can tile with integers.
5646 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5647 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5656 OpTy = IntegerType::get(Context, BitSize);
5661 return TLI.getValueType(OpTy, true);
5665 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5667 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5668 const TargetRegisterInfo &TRI) {
5669 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5671 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5672 for (; *Aliases; ++Aliases)
5673 Regs.insert(*Aliases);
5677 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5679 } // end anonymous namespace
5681 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5682 /// specified operand. We prefer to assign virtual registers, to allow the
5683 /// register allocator to handle the assignment process. However, if the asm
5684 /// uses features that we can't model on machineinstrs, we have SDISel do the
5685 /// allocation. This produces generally horrible, but correct, code.
5687 /// OpInfo describes the operand.
5688 /// Input and OutputRegs are the set of already allocated physical registers.
5690 static void GetRegistersForValue(SelectionDAG &DAG,
5691 const TargetLowering &TLI,
5693 SDISelAsmOperandInfo &OpInfo,
5694 std::set<unsigned> &OutputRegs,
5695 std::set<unsigned> &InputRegs) {
5696 LLVMContext &Context = *DAG.getContext();
5698 // Compute whether this value requires an input register, an output register,
5700 bool isOutReg = false;
5701 bool isInReg = false;
5702 switch (OpInfo.Type) {
5703 case InlineAsm::isOutput:
5706 // If there is an input constraint that matches this, we need to reserve
5707 // the input register so no other inputs allocate to it.
5708 isInReg = OpInfo.hasMatchingInput();
5710 case InlineAsm::isInput:
5714 case InlineAsm::isClobber:
5721 MachineFunction &MF = DAG.getMachineFunction();
5722 SmallVector<unsigned, 4> Regs;
5724 // If this is a constraint for a single physreg, or a constraint for a
5725 // register class, find it.
5726 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5727 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5728 OpInfo.ConstraintVT);
5730 unsigned NumRegs = 1;
5731 if (OpInfo.ConstraintVT != MVT::Other) {
5732 // If this is a FP input in an integer register (or visa versa) insert a bit
5733 // cast of the input value. More generally, handle any case where the input
5734 // value disagrees with the register class we plan to stick this in.
5735 if (OpInfo.Type == InlineAsm::isInput &&
5736 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5737 // Try to convert to the first EVT that the reg class contains. If the
5738 // types are identical size, use a bitcast to convert (e.g. two differing
5740 EVT RegVT = *PhysReg.second->vt_begin();
5741 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5742 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5743 RegVT, OpInfo.CallOperand);
5744 OpInfo.ConstraintVT = RegVT;
5745 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5746 // If the input is a FP value and we want it in FP registers, do a
5747 // bitcast to the corresponding integer type. This turns an f64 value
5748 // into i64, which can be passed with two i32 values on a 32-bit
5750 RegVT = EVT::getIntegerVT(Context,
5751 OpInfo.ConstraintVT.getSizeInBits());
5752 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5753 RegVT, OpInfo.CallOperand);
5754 OpInfo.ConstraintVT = RegVT;
5758 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5762 EVT ValueVT = OpInfo.ConstraintVT;
5764 // If this is a constraint for a specific physical register, like {r17},
5766 if (unsigned AssignedReg = PhysReg.first) {
5767 const TargetRegisterClass *RC = PhysReg.second;
5768 if (OpInfo.ConstraintVT == MVT::Other)
5769 ValueVT = *RC->vt_begin();
5771 // Get the actual register value type. This is important, because the user
5772 // may have asked for (e.g.) the AX register in i32 type. We need to
5773 // remember that AX is actually i16 to get the right extension.
5774 RegVT = *RC->vt_begin();
5776 // This is a explicit reference to a physical register.
5777 Regs.push_back(AssignedReg);
5779 // If this is an expanded reference, add the rest of the regs to Regs.
5781 TargetRegisterClass::iterator I = RC->begin();
5782 for (; *I != AssignedReg; ++I)
5783 assert(I != RC->end() && "Didn't find reg!");
5785 // Already added the first reg.
5787 for (; NumRegs; --NumRegs, ++I) {
5788 assert(I != RC->end() && "Ran out of registers to allocate!");
5793 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5794 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5795 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5799 // Otherwise, if this was a reference to an LLVM register class, create vregs
5800 // for this reference.
5801 if (const TargetRegisterClass *RC = PhysReg.second) {
5802 RegVT = *RC->vt_begin();
5803 if (OpInfo.ConstraintVT == MVT::Other)
5806 // Create the appropriate number of virtual registers.
5807 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5808 for (; NumRegs; --NumRegs)
5809 Regs.push_back(RegInfo.createVirtualRegister(RC));
5811 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5815 // Otherwise, we couldn't allocate enough registers for this.
5818 /// visitInlineAsm - Handle a call to an InlineAsm object.
5820 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5821 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5823 /// ConstraintOperands - Information about all of the constraints.
5824 SDISelAsmOperandInfoVector ConstraintOperands;
5826 std::set<unsigned> OutputRegs, InputRegs;
5828 TargetLowering::AsmOperandInfoVector
5829 TargetConstraints = TLI.ParseConstraints(CS);
5831 bool hasMemory = false;
5833 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5834 unsigned ResNo = 0; // ResNo - The result number of the next output.
5835 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5836 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5837 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5839 EVT OpVT = MVT::Other;
5841 // Compute the value type for each operand.
5842 switch (OpInfo.Type) {
5843 case InlineAsm::isOutput:
5844 // Indirect outputs just consume an argument.
5845 if (OpInfo.isIndirect) {
5846 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5850 // The return value of the call is this value. As such, there is no
5851 // corresponding argument.
5852 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5853 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
5854 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5856 assert(ResNo == 0 && "Asm only has one result!");
5857 OpVT = TLI.getValueType(CS.getType());
5861 case InlineAsm::isInput:
5862 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5864 case InlineAsm::isClobber:
5869 // If this is an input or an indirect output, process the call argument.
5870 // BasicBlocks are labels, currently appearing only in asm's.
5871 if (OpInfo.CallOperandVal) {
5872 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5873 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5875 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5878 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5881 OpInfo.ConstraintVT = OpVT;
5883 // Indirect operand accesses access memory.
5884 if (OpInfo.isIndirect)
5887 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5888 TargetLowering::ConstraintType
5889 CType = TLI.getConstraintType(OpInfo.Codes[j]);
5890 if (CType == TargetLowering::C_Memory) {
5898 SDValue Chain, Flag;
5900 // We won't need to flush pending loads if this asm doesn't touch
5901 // memory and is nonvolatile.
5902 if (hasMemory || IA->hasSideEffects())
5905 Chain = DAG.getRoot();
5907 // Second pass over the constraints: compute which constraint option to use
5908 // and assign registers to constraints that want a specific physreg.
5909 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5910 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5912 // If this is an output operand with a matching input operand, look up the
5913 // matching input. If their types mismatch, e.g. one is an integer, the
5914 // other is floating point, or their sizes are different, flag it as an
5916 if (OpInfo.hasMatchingInput()) {
5917 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5919 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5920 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
5921 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5922 OpInfo.ConstraintVT);
5923 std::pair<unsigned, const TargetRegisterClass*> InputRC =
5924 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
5925 Input.ConstraintVT);
5926 if ((OpInfo.ConstraintVT.isInteger() !=
5927 Input.ConstraintVT.isInteger()) ||
5928 (MatchRC.second != InputRC.second)) {
5929 report_fatal_error("Unsupported asm: input constraint"
5930 " with a matching output constraint of"
5931 " incompatible type!");
5933 Input.ConstraintVT = OpInfo.ConstraintVT;
5937 // Compute the constraint code and ConstraintType to use.
5938 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5940 // If this is a memory input, and if the operand is not indirect, do what we
5941 // need to to provide an address for the memory input.
5942 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5943 !OpInfo.isIndirect) {
5944 assert((OpInfo.isMultipleAlternative ||
5945 (OpInfo.Type == InlineAsm::isInput)) &&
5946 "Can only indirectify direct input operands!");
5948 // Memory operands really want the address of the value. If we don't have
5949 // an indirect input, put it in the constpool if we can, otherwise spill
5950 // it to a stack slot.
5951 // TODO: This isn't quite right. We need to handle these according to
5952 // the addressing mode that the constraint wants. Also, this may take
5953 // an additional register for the computation and we don't want that
5956 // If the operand is a float, integer, or vector constant, spill to a
5957 // constant pool entry to get its address.
5958 const Value *OpVal = OpInfo.CallOperandVal;
5959 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5960 isa<ConstantVector>(OpVal)) {
5961 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5962 TLI.getPointerTy());
5964 // Otherwise, create a stack slot and emit a store to it before the
5966 Type *Ty = OpVal->getType();
5967 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5968 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5969 MachineFunction &MF = DAG.getMachineFunction();
5970 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5971 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5972 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5973 OpInfo.CallOperand, StackSlot,
5974 MachinePointerInfo::getFixedStack(SSFI),
5976 OpInfo.CallOperand = StackSlot;
5979 // There is no longer a Value* corresponding to this operand.
5980 OpInfo.CallOperandVal = 0;
5982 // It is now an indirect operand.
5983 OpInfo.isIndirect = true;
5986 // If this constraint is for a specific register, allocate it before
5988 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5989 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
5993 // Second pass - Loop over all of the operands, assigning virtual or physregs
5994 // to register class operands.
5995 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5996 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5998 // C_Register operands have already been allocated, Other/Memory don't need
6000 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6001 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
6005 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6006 std::vector<SDValue> AsmNodeOperands;
6007 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6008 AsmNodeOperands.push_back(
6009 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6010 TLI.getPointerTy()));
6012 // If we have a !srcloc metadata node associated with it, we want to attach
6013 // this to the ultimately generated inline asm machineinstr. To do this, we
6014 // pass in the third operand as this (potentially null) inline asm MDNode.
6015 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6016 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6018 // Remember the HasSideEffect and AlignStack bits as operand 3.
6019 unsigned ExtraInfo = 0;
6020 if (IA->hasSideEffects())
6021 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6022 if (IA->isAlignStack())
6023 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6024 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6025 TLI.getPointerTy()));
6027 // Loop over all of the inputs, copying the operand values into the
6028 // appropriate registers and processing the output regs.
6029 RegsForValue RetValRegs;
6031 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6032 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6034 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6035 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6037 switch (OpInfo.Type) {
6038 case InlineAsm::isOutput: {
6039 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6040 OpInfo.ConstraintType != TargetLowering::C_Register) {
6041 // Memory output, or 'other' output (e.g. 'X' constraint).
6042 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6044 // Add information to the INLINEASM node to know about this output.
6045 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6046 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6047 TLI.getPointerTy()));
6048 AsmNodeOperands.push_back(OpInfo.CallOperand);
6052 // Otherwise, this is a register or register class output.
6054 // Copy the output from the appropriate register. Find a register that
6056 if (OpInfo.AssignedRegs.Regs.empty())
6057 report_fatal_error("Couldn't allocate output reg for constraint '" +
6058 Twine(OpInfo.ConstraintCode) + "'!");
6060 // If this is an indirect operand, store through the pointer after the
6062 if (OpInfo.isIndirect) {
6063 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6064 OpInfo.CallOperandVal));
6066 // This is the result value of the call.
6067 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6068 // Concatenate this output onto the outputs list.
6069 RetValRegs.append(OpInfo.AssignedRegs);
6072 // Add information to the INLINEASM node to know that this register is
6074 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
6075 InlineAsm::Kind_RegDefEarlyClobber :
6076 InlineAsm::Kind_RegDef,
6083 case InlineAsm::isInput: {
6084 SDValue InOperandVal = OpInfo.CallOperand;
6086 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6087 // If this is required to match an output register we have already set,
6088 // just use its register.
6089 unsigned OperandNo = OpInfo.getMatchedOperand();
6091 // Scan until we find the definition we already emitted of this operand.
6092 // When we find it, create a RegsForValue operand.
6093 unsigned CurOp = InlineAsm::Op_FirstOperand;
6094 for (; OperandNo; --OperandNo) {
6095 // Advance to the next operand.
6097 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6098 assert((InlineAsm::isRegDefKind(OpFlag) ||
6099 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6100 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6101 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6105 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6106 if (InlineAsm::isRegDefKind(OpFlag) ||
6107 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6108 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6109 if (OpInfo.isIndirect) {
6110 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6111 LLVMContext &Ctx = *DAG.getContext();
6112 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6113 " don't know how to handle tied "
6114 "indirect register inputs");
6117 RegsForValue MatchedRegs;
6118 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6119 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
6120 MatchedRegs.RegVTs.push_back(RegVT);
6121 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6122 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6124 MatchedRegs.Regs.push_back
6125 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
6127 // Use the produced MatchedRegs object to
6128 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6130 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6131 true, OpInfo.getMatchedOperand(),
6132 DAG, AsmNodeOperands);
6136 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6137 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6138 "Unexpected number of operands");
6139 // Add information to the INLINEASM node to know about this input.
6140 // See InlineAsm.h isUseOperandTiedToDef.
6141 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6142 OpInfo.getMatchedOperand());
6143 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6144 TLI.getPointerTy()));
6145 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6149 // Treat indirect 'X' constraint as memory.
6150 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6152 OpInfo.ConstraintType = TargetLowering::C_Memory;
6154 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6155 std::vector<SDValue> Ops;
6156 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6159 report_fatal_error("Invalid operand for inline asm constraint '" +
6160 Twine(OpInfo.ConstraintCode) + "'!");
6162 // Add information to the INLINEASM node to know about this input.
6163 unsigned ResOpType =
6164 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6165 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6166 TLI.getPointerTy()));
6167 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6171 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6172 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6173 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6174 "Memory operands expect pointer values");
6176 // Add information to the INLINEASM node to know about this input.
6177 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6178 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6179 TLI.getPointerTy()));
6180 AsmNodeOperands.push_back(InOperandVal);
6184 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6185 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6186 "Unknown constraint type!");
6187 assert(!OpInfo.isIndirect &&
6188 "Don't know how to handle indirect register inputs yet!");
6190 // Copy the input into the appropriate registers.
6191 if (OpInfo.AssignedRegs.Regs.empty())
6192 report_fatal_error("Couldn't allocate input reg for constraint '" +
6193 Twine(OpInfo.ConstraintCode) + "'!");
6195 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6198 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6199 DAG, AsmNodeOperands);
6202 case InlineAsm::isClobber: {
6203 // Add the clobbered value to the operand list, so that the register
6204 // allocator is aware that the physreg got clobbered.
6205 if (!OpInfo.AssignedRegs.Regs.empty())
6206 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6214 // Finish up input operands. Set the input chain and add the flag last.
6215 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6216 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6218 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
6219 DAG.getVTList(MVT::Other, MVT::Glue),
6220 &AsmNodeOperands[0], AsmNodeOperands.size());
6221 Flag = Chain.getValue(1);
6223 // If this asm returns a register value, copy the result from that register
6224 // and set it as the value of the call.
6225 if (!RetValRegs.Regs.empty()) {
6226 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6229 // FIXME: Why don't we do this for inline asms with MRVs?
6230 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6231 EVT ResultType = TLI.getValueType(CS.getType());
6233 // If any of the results of the inline asm is a vector, it may have the
6234 // wrong width/num elts. This can happen for register classes that can
6235 // contain multiple different value types. The preg or vreg allocated may
6236 // not have the same VT as was expected. Convert it to the right type
6237 // with bit_convert.
6238 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6239 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
6242 } else if (ResultType != Val.getValueType() &&
6243 ResultType.isInteger() && Val.getValueType().isInteger()) {
6244 // If a result value was tied to an input value, the computed result may
6245 // have a wider width than the expected result. Extract the relevant
6247 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6250 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6253 setValue(CS.getInstruction(), Val);
6254 // Don't need to use this as a chain in this case.
6255 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6259 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6261 // Process indirect outputs, first output all of the flagged copies out of
6263 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6264 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6265 const Value *Ptr = IndirectStoresToEmit[i].second;
6266 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6268 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6271 // Emit the non-flagged stores from the physregs.
6272 SmallVector<SDValue, 8> OutChains;
6273 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6274 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6275 StoresToEmit[i].first,
6276 getValue(StoresToEmit[i].second),
6277 MachinePointerInfo(StoresToEmit[i].second),
6279 OutChains.push_back(Val);
6282 if (!OutChains.empty())
6283 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6284 &OutChains[0], OutChains.size());
6289 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6290 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6291 MVT::Other, getRoot(),
6292 getValue(I.getArgOperand(0)),
6293 DAG.getSrcValue(I.getArgOperand(0))));
6296 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6297 const TargetData &TD = *TLI.getTargetData();
6298 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6299 getRoot(), getValue(I.getOperand(0)),
6300 DAG.getSrcValue(I.getOperand(0)),
6301 TD.getABITypeAlignment(I.getType()));
6303 DAG.setRoot(V.getValue(1));
6306 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6307 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6308 MVT::Other, getRoot(),
6309 getValue(I.getArgOperand(0)),
6310 DAG.getSrcValue(I.getArgOperand(0))));
6313 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6314 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6315 MVT::Other, getRoot(),
6316 getValue(I.getArgOperand(0)),
6317 getValue(I.getArgOperand(1)),
6318 DAG.getSrcValue(I.getArgOperand(0)),
6319 DAG.getSrcValue(I.getArgOperand(1))));
6322 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6323 /// implementation, which just calls LowerCall.
6324 /// FIXME: When all targets are
6325 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6326 std::pair<SDValue, SDValue>
6327 TargetLowering::LowerCallTo(SDValue Chain, Type *RetTy,
6328 bool RetSExt, bool RetZExt, bool isVarArg,
6329 bool isInreg, unsigned NumFixedArgs,
6330 CallingConv::ID CallConv, bool isTailCall,
6331 bool isReturnValueUsed,
6333 ArgListTy &Args, SelectionDAG &DAG,
6334 DebugLoc dl) const {
6335 // Handle all of the outgoing arguments.
6336 SmallVector<ISD::OutputArg, 32> Outs;
6337 SmallVector<SDValue, 32> OutVals;
6338 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6339 SmallVector<EVT, 4> ValueVTs;
6340 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6341 for (unsigned Value = 0, NumValues = ValueVTs.size();
6342 Value != NumValues; ++Value) {
6343 EVT VT = ValueVTs[Value];
6344 Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6345 SDValue Op = SDValue(Args[i].Node.getNode(),
6346 Args[i].Node.getResNo() + Value);
6347 ISD::ArgFlagsTy Flags;
6348 unsigned OriginalAlignment =
6349 getTargetData()->getABITypeAlignment(ArgTy);
6355 if (Args[i].isInReg)
6359 if (Args[i].isByVal) {
6361 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6362 Type *ElementTy = Ty->getElementType();
6363 Flags.setByValSize(getTargetData()->getTypeAllocSize(ElementTy));
6364 // For ByVal, alignment should come from FE. BE will guess if this
6365 // info is not there but there are cases it cannot get right.
6366 unsigned FrameAlign;
6367 if (Args[i].Alignment)
6368 FrameAlign = Args[i].Alignment;
6370 FrameAlign = getByValTypeAlignment(ElementTy);
6371 Flags.setByValAlign(FrameAlign);
6375 Flags.setOrigAlign(OriginalAlignment);
6377 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6378 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6379 SmallVector<SDValue, 4> Parts(NumParts);
6380 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6383 ExtendKind = ISD::SIGN_EXTEND;
6384 else if (Args[i].isZExt)
6385 ExtendKind = ISD::ZERO_EXTEND;
6387 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
6388 PartVT, ExtendKind);
6390 for (unsigned j = 0; j != NumParts; ++j) {
6391 // if it isn't first piece, alignment must be 1
6392 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
6394 if (NumParts > 1 && j == 0)
6395 MyFlags.Flags.setSplit();
6397 MyFlags.Flags.setOrigAlign(1);
6399 Outs.push_back(MyFlags);
6400 OutVals.push_back(Parts[j]);
6405 // Handle the incoming return values from the call.
6406 SmallVector<ISD::InputArg, 32> Ins;
6407 SmallVector<EVT, 4> RetTys;
6408 ComputeValueVTs(*this, RetTy, RetTys);
6409 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6411 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6412 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6413 for (unsigned i = 0; i != NumRegs; ++i) {
6414 ISD::InputArg MyFlags;
6415 MyFlags.VT = RegisterVT.getSimpleVT();
6416 MyFlags.Used = isReturnValueUsed;
6418 MyFlags.Flags.setSExt();
6420 MyFlags.Flags.setZExt();
6422 MyFlags.Flags.setInReg();
6423 Ins.push_back(MyFlags);
6427 SmallVector<SDValue, 4> InVals;
6428 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6429 Outs, OutVals, Ins, dl, DAG, InVals);
6431 // Verify that the target's LowerCall behaved as expected.
6432 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6433 "LowerCall didn't return a valid chain!");
6434 assert((!isTailCall || InVals.empty()) &&
6435 "LowerCall emitted a return value for a tail call!");
6436 assert((isTailCall || InVals.size() == Ins.size()) &&
6437 "LowerCall didn't emit the correct number of values!");
6439 // For a tail call, the return value is merely live-out and there aren't
6440 // any nodes in the DAG representing it. Return a special value to
6441 // indicate that a tail call has been emitted and no more Instructions
6442 // should be processed in the current block.
6445 return std::make_pair(SDValue(), SDValue());
6448 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6449 assert(InVals[i].getNode() &&
6450 "LowerCall emitted a null value!");
6451 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6452 "LowerCall emitted a value with the wrong type!");
6455 // Collect the legal value parts into potentially illegal values
6456 // that correspond to the original function's return values.
6457 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6459 AssertOp = ISD::AssertSext;
6461 AssertOp = ISD::AssertZext;
6462 SmallVector<SDValue, 4> ReturnValues;
6463 unsigned CurReg = 0;
6464 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6466 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6467 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6469 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
6470 NumRegs, RegisterVT, VT,
6475 // For a function returning void, there is no return value. We can't create
6476 // such a node, so we just return a null return value in that case. In
6477 // that case, nothing will actually look at the value.
6478 if (ReturnValues.empty())
6479 return std::make_pair(SDValue(), Chain);
6481 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6482 DAG.getVTList(&RetTys[0], RetTys.size()),
6483 &ReturnValues[0], ReturnValues.size());
6484 return std::make_pair(Res, Chain);
6487 void TargetLowering::LowerOperationWrapper(SDNode *N,
6488 SmallVectorImpl<SDValue> &Results,
6489 SelectionDAG &DAG) const {
6490 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6492 Results.push_back(Res);
6495 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6496 llvm_unreachable("LowerOperation not implemented for this target!");
6501 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6502 SDValue Op = getNonRegisterValue(V);
6503 assert((Op.getOpcode() != ISD::CopyFromReg ||
6504 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6505 "Copy from a reg to the same reg!");
6506 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6508 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6509 SDValue Chain = DAG.getEntryNode();
6510 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
6511 PendingExports.push_back(Chain);
6514 #include "llvm/CodeGen/SelectionDAGISel.h"
6516 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6517 /// entry block, return true. This includes arguments used by switches, since
6518 /// the switch may expand into multiple basic blocks.
6519 static bool isOnlyUsedInEntryBlock(const Argument *A) {
6520 // With FastISel active, we may be splitting blocks, so force creation
6521 // of virtual registers for all non-dead arguments.
6523 return A->use_empty();
6525 const BasicBlock *Entry = A->getParent()->begin();
6526 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6528 const User *U = *UI;
6529 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6530 return false; // Use not in entry block.
6535 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
6536 // If this is the entry block, emit arguments.
6537 const Function &F = *LLVMBB->getParent();
6538 SelectionDAG &DAG = SDB->DAG;
6539 DebugLoc dl = SDB->getCurDebugLoc();
6540 const TargetData *TD = TLI.getTargetData();
6541 SmallVector<ISD::InputArg, 16> Ins;
6543 // Check whether the function can return without sret-demotion.
6544 SmallVector<ISD::OutputArg, 4> Outs;
6545 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6548 if (!FuncInfo->CanLowerReturn) {
6549 // Put in an sret pointer parameter before all the other parameters.
6550 SmallVector<EVT, 1> ValueVTs;
6551 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6553 // NOTE: Assuming that a pointer will never break down to more than one VT
6555 ISD::ArgFlagsTy Flags;
6557 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
6558 ISD::InputArg RetArg(Flags, RegisterVT, true);
6559 Ins.push_back(RetArg);
6562 // Set up the incoming argument description vector.
6564 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
6565 I != E; ++I, ++Idx) {
6566 SmallVector<EVT, 4> ValueVTs;
6567 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6568 bool isArgValueUsed = !I->use_empty();
6569 for (unsigned Value = 0, NumValues = ValueVTs.size();
6570 Value != NumValues; ++Value) {
6571 EVT VT = ValueVTs[Value];
6572 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6573 ISD::ArgFlagsTy Flags;
6574 unsigned OriginalAlignment =
6575 TD->getABITypeAlignment(ArgTy);
6577 if (F.paramHasAttr(Idx, Attribute::ZExt))
6579 if (F.paramHasAttr(Idx, Attribute::SExt))
6581 if (F.paramHasAttr(Idx, Attribute::InReg))
6583 if (F.paramHasAttr(Idx, Attribute::StructRet))
6585 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6587 PointerType *Ty = cast<PointerType>(I->getType());
6588 Type *ElementTy = Ty->getElementType();
6589 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
6590 // For ByVal, alignment should be passed from FE. BE will guess if
6591 // this info is not there but there are cases it cannot get right.
6592 unsigned FrameAlign;
6593 if (F.getParamAlignment(Idx))
6594 FrameAlign = F.getParamAlignment(Idx);
6596 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6597 Flags.setByValAlign(FrameAlign);
6599 if (F.paramHasAttr(Idx, Attribute::Nest))
6601 Flags.setOrigAlign(OriginalAlignment);
6603 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6604 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6605 for (unsigned i = 0; i != NumRegs; ++i) {
6606 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6607 if (NumRegs > 1 && i == 0)
6608 MyFlags.Flags.setSplit();
6609 // if it isn't first piece, alignment must be 1
6611 MyFlags.Flags.setOrigAlign(1);
6612 Ins.push_back(MyFlags);
6617 // Call the target to set up the argument values.
6618 SmallVector<SDValue, 8> InVals;
6619 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6623 // Verify that the target's LowerFormalArguments behaved as expected.
6624 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6625 "LowerFormalArguments didn't return a valid chain!");
6626 assert(InVals.size() == Ins.size() &&
6627 "LowerFormalArguments didn't emit the correct number of values!");
6629 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6630 assert(InVals[i].getNode() &&
6631 "LowerFormalArguments emitted a null value!");
6632 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6633 "LowerFormalArguments emitted a value with the wrong type!");
6637 // Update the DAG with the new chain value resulting from argument lowering.
6638 DAG.setRoot(NewRoot);
6640 // Set up the argument values.
6643 if (!FuncInfo->CanLowerReturn) {
6644 // Create a virtual register for the sret pointer, and put in a copy
6645 // from the sret argument into it.
6646 SmallVector<EVT, 1> ValueVTs;
6647 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6648 EVT VT = ValueVTs[0];
6649 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6650 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6651 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6652 RegVT, VT, AssertOp);
6654 MachineFunction& MF = SDB->DAG.getMachineFunction();
6655 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6656 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6657 FuncInfo->DemoteRegister = SRetReg;
6658 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6660 DAG.setRoot(NewRoot);
6662 // i indexes lowered arguments. Bump it past the hidden sret argument.
6663 // Idx indexes LLVM arguments. Don't touch it.
6667 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6669 SmallVector<SDValue, 4> ArgValues;
6670 SmallVector<EVT, 4> ValueVTs;
6671 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6672 unsigned NumValues = ValueVTs.size();
6674 // If this argument is unused then remember its value. It is used to generate
6675 // debugging information.
6676 if (I->use_empty() && NumValues)
6677 SDB->setUnusedArgValue(I, InVals[i]);
6679 for (unsigned Val = 0; Val != NumValues; ++Val) {
6680 EVT VT = ValueVTs[Val];
6681 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6682 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6684 if (!I->use_empty()) {
6685 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6686 if (F.paramHasAttr(Idx, Attribute::SExt))
6687 AssertOp = ISD::AssertSext;
6688 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6689 AssertOp = ISD::AssertZext;
6691 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6692 NumParts, PartVT, VT,
6699 // We don't need to do anything else for unused arguments.
6700 if (ArgValues.empty())
6703 // Note down frame index.
6704 if (FrameIndexSDNode *FI =
6705 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
6706 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
6708 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6709 SDB->getCurDebugLoc());
6711 SDB->setValue(I, Res);
6712 if (!EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
6713 if (LoadSDNode *LNode =
6714 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
6715 if (FrameIndexSDNode *FI =
6716 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6717 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
6720 // If this argument is live outside of the entry block, insert a copy from
6721 // wherever we got it to the vreg that other BB's will reference it as.
6722 if (!EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
6723 // If we can, though, try to skip creating an unnecessary vreg.
6724 // FIXME: This isn't very clean... it would be nice to make this more
6725 // general. It's also subtly incompatible with the hacks FastISel
6727 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6728 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6729 FuncInfo->ValueMap[I] = Reg;
6733 if (!isOnlyUsedInEntryBlock(I)) {
6734 FuncInfo->InitializeRegForValue(I);
6735 SDB->CopyToExportRegsIfNeeded(I);
6739 assert(i == InVals.size() && "Argument register count mismatch!");
6741 // Finally, if the target has anything special to do, allow it to do so.
6742 // FIXME: this should insert code into the DAG!
6743 EmitFunctionEntryCode();
6746 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6747 /// ensure constants are generated when needed. Remember the virtual registers
6748 /// that need to be added to the Machine PHI nodes as input. We cannot just
6749 /// directly add them, because expansion might result in multiple MBB's for one
6750 /// BB. As such, the start of the BB might correspond to a different MBB than
6754 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6755 const TerminatorInst *TI = LLVMBB->getTerminator();
6757 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6759 // Check successor nodes' PHI nodes that expect a constant to be available
6761 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6762 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6763 if (!isa<PHINode>(SuccBB->begin())) continue;
6764 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6766 // If this terminator has multiple identical successors (common for
6767 // switches), only handle each succ once.
6768 if (!SuccsHandled.insert(SuccMBB)) continue;
6770 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6772 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6773 // nodes and Machine PHI nodes, but the incoming operands have not been
6775 for (BasicBlock::const_iterator I = SuccBB->begin();
6776 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6777 // Ignore dead phi's.
6778 if (PN->use_empty()) continue;
6781 if (PN->getType()->isEmptyTy())
6785 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6787 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6788 unsigned &RegOut = ConstantsOut[C];
6790 RegOut = FuncInfo.CreateRegs(C->getType());
6791 CopyValueToVirtualRegister(C, RegOut);
6795 DenseMap<const Value *, unsigned>::iterator I =
6796 FuncInfo.ValueMap.find(PHIOp);
6797 if (I != FuncInfo.ValueMap.end())
6800 assert(isa<AllocaInst>(PHIOp) &&
6801 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6802 "Didn't codegen value into a register!??");
6803 Reg = FuncInfo.CreateRegs(PHIOp->getType());
6804 CopyValueToVirtualRegister(PHIOp, Reg);
6808 // Remember that this register needs to added to the machine PHI node as
6809 // the input for this MBB.
6810 SmallVector<EVT, 4> ValueVTs;
6811 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6812 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6813 EVT VT = ValueVTs[vti];
6814 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6815 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6816 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6817 Reg += NumRegisters;
6821 ConstantsOut.clear();