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());
1338 if (TM.Options.NoNaNsFPMath)
1339 Condition = getFCmpCodeWithoutNaN(Condition);
1341 Condition = ISD::SETEQ; // silence warning.
1342 llvm_unreachable("Unknown compare instruction");
1345 CaseBlock CB(Condition, BOp->getOperand(0),
1346 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1347 SwitchCases.push_back(CB);
1352 // Create a CaseBlock record representing this branch.
1353 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1354 NULL, TBB, FBB, CurBB);
1355 SwitchCases.push_back(CB);
1358 /// FindMergedConditions - If Cond is an expression like
1359 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1360 MachineBasicBlock *TBB,
1361 MachineBasicBlock *FBB,
1362 MachineBasicBlock *CurBB,
1363 MachineBasicBlock *SwitchBB,
1365 // If this node is not part of the or/and tree, emit it as a branch.
1366 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1367 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1368 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1369 BOp->getParent() != CurBB->getBasicBlock() ||
1370 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1371 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1372 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1376 // Create TmpBB after CurBB.
1377 MachineFunction::iterator BBI = CurBB;
1378 MachineFunction &MF = DAG.getMachineFunction();
1379 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1380 CurBB->getParent()->insert(++BBI, TmpBB);
1382 if (Opc == Instruction::Or) {
1383 // Codegen X | Y as:
1391 // Emit the LHS condition.
1392 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1394 // Emit the RHS condition into TmpBB.
1395 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1397 assert(Opc == Instruction::And && "Unknown merge op!");
1398 // Codegen X & Y as:
1405 // This requires creation of TmpBB after CurBB.
1407 // Emit the LHS condition.
1408 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1410 // Emit the RHS condition into TmpBB.
1411 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1415 /// If the set of cases should be emitted as a series of branches, return true.
1416 /// If we should emit this as a bunch of and/or'd together conditions, return
1419 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1420 if (Cases.size() != 2) return true;
1422 // If this is two comparisons of the same values or'd or and'd together, they
1423 // will get folded into a single comparison, so don't emit two blocks.
1424 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1425 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1426 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1427 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1431 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1432 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1433 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1434 Cases[0].CC == Cases[1].CC &&
1435 isa<Constant>(Cases[0].CmpRHS) &&
1436 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1437 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1439 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1446 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1447 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1449 // Update machine-CFG edges.
1450 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1452 // Figure out which block is immediately after the current one.
1453 MachineBasicBlock *NextBlock = 0;
1454 MachineFunction::iterator BBI = BrMBB;
1455 if (++BBI != FuncInfo.MF->end())
1458 if (I.isUnconditional()) {
1459 // Update machine-CFG edges.
1460 BrMBB->addSuccessor(Succ0MBB);
1462 // If this is not a fall-through branch, emit the branch.
1463 if (Succ0MBB != NextBlock)
1464 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1465 MVT::Other, getControlRoot(),
1466 DAG.getBasicBlock(Succ0MBB)));
1471 // If this condition is one of the special cases we handle, do special stuff
1473 const Value *CondVal = I.getCondition();
1474 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1476 // If this is a series of conditions that are or'd or and'd together, emit
1477 // this as a sequence of branches instead of setcc's with and/or operations.
1478 // As long as jumps are not expensive, this should improve performance.
1479 // For example, instead of something like:
1492 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1493 if (!TLI.isJumpExpensive() &&
1495 (BOp->getOpcode() == Instruction::And ||
1496 BOp->getOpcode() == Instruction::Or)) {
1497 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1499 // If the compares in later blocks need to use values not currently
1500 // exported from this block, export them now. This block should always
1501 // be the first entry.
1502 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1504 // Allow some cases to be rejected.
1505 if (ShouldEmitAsBranches(SwitchCases)) {
1506 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1507 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1508 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1511 // Emit the branch for this block.
1512 visitSwitchCase(SwitchCases[0], BrMBB);
1513 SwitchCases.erase(SwitchCases.begin());
1517 // Okay, we decided not to do this, remove any inserted MBB's and clear
1519 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1520 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1522 SwitchCases.clear();
1526 // Create a CaseBlock record representing this branch.
1527 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1528 NULL, Succ0MBB, Succ1MBB, BrMBB);
1530 // Use visitSwitchCase to actually insert the fast branch sequence for this
1532 visitSwitchCase(CB, BrMBB);
1535 /// visitSwitchCase - Emits the necessary code to represent a single node in
1536 /// the binary search tree resulting from lowering a switch instruction.
1537 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1538 MachineBasicBlock *SwitchBB) {
1540 SDValue CondLHS = getValue(CB.CmpLHS);
1541 DebugLoc dl = getCurDebugLoc();
1543 // Build the setcc now.
1544 if (CB.CmpMHS == NULL) {
1545 // Fold "(X == true)" to X and "(X == false)" to !X to
1546 // handle common cases produced by branch lowering.
1547 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1548 CB.CC == ISD::SETEQ)
1550 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1551 CB.CC == ISD::SETEQ) {
1552 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1553 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1555 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1557 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1559 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1560 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1562 SDValue CmpOp = getValue(CB.CmpMHS);
1563 EVT VT = CmpOp.getValueType();
1565 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1566 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1569 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1570 VT, CmpOp, DAG.getConstant(Low, VT));
1571 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1572 DAG.getConstant(High-Low, VT), ISD::SETULE);
1576 // Update successor info
1577 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1578 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1580 // Set NextBlock to be the MBB immediately after the current one, if any.
1581 // This is used to avoid emitting unnecessary branches to the next block.
1582 MachineBasicBlock *NextBlock = 0;
1583 MachineFunction::iterator BBI = SwitchBB;
1584 if (++BBI != FuncInfo.MF->end())
1587 // If the lhs block is the next block, invert the condition so that we can
1588 // fall through to the lhs instead of the rhs block.
1589 if (CB.TrueBB == NextBlock) {
1590 std::swap(CB.TrueBB, CB.FalseBB);
1591 SDValue True = DAG.getConstant(1, Cond.getValueType());
1592 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1595 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1596 MVT::Other, getControlRoot(), Cond,
1597 DAG.getBasicBlock(CB.TrueBB));
1599 // Insert the false branch. Do this even if it's a fall through branch,
1600 // this makes it easier to do DAG optimizations which require inverting
1601 // the branch condition.
1602 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1603 DAG.getBasicBlock(CB.FalseBB));
1605 DAG.setRoot(BrCond);
1608 /// visitJumpTable - Emit JumpTable node in the current MBB
1609 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1610 // Emit the code for the jump table
1611 assert(JT.Reg != -1U && "Should lower JT Header first!");
1612 EVT PTy = TLI.getPointerTy();
1613 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1615 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1616 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1617 MVT::Other, Index.getValue(1),
1619 DAG.setRoot(BrJumpTable);
1622 /// visitJumpTableHeader - This function emits necessary code to produce index
1623 /// in the JumpTable from switch case.
1624 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1625 JumpTableHeader &JTH,
1626 MachineBasicBlock *SwitchBB) {
1627 // Subtract the lowest switch case value from the value being switched on and
1628 // conditional branch to default mbb if the result is greater than the
1629 // difference between smallest and largest cases.
1630 SDValue SwitchOp = getValue(JTH.SValue);
1631 EVT VT = SwitchOp.getValueType();
1632 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1633 DAG.getConstant(JTH.First, VT));
1635 // The SDNode we just created, which holds the value being switched on minus
1636 // the smallest case value, needs to be copied to a virtual register so it
1637 // can be used as an index into the jump table in a subsequent basic block.
1638 // This value may be smaller or larger than the target's pointer type, and
1639 // therefore require extension or truncating.
1640 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1642 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1643 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1644 JumpTableReg, SwitchOp);
1645 JT.Reg = JumpTableReg;
1647 // Emit the range check for the jump table, and branch to the default block
1648 // for the switch statement if the value being switched on exceeds the largest
1649 // case in the switch.
1650 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1651 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1652 DAG.getConstant(JTH.Last-JTH.First,VT),
1655 // Set NextBlock to be the MBB immediately after the current one, if any.
1656 // This is used to avoid emitting unnecessary branches to the next block.
1657 MachineBasicBlock *NextBlock = 0;
1658 MachineFunction::iterator BBI = SwitchBB;
1660 if (++BBI != FuncInfo.MF->end())
1663 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1664 MVT::Other, CopyTo, CMP,
1665 DAG.getBasicBlock(JT.Default));
1667 if (JT.MBB != NextBlock)
1668 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1669 DAG.getBasicBlock(JT.MBB));
1671 DAG.setRoot(BrCond);
1674 /// visitBitTestHeader - This function emits necessary code to produce value
1675 /// suitable for "bit tests"
1676 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1677 MachineBasicBlock *SwitchBB) {
1678 // Subtract the minimum value
1679 SDValue SwitchOp = getValue(B.SValue);
1680 EVT VT = SwitchOp.getValueType();
1681 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1682 DAG.getConstant(B.First, VT));
1685 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1686 TLI.getSetCCResultType(Sub.getValueType()),
1687 Sub, DAG.getConstant(B.Range, VT),
1690 // Determine the type of the test operands.
1691 bool UsePtrType = false;
1692 if (!TLI.isTypeLegal(VT))
1695 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1696 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1697 // Switch table case range are encoded into series of masks.
1698 // Just use pointer type, it's guaranteed to fit.
1704 VT = TLI.getPointerTy();
1705 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1709 B.Reg = FuncInfo.CreateReg(VT);
1710 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1713 // Set NextBlock to be the MBB immediately after the current one, if any.
1714 // This is used to avoid emitting unnecessary branches to the next block.
1715 MachineBasicBlock *NextBlock = 0;
1716 MachineFunction::iterator BBI = SwitchBB;
1717 if (++BBI != FuncInfo.MF->end())
1720 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1722 addSuccessorWithWeight(SwitchBB, B.Default);
1723 addSuccessorWithWeight(SwitchBB, MBB);
1725 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1726 MVT::Other, CopyTo, RangeCmp,
1727 DAG.getBasicBlock(B.Default));
1729 if (MBB != NextBlock)
1730 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1731 DAG.getBasicBlock(MBB));
1733 DAG.setRoot(BrRange);
1736 /// visitBitTestCase - this function produces one "bit test"
1737 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1738 MachineBasicBlock* NextMBB,
1741 MachineBasicBlock *SwitchBB) {
1743 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1746 unsigned PopCount = CountPopulation_64(B.Mask);
1747 if (PopCount == 1) {
1748 // Testing for a single bit; just compare the shift count with what it
1749 // would need to be to shift a 1 bit in that position.
1750 Cmp = DAG.getSetCC(getCurDebugLoc(),
1751 TLI.getSetCCResultType(VT),
1753 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
1755 } else if (PopCount == BB.Range) {
1756 // There is only one zero bit in the range, test for it directly.
1757 Cmp = DAG.getSetCC(getCurDebugLoc(),
1758 TLI.getSetCCResultType(VT),
1760 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1763 // Make desired shift
1764 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1765 DAG.getConstant(1, VT), ShiftOp);
1767 // Emit bit tests and jumps
1768 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1769 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1770 Cmp = DAG.getSetCC(getCurDebugLoc(),
1771 TLI.getSetCCResultType(VT),
1772 AndOp, DAG.getConstant(0, VT),
1776 addSuccessorWithWeight(SwitchBB, B.TargetBB);
1777 addSuccessorWithWeight(SwitchBB, NextMBB);
1779 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1780 MVT::Other, getControlRoot(),
1781 Cmp, DAG.getBasicBlock(B.TargetBB));
1783 // Set NextBlock to be the MBB immediately after the current one, if any.
1784 // This is used to avoid emitting unnecessary branches to the next block.
1785 MachineBasicBlock *NextBlock = 0;
1786 MachineFunction::iterator BBI = SwitchBB;
1787 if (++BBI != FuncInfo.MF->end())
1790 if (NextMBB != NextBlock)
1791 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1792 DAG.getBasicBlock(NextMBB));
1797 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1798 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1800 // Retrieve successors.
1801 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1802 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1804 const Value *Callee(I.getCalledValue());
1805 if (isa<InlineAsm>(Callee))
1808 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1810 // If the value of the invoke is used outside of its defining block, make it
1811 // available as a virtual register.
1812 CopyToExportRegsIfNeeded(&I);
1814 // Update successor info
1815 addSuccessorWithWeight(InvokeMBB, Return);
1816 addSuccessorWithWeight(InvokeMBB, LandingPad);
1818 // Drop into normal successor.
1819 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1820 MVT::Other, getControlRoot(),
1821 DAG.getBasicBlock(Return)));
1824 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1827 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1828 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1831 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1832 assert(FuncInfo.MBB->isLandingPad() &&
1833 "Call to landingpad not in landing pad!");
1835 MachineBasicBlock *MBB = FuncInfo.MBB;
1836 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1837 AddLandingPadInfo(LP, MMI, MBB);
1839 SmallVector<EVT, 2> ValueVTs;
1840 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
1842 // Insert the EXCEPTIONADDR instruction.
1843 assert(FuncInfo.MBB->isLandingPad() &&
1844 "Call to eh.exception not in landing pad!");
1845 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1847 Ops[0] = DAG.getRoot();
1848 SDValue Op1 = DAG.getNode(ISD::EXCEPTIONADDR, getCurDebugLoc(), VTs, Ops, 1);
1849 SDValue Chain = Op1.getValue(1);
1851 // Insert the EHSELECTION instruction.
1852 VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1855 SDValue Op2 = DAG.getNode(ISD::EHSELECTION, getCurDebugLoc(), VTs, Ops, 2);
1856 Chain = Op2.getValue(1);
1857 Op2 = DAG.getSExtOrTrunc(Op2, getCurDebugLoc(), MVT::i32);
1861 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
1862 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1865 std::pair<SDValue, SDValue> RetPair = std::make_pair(Res, Chain);
1866 setValue(&LP, RetPair.first);
1867 DAG.setRoot(RetPair.second);
1870 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1871 /// small case ranges).
1872 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1873 CaseRecVector& WorkList,
1875 MachineBasicBlock *Default,
1876 MachineBasicBlock *SwitchBB) {
1877 Case& BackCase = *(CR.Range.second-1);
1879 // Size is the number of Cases represented by this range.
1880 size_t Size = CR.Range.second - CR.Range.first;
1884 // Get the MachineFunction which holds the current MBB. This is used when
1885 // inserting any additional MBBs necessary to represent the switch.
1886 MachineFunction *CurMF = FuncInfo.MF;
1888 // Figure out which block is immediately after the current one.
1889 MachineBasicBlock *NextBlock = 0;
1890 MachineFunction::iterator BBI = CR.CaseBB;
1892 if (++BBI != FuncInfo.MF->end())
1895 // If any two of the cases has the same destination, and if one value
1896 // is the same as the other, but has one bit unset that the other has set,
1897 // use bit manipulation to do two compares at once. For example:
1898 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1899 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1900 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1901 if (Size == 2 && CR.CaseBB == SwitchBB) {
1902 Case &Small = *CR.Range.first;
1903 Case &Big = *(CR.Range.second-1);
1905 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1906 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1907 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1909 // Check that there is only one bit different.
1910 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1911 (SmallValue | BigValue) == BigValue) {
1912 // Isolate the common bit.
1913 APInt CommonBit = BigValue & ~SmallValue;
1914 assert((SmallValue | CommonBit) == BigValue &&
1915 CommonBit.countPopulation() == 1 && "Not a common bit?");
1917 SDValue CondLHS = getValue(SV);
1918 EVT VT = CondLHS.getValueType();
1919 DebugLoc DL = getCurDebugLoc();
1921 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1922 DAG.getConstant(CommonBit, VT));
1923 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1924 Or, DAG.getConstant(BigValue, VT),
1927 // Update successor info.
1928 addSuccessorWithWeight(SwitchBB, Small.BB);
1929 addSuccessorWithWeight(SwitchBB, Default);
1931 // Insert the true branch.
1932 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1933 getControlRoot(), Cond,
1934 DAG.getBasicBlock(Small.BB));
1936 // Insert the false branch.
1937 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
1938 DAG.getBasicBlock(Default));
1940 DAG.setRoot(BrCond);
1946 // Rearrange the case blocks so that the last one falls through if possible.
1947 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1948 // The last case block won't fall through into 'NextBlock' if we emit the
1949 // branches in this order. See if rearranging a case value would help.
1950 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1951 if (I->BB == NextBlock) {
1952 std::swap(*I, BackCase);
1958 // Create a CaseBlock record representing a conditional branch to
1959 // the Case's target mbb if the value being switched on SV is equal
1961 MachineBasicBlock *CurBlock = CR.CaseBB;
1962 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1963 MachineBasicBlock *FallThrough;
1965 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1966 CurMF->insert(BBI, FallThrough);
1968 // Put SV in a virtual register to make it available from the new blocks.
1969 ExportFromCurrentBlock(SV);
1971 // If the last case doesn't match, go to the default block.
1972 FallThrough = Default;
1975 const Value *RHS, *LHS, *MHS;
1977 if (I->High == I->Low) {
1978 // This is just small small case range :) containing exactly 1 case
1980 LHS = SV; RHS = I->High; MHS = NULL;
1983 LHS = I->Low; MHS = SV; RHS = I->High;
1986 uint32_t ExtraWeight = I->ExtraWeight;
1987 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
1989 /* trueweight */ ExtraWeight / 2, /* falseweight */ ExtraWeight / 2);
1991 // If emitting the first comparison, just call visitSwitchCase to emit the
1992 // code into the current block. Otherwise, push the CaseBlock onto the
1993 // vector to be later processed by SDISel, and insert the node's MBB
1994 // before the next MBB.
1995 if (CurBlock == SwitchBB)
1996 visitSwitchCase(CB, SwitchBB);
1998 SwitchCases.push_back(CB);
2000 CurBlock = FallThrough;
2006 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2007 return !TLI.getTargetMachine().Options.DisableJumpTables &&
2008 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2009 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
2012 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2013 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2014 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2015 return (LastExt - FirstExt + 1ULL);
2018 /// handleJTSwitchCase - Emit jumptable for current switch case range
2019 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2020 CaseRecVector &WorkList,
2022 MachineBasicBlock *Default,
2023 MachineBasicBlock *SwitchBB) {
2024 Case& FrontCase = *CR.Range.first;
2025 Case& BackCase = *(CR.Range.second-1);
2027 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2028 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2030 APInt TSize(First.getBitWidth(), 0);
2031 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2034 if (!areJTsAllowed(TLI) || TSize.ult(4))
2037 APInt Range = ComputeRange(First, Last);
2038 // The density is TSize / Range. Require at least 40%.
2039 // It should not be possible for IntTSize to saturate for sane code, but make
2040 // sure we handle Range saturation correctly.
2041 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2042 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2043 if (IntTSize * 10 < IntRange * 4)
2046 DEBUG(dbgs() << "Lowering jump table\n"
2047 << "First entry: " << First << ". Last entry: " << Last << '\n'
2048 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2050 // Get the MachineFunction which holds the current MBB. This is used when
2051 // inserting any additional MBBs necessary to represent the switch.
2052 MachineFunction *CurMF = FuncInfo.MF;
2054 // Figure out which block is immediately after the current one.
2055 MachineFunction::iterator BBI = CR.CaseBB;
2058 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2060 // Create a new basic block to hold the code for loading the address
2061 // of the jump table, and jumping to it. Update successor information;
2062 // we will either branch to the default case for the switch, or the jump
2064 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2065 CurMF->insert(BBI, JumpTableBB);
2067 addSuccessorWithWeight(CR.CaseBB, Default);
2068 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2070 // Build a vector of destination BBs, corresponding to each target
2071 // of the jump table. If the value of the jump table slot corresponds to
2072 // a case statement, push the case's BB onto the vector, otherwise, push
2074 std::vector<MachineBasicBlock*> DestBBs;
2076 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2077 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2078 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2080 if (Low.sle(TEI) && TEI.sle(High)) {
2081 DestBBs.push_back(I->BB);
2085 DestBBs.push_back(Default);
2089 // Update successor info. Add one edge to each unique successor.
2090 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2091 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2092 E = DestBBs.end(); I != E; ++I) {
2093 if (!SuccsHandled[(*I)->getNumber()]) {
2094 SuccsHandled[(*I)->getNumber()] = true;
2095 addSuccessorWithWeight(JumpTableBB, *I);
2099 // Create a jump table index for this jump table.
2100 unsigned JTEncoding = TLI.getJumpTableEncoding();
2101 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2102 ->createJumpTableIndex(DestBBs);
2104 // Set the jump table information so that we can codegen it as a second
2105 // MachineBasicBlock
2106 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2107 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2108 if (CR.CaseBB == SwitchBB)
2109 visitJumpTableHeader(JT, JTH, SwitchBB);
2111 JTCases.push_back(JumpTableBlock(JTH, JT));
2115 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2117 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2118 CaseRecVector& WorkList,
2120 MachineBasicBlock *Default,
2121 MachineBasicBlock *SwitchBB) {
2122 // Get the MachineFunction which holds the current MBB. This is used when
2123 // inserting any additional MBBs necessary to represent the switch.
2124 MachineFunction *CurMF = FuncInfo.MF;
2126 // Figure out which block is immediately after the current one.
2127 MachineFunction::iterator BBI = CR.CaseBB;
2130 Case& FrontCase = *CR.Range.first;
2131 Case& BackCase = *(CR.Range.second-1);
2132 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2134 // Size is the number of Cases represented by this range.
2135 unsigned Size = CR.Range.second - CR.Range.first;
2137 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2138 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2140 CaseItr Pivot = CR.Range.first + Size/2;
2142 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2143 // (heuristically) allow us to emit JumpTable's later.
2144 APInt TSize(First.getBitWidth(), 0);
2145 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2149 APInt LSize = FrontCase.size();
2150 APInt RSize = TSize-LSize;
2151 DEBUG(dbgs() << "Selecting best pivot: \n"
2152 << "First: " << First << ", Last: " << Last <<'\n'
2153 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2154 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2156 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2157 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2158 APInt Range = ComputeRange(LEnd, RBegin);
2159 assert((Range - 2ULL).isNonNegative() &&
2160 "Invalid case distance");
2161 // Use volatile double here to avoid excess precision issues on some hosts,
2162 // e.g. that use 80-bit X87 registers.
2163 volatile double LDensity =
2164 (double)LSize.roundToDouble() /
2165 (LEnd - First + 1ULL).roundToDouble();
2166 volatile double RDensity =
2167 (double)RSize.roundToDouble() /
2168 (Last - RBegin + 1ULL).roundToDouble();
2169 double Metric = Range.logBase2()*(LDensity+RDensity);
2170 // Should always split in some non-trivial place
2171 DEBUG(dbgs() <<"=>Step\n"
2172 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2173 << "LDensity: " << LDensity
2174 << ", RDensity: " << RDensity << '\n'
2175 << "Metric: " << Metric << '\n');
2176 if (FMetric < Metric) {
2179 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2185 if (areJTsAllowed(TLI)) {
2186 // If our case is dense we *really* should handle it earlier!
2187 assert((FMetric > 0) && "Should handle dense range earlier!");
2189 Pivot = CR.Range.first + Size/2;
2192 CaseRange LHSR(CR.Range.first, Pivot);
2193 CaseRange RHSR(Pivot, CR.Range.second);
2194 Constant *C = Pivot->Low;
2195 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2197 // We know that we branch to the LHS if the Value being switched on is
2198 // less than the Pivot value, C. We use this to optimize our binary
2199 // tree a bit, by recognizing that if SV is greater than or equal to the
2200 // LHS's Case Value, and that Case Value is exactly one less than the
2201 // Pivot's Value, then we can branch directly to the LHS's Target,
2202 // rather than creating a leaf node for it.
2203 if ((LHSR.second - LHSR.first) == 1 &&
2204 LHSR.first->High == CR.GE &&
2205 cast<ConstantInt>(C)->getValue() ==
2206 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2207 TrueBB = LHSR.first->BB;
2209 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2210 CurMF->insert(BBI, TrueBB);
2211 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2213 // Put SV in a virtual register to make it available from the new blocks.
2214 ExportFromCurrentBlock(SV);
2217 // Similar to the optimization above, if the Value being switched on is
2218 // known to be less than the Constant CR.LT, and the current Case Value
2219 // is CR.LT - 1, then we can branch directly to the target block for
2220 // the current Case Value, rather than emitting a RHS leaf node for it.
2221 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2222 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2223 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2224 FalseBB = RHSR.first->BB;
2226 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2227 CurMF->insert(BBI, FalseBB);
2228 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2230 // Put SV in a virtual register to make it available from the new blocks.
2231 ExportFromCurrentBlock(SV);
2234 // Create a CaseBlock record representing a conditional branch to
2235 // the LHS node if the value being switched on SV is less than C.
2236 // Otherwise, branch to LHS.
2237 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2239 if (CR.CaseBB == SwitchBB)
2240 visitSwitchCase(CB, SwitchBB);
2242 SwitchCases.push_back(CB);
2247 /// handleBitTestsSwitchCase - if current case range has few destination and
2248 /// range span less, than machine word bitwidth, encode case range into series
2249 /// of masks and emit bit tests with these masks.
2250 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2251 CaseRecVector& WorkList,
2253 MachineBasicBlock* Default,
2254 MachineBasicBlock *SwitchBB){
2255 EVT PTy = TLI.getPointerTy();
2256 unsigned IntPtrBits = PTy.getSizeInBits();
2258 Case& FrontCase = *CR.Range.first;
2259 Case& BackCase = *(CR.Range.second-1);
2261 // Get the MachineFunction which holds the current MBB. This is used when
2262 // inserting any additional MBBs necessary to represent the switch.
2263 MachineFunction *CurMF = FuncInfo.MF;
2265 // If target does not have legal shift left, do not emit bit tests at all.
2266 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2270 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2272 // Single case counts one, case range - two.
2273 numCmps += (I->Low == I->High ? 1 : 2);
2276 // Count unique destinations
2277 SmallSet<MachineBasicBlock*, 4> Dests;
2278 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2279 Dests.insert(I->BB);
2280 if (Dests.size() > 3)
2281 // Don't bother the code below, if there are too much unique destinations
2284 DEBUG(dbgs() << "Total number of unique destinations: "
2285 << Dests.size() << '\n'
2286 << "Total number of comparisons: " << numCmps << '\n');
2288 // Compute span of values.
2289 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2290 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2291 APInt cmpRange = maxValue - minValue;
2293 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2294 << "Low bound: " << minValue << '\n'
2295 << "High bound: " << maxValue << '\n');
2297 if (cmpRange.uge(IntPtrBits) ||
2298 (!(Dests.size() == 1 && numCmps >= 3) &&
2299 !(Dests.size() == 2 && numCmps >= 5) &&
2300 !(Dests.size() >= 3 && numCmps >= 6)))
2303 DEBUG(dbgs() << "Emitting bit tests\n");
2304 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2306 // Optimize the case where all the case values fit in a
2307 // word without having to subtract minValue. In this case,
2308 // we can optimize away the subtraction.
2309 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2310 cmpRange = maxValue;
2312 lowBound = minValue;
2315 CaseBitsVector CasesBits;
2316 unsigned i, count = 0;
2318 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2319 MachineBasicBlock* Dest = I->BB;
2320 for (i = 0; i < count; ++i)
2321 if (Dest == CasesBits[i].BB)
2325 assert((count < 3) && "Too much destinations to test!");
2326 CasesBits.push_back(CaseBits(0, Dest, 0));
2330 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2331 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2333 uint64_t lo = (lowValue - lowBound).getZExtValue();
2334 uint64_t hi = (highValue - lowBound).getZExtValue();
2336 for (uint64_t j = lo; j <= hi; j++) {
2337 CasesBits[i].Mask |= 1ULL << j;
2338 CasesBits[i].Bits++;
2342 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2346 // Figure out which block is immediately after the current one.
2347 MachineFunction::iterator BBI = CR.CaseBB;
2350 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2352 DEBUG(dbgs() << "Cases:\n");
2353 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2354 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2355 << ", Bits: " << CasesBits[i].Bits
2356 << ", BB: " << CasesBits[i].BB << '\n');
2358 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2359 CurMF->insert(BBI, CaseBB);
2360 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2364 // Put SV in a virtual register to make it available from the new blocks.
2365 ExportFromCurrentBlock(SV);
2368 BitTestBlock BTB(lowBound, cmpRange, SV,
2369 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2370 CR.CaseBB, Default, BTC);
2372 if (CR.CaseBB == SwitchBB)
2373 visitBitTestHeader(BTB, SwitchBB);
2375 BitTestCases.push_back(BTB);
2380 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2381 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2382 const SwitchInst& SI) {
2385 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2386 // Start with "simple" cases
2387 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2388 BasicBlock *SuccBB = SI.getSuccessor(i);
2389 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2391 uint32_t ExtraWeight = BPI ? BPI->getEdgeWeight(SI.getParent(), SuccBB) : 0;
2393 Cases.push_back(Case(SI.getSuccessorValue(i),
2394 SI.getSuccessorValue(i),
2395 SMBB, ExtraWeight));
2397 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2399 // Merge case into clusters
2400 if (Cases.size() >= 2)
2401 // Must recompute end() each iteration because it may be
2402 // invalidated by erase if we hold on to it
2403 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2404 J != Cases.end(); ) {
2405 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2406 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2407 MachineBasicBlock* nextBB = J->BB;
2408 MachineBasicBlock* currentBB = I->BB;
2410 // If the two neighboring cases go to the same destination, merge them
2411 // into a single case.
2412 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2416 if (BranchProbabilityInfo *BPI = FuncInfo.BPI) {
2417 uint32_t CurWeight = currentBB->getBasicBlock() ?
2418 BPI->getEdgeWeight(SI.getParent(), currentBB->getBasicBlock()) : 16;
2419 uint32_t NextWeight = nextBB->getBasicBlock() ?
2420 BPI->getEdgeWeight(SI.getParent(), nextBB->getBasicBlock()) : 16;
2422 BPI->setEdgeWeight(SI.getParent(), currentBB->getBasicBlock(),
2423 CurWeight + NextWeight);
2430 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2431 if (I->Low != I->High)
2432 // A range counts double, since it requires two compares.
2439 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2440 MachineBasicBlock *Last) {
2442 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2443 if (JTCases[i].first.HeaderBB == First)
2444 JTCases[i].first.HeaderBB = Last;
2446 // Update BitTestCases.
2447 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2448 if (BitTestCases[i].Parent == First)
2449 BitTestCases[i].Parent = Last;
2452 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2453 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2455 // Figure out which block is immediately after the current one.
2456 MachineBasicBlock *NextBlock = 0;
2457 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2459 // If there is only the default destination, branch to it if it is not the
2460 // next basic block. Otherwise, just fall through.
2461 if (SI.getNumCases() == 1) {
2462 // Update machine-CFG edges.
2464 // If this is not a fall-through branch, emit the branch.
2465 SwitchMBB->addSuccessor(Default);
2466 if (Default != NextBlock)
2467 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2468 MVT::Other, getControlRoot(),
2469 DAG.getBasicBlock(Default)));
2474 // If there are any non-default case statements, create a vector of Cases
2475 // representing each one, and sort the vector so that we can efficiently
2476 // create a binary search tree from them.
2478 size_t numCmps = Clusterify(Cases, SI);
2479 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2480 << ". Total compares: " << numCmps << '\n');
2483 // Get the Value to be switched on and default basic blocks, which will be
2484 // inserted into CaseBlock records, representing basic blocks in the binary
2486 const Value *SV = SI.getCondition();
2488 // Push the initial CaseRec onto the worklist
2489 CaseRecVector WorkList;
2490 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2491 CaseRange(Cases.begin(),Cases.end())));
2493 while (!WorkList.empty()) {
2494 // Grab a record representing a case range to process off the worklist
2495 CaseRec CR = WorkList.back();
2496 WorkList.pop_back();
2498 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2501 // If the range has few cases (two or less) emit a series of specific
2503 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2506 // If the switch has more than 5 blocks, and at least 40% dense, and the
2507 // target supports indirect branches, then emit a jump table rather than
2508 // lowering the switch to a binary tree of conditional branches.
2509 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2512 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2513 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2514 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2518 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2519 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2521 // Update machine-CFG edges with unique successors.
2522 SmallVector<BasicBlock*, 32> succs;
2523 succs.reserve(I.getNumSuccessors());
2524 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2525 succs.push_back(I.getSuccessor(i));
2526 array_pod_sort(succs.begin(), succs.end());
2527 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2528 for (unsigned i = 0, e = succs.size(); i != e; ++i) {
2529 MachineBasicBlock *Succ = FuncInfo.MBBMap[succs[i]];
2530 addSuccessorWithWeight(IndirectBrMBB, Succ);
2533 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2534 MVT::Other, getControlRoot(),
2535 getValue(I.getAddress())));
2538 void SelectionDAGBuilder::visitFSub(const User &I) {
2539 // -0.0 - X --> fneg
2540 Type *Ty = I.getType();
2541 if (isa<Constant>(I.getOperand(0)) &&
2542 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2543 SDValue Op2 = getValue(I.getOperand(1));
2544 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2545 Op2.getValueType(), Op2));
2549 visitBinary(I, ISD::FSUB);
2552 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2553 SDValue Op1 = getValue(I.getOperand(0));
2554 SDValue Op2 = getValue(I.getOperand(1));
2555 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2556 Op1.getValueType(), Op1, Op2));
2559 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2560 SDValue Op1 = getValue(I.getOperand(0));
2561 SDValue Op2 = getValue(I.getOperand(1));
2563 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2565 // Coerce the shift amount to the right type if we can.
2566 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2567 unsigned ShiftSize = ShiftTy.getSizeInBits();
2568 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2569 DebugLoc DL = getCurDebugLoc();
2571 // If the operand is smaller than the shift count type, promote it.
2572 if (ShiftSize > Op2Size)
2573 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2575 // If the operand is larger than the shift count type but the shift
2576 // count type has enough bits to represent any shift value, truncate
2577 // it now. This is a common case and it exposes the truncate to
2578 // optimization early.
2579 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2580 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2581 // Otherwise we'll need to temporarily settle for some other convenient
2582 // type. Type legalization will make adjustments once the shiftee is split.
2584 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2587 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2588 Op1.getValueType(), Op1, Op2));
2591 void SelectionDAGBuilder::visitSDiv(const User &I) {
2592 SDValue Op1 = getValue(I.getOperand(0));
2593 SDValue Op2 = getValue(I.getOperand(1));
2595 // Turn exact SDivs into multiplications.
2596 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2598 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2599 !isa<ConstantSDNode>(Op1) &&
2600 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2601 setValue(&I, TLI.BuildExactSDIV(Op1, Op2, getCurDebugLoc(), DAG));
2603 setValue(&I, DAG.getNode(ISD::SDIV, getCurDebugLoc(), Op1.getValueType(),
2607 void SelectionDAGBuilder::visitICmp(const User &I) {
2608 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2609 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2610 predicate = IC->getPredicate();
2611 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2612 predicate = ICmpInst::Predicate(IC->getPredicate());
2613 SDValue Op1 = getValue(I.getOperand(0));
2614 SDValue Op2 = getValue(I.getOperand(1));
2615 ISD::CondCode Opcode = getICmpCondCode(predicate);
2617 EVT DestVT = TLI.getValueType(I.getType());
2618 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2621 void SelectionDAGBuilder::visitFCmp(const User &I) {
2622 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2623 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2624 predicate = FC->getPredicate();
2625 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2626 predicate = FCmpInst::Predicate(FC->getPredicate());
2627 SDValue Op1 = getValue(I.getOperand(0));
2628 SDValue Op2 = getValue(I.getOperand(1));
2629 ISD::CondCode Condition = getFCmpCondCode(predicate);
2630 if (TM.Options.NoNaNsFPMath)
2631 Condition = getFCmpCodeWithoutNaN(Condition);
2632 EVT DestVT = TLI.getValueType(I.getType());
2633 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2636 void SelectionDAGBuilder::visitSelect(const User &I) {
2637 SmallVector<EVT, 4> ValueVTs;
2638 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2639 unsigned NumValues = ValueVTs.size();
2640 if (NumValues == 0) return;
2642 SmallVector<SDValue, 4> Values(NumValues);
2643 SDValue Cond = getValue(I.getOperand(0));
2644 SDValue TrueVal = getValue(I.getOperand(1));
2645 SDValue FalseVal = getValue(I.getOperand(2));
2646 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2647 ISD::VSELECT : ISD::SELECT;
2649 for (unsigned i = 0; i != NumValues; ++i)
2650 Values[i] = DAG.getNode(OpCode, getCurDebugLoc(),
2651 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2653 SDValue(TrueVal.getNode(),
2654 TrueVal.getResNo() + i),
2655 SDValue(FalseVal.getNode(),
2656 FalseVal.getResNo() + i));
2658 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2659 DAG.getVTList(&ValueVTs[0], NumValues),
2660 &Values[0], NumValues));
2663 void SelectionDAGBuilder::visitTrunc(const User &I) {
2664 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2665 SDValue N = getValue(I.getOperand(0));
2666 EVT DestVT = TLI.getValueType(I.getType());
2667 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2670 void SelectionDAGBuilder::visitZExt(const User &I) {
2671 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2672 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2673 SDValue N = getValue(I.getOperand(0));
2674 EVT DestVT = TLI.getValueType(I.getType());
2675 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2678 void SelectionDAGBuilder::visitSExt(const User &I) {
2679 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2680 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2681 SDValue N = getValue(I.getOperand(0));
2682 EVT DestVT = TLI.getValueType(I.getType());
2683 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2686 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2687 // FPTrunc is never a no-op cast, no need to check
2688 SDValue N = getValue(I.getOperand(0));
2689 EVT DestVT = TLI.getValueType(I.getType());
2690 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2691 DestVT, N, DAG.getIntPtrConstant(0)));
2694 void SelectionDAGBuilder::visitFPExt(const User &I){
2695 // FPExt is never a no-op cast, no need to check
2696 SDValue N = getValue(I.getOperand(0));
2697 EVT DestVT = TLI.getValueType(I.getType());
2698 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2701 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2702 // FPToUI is never a no-op cast, no need to check
2703 SDValue N = getValue(I.getOperand(0));
2704 EVT DestVT = TLI.getValueType(I.getType());
2705 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2708 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2709 // FPToSI is never a no-op cast, no need to check
2710 SDValue N = getValue(I.getOperand(0));
2711 EVT DestVT = TLI.getValueType(I.getType());
2712 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2715 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2716 // UIToFP is never a no-op cast, no need to check
2717 SDValue N = getValue(I.getOperand(0));
2718 EVT DestVT = TLI.getValueType(I.getType());
2719 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2722 void SelectionDAGBuilder::visitSIToFP(const User &I){
2723 // SIToFP is never a no-op cast, no need to check
2724 SDValue N = getValue(I.getOperand(0));
2725 EVT DestVT = TLI.getValueType(I.getType());
2726 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2729 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2730 // What to do depends on the size of the integer and the size of the pointer.
2731 // We can either truncate, zero extend, or no-op, accordingly.
2732 SDValue N = getValue(I.getOperand(0));
2733 EVT DestVT = TLI.getValueType(I.getType());
2734 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2737 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2738 // What to do depends on the size of the integer and the size of the pointer.
2739 // We can either truncate, zero extend, or no-op, accordingly.
2740 SDValue N = getValue(I.getOperand(0));
2741 EVT DestVT = TLI.getValueType(I.getType());
2742 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2745 void SelectionDAGBuilder::visitBitCast(const User &I) {
2746 SDValue N = getValue(I.getOperand(0));
2747 EVT DestVT = TLI.getValueType(I.getType());
2749 // BitCast assures us that source and destination are the same size so this is
2750 // either a BITCAST or a no-op.
2751 if (DestVT != N.getValueType())
2752 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
2753 DestVT, N)); // convert types.
2755 setValue(&I, N); // noop cast.
2758 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2759 SDValue InVec = getValue(I.getOperand(0));
2760 SDValue InVal = getValue(I.getOperand(1));
2761 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2763 getValue(I.getOperand(2)));
2764 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2765 TLI.getValueType(I.getType()),
2766 InVec, InVal, InIdx));
2769 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2770 SDValue InVec = getValue(I.getOperand(0));
2771 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2773 getValue(I.getOperand(1)));
2774 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2775 TLI.getValueType(I.getType()), InVec, InIdx));
2778 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2779 // from SIndx and increasing to the element length (undefs are allowed).
2780 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2781 unsigned MaskNumElts = Mask.size();
2782 for (unsigned i = 0; i != MaskNumElts; ++i)
2783 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2788 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2789 SmallVector<int, 8> Mask;
2790 SDValue Src1 = getValue(I.getOperand(0));
2791 SDValue Src2 = getValue(I.getOperand(1));
2793 // Convert the ConstantVector mask operand into an array of ints, with -1
2794 // representing undef values.
2795 SmallVector<Constant*, 8> MaskElts;
2796 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2797 unsigned MaskNumElts = MaskElts.size();
2798 for (unsigned i = 0; i != MaskNumElts; ++i) {
2799 if (isa<UndefValue>(MaskElts[i]))
2802 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2805 EVT VT = TLI.getValueType(I.getType());
2806 EVT SrcVT = Src1.getValueType();
2807 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2809 if (SrcNumElts == MaskNumElts) {
2810 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2815 // Normalize the shuffle vector since mask and vector length don't match.
2816 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2817 // Mask is longer than the source vectors and is a multiple of the source
2818 // vectors. We can use concatenate vector to make the mask and vectors
2820 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2821 // The shuffle is concatenating two vectors together.
2822 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2827 // Pad both vectors with undefs to make them the same length as the mask.
2828 unsigned NumConcat = MaskNumElts / SrcNumElts;
2829 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2830 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2831 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2833 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2834 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2838 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2839 getCurDebugLoc(), VT,
2840 &MOps1[0], NumConcat);
2841 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2842 getCurDebugLoc(), VT,
2843 &MOps2[0], NumConcat);
2845 // Readjust mask for new input vector length.
2846 SmallVector<int, 8> MappedOps;
2847 for (unsigned i = 0; i != MaskNumElts; ++i) {
2849 if (Idx < (int)SrcNumElts)
2850 MappedOps.push_back(Idx);
2852 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2855 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2860 if (SrcNumElts > MaskNumElts) {
2861 // Analyze the access pattern of the vector to see if we can extract
2862 // two subvectors and do the shuffle. The analysis is done by calculating
2863 // the range of elements the mask access on both vectors.
2864 int MinRange[2] = { static_cast<int>(SrcNumElts+1),
2865 static_cast<int>(SrcNumElts+1)};
2866 int MaxRange[2] = {-1, -1};
2868 for (unsigned i = 0; i != MaskNumElts; ++i) {
2874 if (Idx >= (int)SrcNumElts) {
2878 if (Idx > MaxRange[Input])
2879 MaxRange[Input] = Idx;
2880 if (Idx < MinRange[Input])
2881 MinRange[Input] = Idx;
2884 // Check if the access is smaller than the vector size and can we find
2885 // a reasonable extract index.
2886 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2888 int StartIdx[2]; // StartIdx to extract from
2889 for (int Input=0; Input < 2; ++Input) {
2890 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2891 RangeUse[Input] = 0; // Unused
2892 StartIdx[Input] = 0;
2893 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2894 // Fits within range but we should see if we can find a good
2895 // start index that is a multiple of the mask length.
2896 if (MaxRange[Input] < (int)MaskNumElts) {
2897 RangeUse[Input] = 1; // Extract from beginning of the vector
2898 StartIdx[Input] = 0;
2900 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2901 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2902 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2903 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2908 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2909 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2912 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2913 // Extract appropriate subvector and generate a vector shuffle
2914 for (int Input=0; Input < 2; ++Input) {
2915 SDValue &Src = Input == 0 ? Src1 : Src2;
2916 if (RangeUse[Input] == 0)
2917 Src = DAG.getUNDEF(VT);
2919 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2920 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2923 // Calculate new mask.
2924 SmallVector<int, 8> MappedOps;
2925 for (unsigned i = 0; i != MaskNumElts; ++i) {
2928 MappedOps.push_back(Idx);
2929 else if (Idx < (int)SrcNumElts)
2930 MappedOps.push_back(Idx - StartIdx[0]);
2932 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2935 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2941 // We can't use either concat vectors or extract subvectors so fall back to
2942 // replacing the shuffle with extract and build vector.
2943 // to insert and build vector.
2944 EVT EltVT = VT.getVectorElementType();
2945 EVT PtrVT = TLI.getPointerTy();
2946 SmallVector<SDValue,8> Ops;
2947 for (unsigned i = 0; i != MaskNumElts; ++i) {
2949 Ops.push_back(DAG.getUNDEF(EltVT));
2954 if (Idx < (int)SrcNumElts)
2955 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2956 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2958 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2960 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2966 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2967 VT, &Ops[0], Ops.size()));
2970 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2971 const Value *Op0 = I.getOperand(0);
2972 const Value *Op1 = I.getOperand(1);
2973 Type *AggTy = I.getType();
2974 Type *ValTy = Op1->getType();
2975 bool IntoUndef = isa<UndefValue>(Op0);
2976 bool FromUndef = isa<UndefValue>(Op1);
2978 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2980 SmallVector<EVT, 4> AggValueVTs;
2981 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2982 SmallVector<EVT, 4> ValValueVTs;
2983 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2985 unsigned NumAggValues = AggValueVTs.size();
2986 unsigned NumValValues = ValValueVTs.size();
2987 SmallVector<SDValue, 4> Values(NumAggValues);
2989 SDValue Agg = getValue(Op0);
2991 // Copy the beginning value(s) from the original aggregate.
2992 for (; i != LinearIndex; ++i)
2993 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2994 SDValue(Agg.getNode(), Agg.getResNo() + i);
2995 // Copy values from the inserted value(s).
2997 SDValue Val = getValue(Op1);
2998 for (; i != LinearIndex + NumValValues; ++i)
2999 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3000 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3002 // Copy remaining value(s) from the original aggregate.
3003 for (; i != NumAggValues; ++i)
3004 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3005 SDValue(Agg.getNode(), Agg.getResNo() + i);
3007 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3008 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3009 &Values[0], NumAggValues));
3012 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3013 const Value *Op0 = I.getOperand(0);
3014 Type *AggTy = Op0->getType();
3015 Type *ValTy = I.getType();
3016 bool OutOfUndef = isa<UndefValue>(Op0);
3018 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3020 SmallVector<EVT, 4> ValValueVTs;
3021 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3023 unsigned NumValValues = ValValueVTs.size();
3025 // Ignore a extractvalue that produces an empty object
3026 if (!NumValValues) {
3027 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3031 SmallVector<SDValue, 4> Values(NumValValues);
3033 SDValue Agg = getValue(Op0);
3034 // Copy out the selected value(s).
3035 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3036 Values[i - LinearIndex] =
3038 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3039 SDValue(Agg.getNode(), Agg.getResNo() + i);
3041 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3042 DAG.getVTList(&ValValueVTs[0], NumValValues),
3043 &Values[0], NumValValues));
3046 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3047 SDValue N = getValue(I.getOperand(0));
3048 Type *Ty = I.getOperand(0)->getType();
3050 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3052 const Value *Idx = *OI;
3053 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3054 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3057 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
3058 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
3059 DAG.getIntPtrConstant(Offset));
3062 Ty = StTy->getElementType(Field);
3064 Ty = cast<SequentialType>(Ty)->getElementType();
3066 // If this is a constant subscript, handle it quickly.
3067 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3068 if (CI->isZero()) continue;
3070 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3072 EVT PTy = TLI.getPointerTy();
3073 unsigned PtrBits = PTy.getSizeInBits();
3075 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
3077 DAG.getConstant(Offs, MVT::i64));
3079 OffsVal = DAG.getIntPtrConstant(Offs);
3081 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
3086 // N = N + Idx * ElementSize;
3087 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
3088 TD->getTypeAllocSize(Ty));
3089 SDValue IdxN = getValue(Idx);
3091 // If the index is smaller or larger than intptr_t, truncate or extend
3093 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
3095 // If this is a multiply by a power of two, turn it into a shl
3096 // immediately. This is a very common case.
3097 if (ElementSize != 1) {
3098 if (ElementSize.isPowerOf2()) {
3099 unsigned Amt = ElementSize.logBase2();
3100 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
3101 N.getValueType(), IdxN,
3102 DAG.getConstant(Amt, IdxN.getValueType()));
3104 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
3105 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
3106 N.getValueType(), IdxN, Scale);
3110 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3111 N.getValueType(), N, IdxN);
3118 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3119 // If this is a fixed sized alloca in the entry block of the function,
3120 // allocate it statically on the stack.
3121 if (FuncInfo.StaticAllocaMap.count(&I))
3122 return; // getValue will auto-populate this.
3124 Type *Ty = I.getAllocatedType();
3125 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
3127 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
3130 SDValue AllocSize = getValue(I.getArraySize());
3132 EVT IntPtr = TLI.getPointerTy();
3133 if (AllocSize.getValueType() != IntPtr)
3134 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
3136 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
3138 DAG.getConstant(TySize, IntPtr));
3140 // Handle alignment. If the requested alignment is less than or equal to
3141 // the stack alignment, ignore it. If the size is greater than or equal to
3142 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3143 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3144 if (Align <= StackAlign)
3147 // Round the size of the allocation up to the stack alignment size
3148 // by add SA-1 to the size.
3149 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3150 AllocSize.getValueType(), AllocSize,
3151 DAG.getIntPtrConstant(StackAlign-1));
3153 // Mask out the low bits for alignment purposes.
3154 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
3155 AllocSize.getValueType(), AllocSize,
3156 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3158 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3159 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3160 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
3163 DAG.setRoot(DSA.getValue(1));
3165 // Inform the Frame Information that we have just allocated a variable-sized
3167 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3170 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3172 return visitAtomicLoad(I);
3174 const Value *SV = I.getOperand(0);
3175 SDValue Ptr = getValue(SV);
3177 Type *Ty = I.getType();
3179 bool isVolatile = I.isVolatile();
3180 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3181 bool isInvariant = I.getMetadata("invariant.load") != 0;
3182 unsigned Alignment = I.getAlignment();
3183 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3185 SmallVector<EVT, 4> ValueVTs;
3186 SmallVector<uint64_t, 4> Offsets;
3187 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3188 unsigned NumValues = ValueVTs.size();
3193 bool ConstantMemory = false;
3194 if (I.isVolatile() || NumValues > MaxParallelChains)
3195 // Serialize volatile loads with other side effects.
3197 else if (AA->pointsToConstantMemory(
3198 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3199 // Do not serialize (non-volatile) loads of constant memory with anything.
3200 Root = DAG.getEntryNode();
3201 ConstantMemory = true;
3203 // Do not serialize non-volatile loads against each other.
3204 Root = DAG.getRoot();
3207 SmallVector<SDValue, 4> Values(NumValues);
3208 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3210 EVT PtrVT = Ptr.getValueType();
3211 unsigned ChainI = 0;
3212 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3213 // Serializing loads here may result in excessive register pressure, and
3214 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3215 // could recover a bit by hoisting nodes upward in the chain by recognizing
3216 // they are side-effect free or do not alias. The optimizer should really
3217 // avoid this case by converting large object/array copies to llvm.memcpy
3218 // (MaxParallelChains should always remain as failsafe).
3219 if (ChainI == MaxParallelChains) {
3220 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3221 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3222 MVT::Other, &Chains[0], ChainI);
3226 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3228 DAG.getConstant(Offsets[i], PtrVT));
3229 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3230 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3231 isNonTemporal, isInvariant, Alignment, TBAAInfo);
3234 Chains[ChainI] = L.getValue(1);
3237 if (!ConstantMemory) {
3238 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3239 MVT::Other, &Chains[0], ChainI);
3243 PendingLoads.push_back(Chain);
3246 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3247 DAG.getVTList(&ValueVTs[0], NumValues),
3248 &Values[0], NumValues));
3251 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3253 return visitAtomicStore(I);
3255 const Value *SrcV = I.getOperand(0);
3256 const Value *PtrV = I.getOperand(1);
3258 SmallVector<EVT, 4> ValueVTs;
3259 SmallVector<uint64_t, 4> Offsets;
3260 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3261 unsigned NumValues = ValueVTs.size();
3265 // Get the lowered operands. Note that we do this after
3266 // checking if NumResults is zero, because with zero results
3267 // the operands won't have values in the map.
3268 SDValue Src = getValue(SrcV);
3269 SDValue Ptr = getValue(PtrV);
3271 SDValue Root = getRoot();
3272 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3274 EVT PtrVT = Ptr.getValueType();
3275 bool isVolatile = I.isVolatile();
3276 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3277 unsigned Alignment = I.getAlignment();
3278 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3280 unsigned ChainI = 0;
3281 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3282 // See visitLoad comments.
3283 if (ChainI == MaxParallelChains) {
3284 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3285 MVT::Other, &Chains[0], ChainI);
3289 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3290 DAG.getConstant(Offsets[i], PtrVT));
3291 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3292 SDValue(Src.getNode(), Src.getResNo() + i),
3293 Add, MachinePointerInfo(PtrV, Offsets[i]),
3294 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3295 Chains[ChainI] = St;
3298 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3299 MVT::Other, &Chains[0], ChainI);
3301 AssignOrderingToNode(StoreNode.getNode());
3302 DAG.setRoot(StoreNode);
3305 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
3306 SynchronizationScope Scope,
3307 bool Before, DebugLoc dl,
3309 const TargetLowering &TLI) {
3310 // Fence, if necessary
3312 if (Order == AcquireRelease || Order == SequentiallyConsistent)
3314 else if (Order == Acquire || Order == Monotonic)
3317 if (Order == AcquireRelease)
3319 else if (Order == Release || Order == Monotonic)
3324 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3325 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
3326 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3329 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3330 DebugLoc dl = getCurDebugLoc();
3331 AtomicOrdering Order = I.getOrdering();
3332 SynchronizationScope Scope = I.getSynchScope();
3334 SDValue InChain = getRoot();
3336 if (TLI.getInsertFencesForAtomic())
3337 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3341 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
3342 getValue(I.getCompareOperand()).getValueType().getSimpleVT(),
3344 getValue(I.getPointerOperand()),
3345 getValue(I.getCompareOperand()),
3346 getValue(I.getNewValOperand()),
3347 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
3348 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3351 SDValue OutChain = L.getValue(1);
3353 if (TLI.getInsertFencesForAtomic())
3354 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3358 DAG.setRoot(OutChain);
3361 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3362 DebugLoc dl = getCurDebugLoc();
3364 switch (I.getOperation()) {
3365 default: llvm_unreachable("Unknown atomicrmw operation"); return;
3366 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3367 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3368 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3369 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3370 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3371 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3372 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3373 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3374 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3375 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3376 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3378 AtomicOrdering Order = I.getOrdering();
3379 SynchronizationScope Scope = I.getSynchScope();
3381 SDValue InChain = getRoot();
3383 if (TLI.getInsertFencesForAtomic())
3384 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3388 DAG.getAtomic(NT, dl,
3389 getValue(I.getValOperand()).getValueType().getSimpleVT(),
3391 getValue(I.getPointerOperand()),
3392 getValue(I.getValOperand()),
3393 I.getPointerOperand(), 0 /* Alignment */,
3394 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3397 SDValue OutChain = L.getValue(1);
3399 if (TLI.getInsertFencesForAtomic())
3400 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3404 DAG.setRoot(OutChain);
3407 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3408 DebugLoc dl = getCurDebugLoc();
3411 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3412 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3413 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
3416 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3417 DebugLoc dl = getCurDebugLoc();
3418 AtomicOrdering Order = I.getOrdering();
3419 SynchronizationScope Scope = I.getSynchScope();
3421 SDValue InChain = getRoot();
3423 EVT VT = EVT::getEVT(I.getType());
3425 if (I.getAlignment() * 8 < VT.getSizeInBits())
3426 report_fatal_error("Cannot generate unaligned atomic load");
3429 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3430 getValue(I.getPointerOperand()),
3431 I.getPointerOperand(), I.getAlignment(),
3432 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3435 SDValue OutChain = L.getValue(1);
3437 if (TLI.getInsertFencesForAtomic())
3438 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3442 DAG.setRoot(OutChain);
3445 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3446 DebugLoc dl = getCurDebugLoc();
3448 AtomicOrdering Order = I.getOrdering();
3449 SynchronizationScope Scope = I.getSynchScope();
3451 SDValue InChain = getRoot();
3453 EVT VT = EVT::getEVT(I.getValueOperand()->getType());
3455 if (I.getAlignment() * 8 < VT.getSizeInBits())
3456 report_fatal_error("Cannot generate unaligned atomic store");
3458 if (TLI.getInsertFencesForAtomic())
3459 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3463 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3465 getValue(I.getPointerOperand()),
3466 getValue(I.getValueOperand()),
3467 I.getPointerOperand(), I.getAlignment(),
3468 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3471 if (TLI.getInsertFencesForAtomic())
3472 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3475 DAG.setRoot(OutChain);
3478 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3480 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3481 unsigned Intrinsic) {
3482 bool HasChain = !I.doesNotAccessMemory();
3483 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3485 // Build the operand list.
3486 SmallVector<SDValue, 8> Ops;
3487 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3489 // We don't need to serialize loads against other loads.
3490 Ops.push_back(DAG.getRoot());
3492 Ops.push_back(getRoot());
3496 // Info is set by getTgtMemInstrinsic
3497 TargetLowering::IntrinsicInfo Info;
3498 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3500 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3501 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3502 Info.opc == ISD::INTRINSIC_W_CHAIN)
3503 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3505 // Add all operands of the call to the operand list.
3506 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3507 SDValue Op = getValue(I.getArgOperand(i));
3508 assert(TLI.isTypeLegal(Op.getValueType()) &&
3509 "Intrinsic uses a non-legal type?");
3513 SmallVector<EVT, 4> ValueVTs;
3514 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3516 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3517 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3518 "Intrinsic uses a non-legal type?");
3523 ValueVTs.push_back(MVT::Other);
3525 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3529 if (IsTgtIntrinsic) {
3530 // This is target intrinsic that touches memory
3531 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3532 VTs, &Ops[0], Ops.size(),
3534 MachinePointerInfo(Info.ptrVal, Info.offset),
3535 Info.align, Info.vol,
3536 Info.readMem, Info.writeMem);
3537 } else if (!HasChain) {
3538 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3539 VTs, &Ops[0], Ops.size());
3540 } else if (!I.getType()->isVoidTy()) {
3541 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3542 VTs, &Ops[0], Ops.size());
3544 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3545 VTs, &Ops[0], Ops.size());
3549 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3551 PendingLoads.push_back(Chain);
3556 if (!I.getType()->isVoidTy()) {
3557 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3558 EVT VT = TLI.getValueType(PTy);
3559 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
3562 setValue(&I, Result);
3566 /// GetSignificand - Get the significand and build it into a floating-point
3567 /// number with exponent of 1:
3569 /// Op = (Op & 0x007fffff) | 0x3f800000;
3571 /// where Op is the hexidecimal representation of floating point value.
3573 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3574 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3575 DAG.getConstant(0x007fffff, MVT::i32));
3576 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3577 DAG.getConstant(0x3f800000, MVT::i32));
3578 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3581 /// GetExponent - Get the exponent:
3583 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3585 /// where Op is the hexidecimal representation of floating point value.
3587 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3589 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3590 DAG.getConstant(0x7f800000, MVT::i32));
3591 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3592 DAG.getConstant(23, TLI.getPointerTy()));
3593 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3594 DAG.getConstant(127, MVT::i32));
3595 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3598 /// getF32Constant - Get 32-bit floating point constant.
3600 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3601 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3604 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3606 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3607 SDValue Op1 = getValue(I.getArgOperand(0));
3608 SDValue Op2 = getValue(I.getArgOperand(1));
3610 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3611 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3615 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3616 /// limited-precision mode.
3618 SelectionDAGBuilder::visitExp(const CallInst &I) {
3620 DebugLoc dl = getCurDebugLoc();
3622 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3623 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3624 SDValue Op = getValue(I.getArgOperand(0));
3626 // Put the exponent in the right bit position for later addition to the
3629 // #define LOG2OFe 1.4426950f
3630 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3631 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3632 getF32Constant(DAG, 0x3fb8aa3b));
3633 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3635 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3636 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3637 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3639 // IntegerPartOfX <<= 23;
3640 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3641 DAG.getConstant(23, TLI.getPointerTy()));
3643 if (LimitFloatPrecision <= 6) {
3644 // For floating-point precision of 6:
3646 // TwoToFractionalPartOfX =
3648 // (0.735607626f + 0.252464424f * x) * x;
3650 // error 0.0144103317, which is 6 bits
3651 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3652 getF32Constant(DAG, 0x3e814304));
3653 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3654 getF32Constant(DAG, 0x3f3c50c8));
3655 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3656 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3657 getF32Constant(DAG, 0x3f7f5e7e));
3658 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
3660 // Add the exponent into the result in integer domain.
3661 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3662 TwoToFracPartOfX, IntegerPartOfX);
3664 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
3665 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3666 // For floating-point precision of 12:
3668 // TwoToFractionalPartOfX =
3671 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3673 // 0.000107046256 error, which is 13 to 14 bits
3674 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3675 getF32Constant(DAG, 0x3da235e3));
3676 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3677 getF32Constant(DAG, 0x3e65b8f3));
3678 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3679 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3680 getF32Constant(DAG, 0x3f324b07));
3681 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3682 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3683 getF32Constant(DAG, 0x3f7ff8fd));
3684 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
3686 // Add the exponent into the result in integer domain.
3687 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3688 TwoToFracPartOfX, IntegerPartOfX);
3690 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
3691 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3692 // For floating-point precision of 18:
3694 // TwoToFractionalPartOfX =
3698 // (0.554906021e-1f +
3699 // (0.961591928e-2f +
3700 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3702 // error 2.47208000*10^(-7), which is better than 18 bits
3703 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3704 getF32Constant(DAG, 0x3924b03e));
3705 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3706 getF32Constant(DAG, 0x3ab24b87));
3707 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3708 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3709 getF32Constant(DAG, 0x3c1d8c17));
3710 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3711 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3712 getF32Constant(DAG, 0x3d634a1d));
3713 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3714 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3715 getF32Constant(DAG, 0x3e75fe14));
3716 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3717 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3718 getF32Constant(DAG, 0x3f317234));
3719 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3720 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3721 getF32Constant(DAG, 0x3f800000));
3722 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
3725 // Add the exponent into the result in integer domain.
3726 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3727 TwoToFracPartOfX, IntegerPartOfX);
3729 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
3732 // No special expansion.
3733 result = DAG.getNode(ISD::FEXP, dl,
3734 getValue(I.getArgOperand(0)).getValueType(),
3735 getValue(I.getArgOperand(0)));
3738 setValue(&I, result);
3741 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3742 /// limited-precision mode.
3744 SelectionDAGBuilder::visitLog(const CallInst &I) {
3746 DebugLoc dl = getCurDebugLoc();
3748 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3749 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3750 SDValue Op = getValue(I.getArgOperand(0));
3751 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3753 // Scale the exponent by log(2) [0.69314718f].
3754 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3755 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3756 getF32Constant(DAG, 0x3f317218));
3758 // Get the significand and build it into a floating-point number with
3760 SDValue X = GetSignificand(DAG, Op1, dl);
3762 if (LimitFloatPrecision <= 6) {
3763 // For floating-point precision of 6:
3767 // (1.4034025f - 0.23903021f * x) * x;
3769 // error 0.0034276066, which is better than 8 bits
3770 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3771 getF32Constant(DAG, 0xbe74c456));
3772 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3773 getF32Constant(DAG, 0x3fb3a2b1));
3774 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3775 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3776 getF32Constant(DAG, 0x3f949a29));
3778 result = DAG.getNode(ISD::FADD, dl,
3779 MVT::f32, LogOfExponent, LogOfMantissa);
3780 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3781 // For floating-point precision of 12:
3787 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3789 // error 0.000061011436, which is 14 bits
3790 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3791 getF32Constant(DAG, 0xbd67b6d6));
3792 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3793 getF32Constant(DAG, 0x3ee4f4b8));
3794 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3795 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3796 getF32Constant(DAG, 0x3fbc278b));
3797 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3798 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3799 getF32Constant(DAG, 0x40348e95));
3800 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3801 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3802 getF32Constant(DAG, 0x3fdef31a));
3804 result = DAG.getNode(ISD::FADD, dl,
3805 MVT::f32, LogOfExponent, LogOfMantissa);
3806 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3807 // For floating-point precision of 18:
3815 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3817 // error 0.0000023660568, which is better than 18 bits
3818 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3819 getF32Constant(DAG, 0xbc91e5ac));
3820 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3821 getF32Constant(DAG, 0x3e4350aa));
3822 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3823 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3824 getF32Constant(DAG, 0x3f60d3e3));
3825 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3826 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3827 getF32Constant(DAG, 0x4011cdf0));
3828 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3829 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3830 getF32Constant(DAG, 0x406cfd1c));
3831 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3832 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3833 getF32Constant(DAG, 0x408797cb));
3834 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3835 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3836 getF32Constant(DAG, 0x4006dcab));
3838 result = DAG.getNode(ISD::FADD, dl,
3839 MVT::f32, LogOfExponent, LogOfMantissa);
3842 // No special expansion.
3843 result = DAG.getNode(ISD::FLOG, dl,
3844 getValue(I.getArgOperand(0)).getValueType(),
3845 getValue(I.getArgOperand(0)));
3848 setValue(&I, result);
3851 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3852 /// limited-precision mode.
3854 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3856 DebugLoc dl = getCurDebugLoc();
3858 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3859 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3860 SDValue Op = getValue(I.getArgOperand(0));
3861 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3863 // Get the exponent.
3864 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3866 // Get the significand and build it into a floating-point number with
3868 SDValue X = GetSignificand(DAG, Op1, dl);
3870 // Different possible minimax approximations of significand in
3871 // floating-point for various degrees of accuracy over [1,2].
3872 if (LimitFloatPrecision <= 6) {
3873 // For floating-point precision of 6:
3875 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3877 // error 0.0049451742, which is more than 7 bits
3878 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3879 getF32Constant(DAG, 0xbeb08fe0));
3880 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3881 getF32Constant(DAG, 0x40019463));
3882 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3883 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3884 getF32Constant(DAG, 0x3fd6633d));
3886 result = DAG.getNode(ISD::FADD, dl,
3887 MVT::f32, LogOfExponent, Log2ofMantissa);
3888 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3889 // For floating-point precision of 12:
3895 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3897 // error 0.0000876136000, which is better than 13 bits
3898 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3899 getF32Constant(DAG, 0xbda7262e));
3900 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3901 getF32Constant(DAG, 0x3f25280b));
3902 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3903 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3904 getF32Constant(DAG, 0x4007b923));
3905 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3906 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3907 getF32Constant(DAG, 0x40823e2f));
3908 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3909 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3910 getF32Constant(DAG, 0x4020d29c));
3912 result = DAG.getNode(ISD::FADD, dl,
3913 MVT::f32, LogOfExponent, Log2ofMantissa);
3914 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3915 // For floating-point precision of 18:
3924 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3926 // error 0.0000018516, which is better than 18 bits
3927 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3928 getF32Constant(DAG, 0xbcd2769e));
3929 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3930 getF32Constant(DAG, 0x3e8ce0b9));
3931 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3932 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3933 getF32Constant(DAG, 0x3fa22ae7));
3934 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3935 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3936 getF32Constant(DAG, 0x40525723));
3937 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3938 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3939 getF32Constant(DAG, 0x40aaf200));
3940 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3941 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3942 getF32Constant(DAG, 0x40c39dad));
3943 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3944 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3945 getF32Constant(DAG, 0x4042902c));
3947 result = DAG.getNode(ISD::FADD, dl,
3948 MVT::f32, LogOfExponent, Log2ofMantissa);
3951 // No special expansion.
3952 result = DAG.getNode(ISD::FLOG2, dl,
3953 getValue(I.getArgOperand(0)).getValueType(),
3954 getValue(I.getArgOperand(0)));
3957 setValue(&I, result);
3960 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3961 /// limited-precision mode.
3963 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3965 DebugLoc dl = getCurDebugLoc();
3967 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3968 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3969 SDValue Op = getValue(I.getArgOperand(0));
3970 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3972 // Scale the exponent by log10(2) [0.30102999f].
3973 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3974 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3975 getF32Constant(DAG, 0x3e9a209a));
3977 // Get the significand and build it into a floating-point number with
3979 SDValue X = GetSignificand(DAG, Op1, dl);
3981 if (LimitFloatPrecision <= 6) {
3982 // For floating-point precision of 6:
3984 // Log10ofMantissa =
3986 // (0.60948995f - 0.10380950f * x) * x;
3988 // error 0.0014886165, which is 6 bits
3989 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3990 getF32Constant(DAG, 0xbdd49a13));
3991 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3992 getF32Constant(DAG, 0x3f1c0789));
3993 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3994 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3995 getF32Constant(DAG, 0x3f011300));
3997 result = DAG.getNode(ISD::FADD, dl,
3998 MVT::f32, LogOfExponent, Log10ofMantissa);
3999 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4000 // For floating-point precision of 12:
4002 // Log10ofMantissa =
4005 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4007 // error 0.00019228036, which is better than 12 bits
4008 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4009 getF32Constant(DAG, 0x3d431f31));
4010 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4011 getF32Constant(DAG, 0x3ea21fb2));
4012 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4013 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4014 getF32Constant(DAG, 0x3f6ae232));
4015 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4016 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4017 getF32Constant(DAG, 0x3f25f7c3));
4019 result = DAG.getNode(ISD::FADD, dl,
4020 MVT::f32, LogOfExponent, Log10ofMantissa);
4021 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4022 // For floating-point precision of 18:
4024 // Log10ofMantissa =
4029 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4031 // error 0.0000037995730, which is better than 18 bits
4032 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4033 getF32Constant(DAG, 0x3c5d51ce));
4034 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4035 getF32Constant(DAG, 0x3e00685a));
4036 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4037 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4038 getF32Constant(DAG, 0x3efb6798));
4039 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4040 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4041 getF32Constant(DAG, 0x3f88d192));
4042 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4043 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4044 getF32Constant(DAG, 0x3fc4316c));
4045 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4046 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4047 getF32Constant(DAG, 0x3f57ce70));
4049 result = DAG.getNode(ISD::FADD, dl,
4050 MVT::f32, LogOfExponent, Log10ofMantissa);
4053 // No special expansion.
4054 result = DAG.getNode(ISD::FLOG10, dl,
4055 getValue(I.getArgOperand(0)).getValueType(),
4056 getValue(I.getArgOperand(0)));
4059 setValue(&I, result);
4062 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4063 /// limited-precision mode.
4065 SelectionDAGBuilder::visitExp2(const CallInst &I) {
4067 DebugLoc dl = getCurDebugLoc();
4069 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
4070 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4071 SDValue Op = getValue(I.getArgOperand(0));
4073 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4075 // FractionalPartOfX = x - (float)IntegerPartOfX;
4076 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4077 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4079 // IntegerPartOfX <<= 23;
4080 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4081 DAG.getConstant(23, TLI.getPointerTy()));
4083 if (LimitFloatPrecision <= 6) {
4084 // For floating-point precision of 6:
4086 // TwoToFractionalPartOfX =
4088 // (0.735607626f + 0.252464424f * x) * x;
4090 // error 0.0144103317, which is 6 bits
4091 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4092 getF32Constant(DAG, 0x3e814304));
4093 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4094 getF32Constant(DAG, 0x3f3c50c8));
4095 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4096 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4097 getF32Constant(DAG, 0x3f7f5e7e));
4098 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
4099 SDValue TwoToFractionalPartOfX =
4100 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4102 result = DAG.getNode(ISD::BITCAST, dl,
4103 MVT::f32, TwoToFractionalPartOfX);
4104 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4105 // For floating-point precision of 12:
4107 // TwoToFractionalPartOfX =
4110 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4112 // error 0.000107046256, which is 13 to 14 bits
4113 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4114 getF32Constant(DAG, 0x3da235e3));
4115 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4116 getF32Constant(DAG, 0x3e65b8f3));
4117 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4118 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4119 getF32Constant(DAG, 0x3f324b07));
4120 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4121 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4122 getF32Constant(DAG, 0x3f7ff8fd));
4123 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
4124 SDValue TwoToFractionalPartOfX =
4125 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4127 result = DAG.getNode(ISD::BITCAST, dl,
4128 MVT::f32, TwoToFractionalPartOfX);
4129 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4130 // For floating-point precision of 18:
4132 // TwoToFractionalPartOfX =
4136 // (0.554906021e-1f +
4137 // (0.961591928e-2f +
4138 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4139 // error 2.47208000*10^(-7), which is better than 18 bits
4140 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4141 getF32Constant(DAG, 0x3924b03e));
4142 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4143 getF32Constant(DAG, 0x3ab24b87));
4144 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4145 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4146 getF32Constant(DAG, 0x3c1d8c17));
4147 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4148 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4149 getF32Constant(DAG, 0x3d634a1d));
4150 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4151 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4152 getF32Constant(DAG, 0x3e75fe14));
4153 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4154 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4155 getF32Constant(DAG, 0x3f317234));
4156 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4157 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4158 getF32Constant(DAG, 0x3f800000));
4159 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
4160 SDValue TwoToFractionalPartOfX =
4161 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4163 result = DAG.getNode(ISD::BITCAST, dl,
4164 MVT::f32, TwoToFractionalPartOfX);
4167 // No special expansion.
4168 result = DAG.getNode(ISD::FEXP2, dl,
4169 getValue(I.getArgOperand(0)).getValueType(),
4170 getValue(I.getArgOperand(0)));
4173 setValue(&I, result);
4176 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4177 /// limited-precision mode with x == 10.0f.
4179 SelectionDAGBuilder::visitPow(const CallInst &I) {
4181 const Value *Val = I.getArgOperand(0);
4182 DebugLoc dl = getCurDebugLoc();
4183 bool IsExp10 = false;
4185 if (getValue(Val).getValueType() == MVT::f32 &&
4186 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
4187 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4188 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4189 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4191 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4196 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4197 SDValue Op = getValue(I.getArgOperand(1));
4199 // Put the exponent in the right bit position for later addition to the
4202 // #define LOG2OF10 3.3219281f
4203 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4204 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4205 getF32Constant(DAG, 0x40549a78));
4206 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4208 // FractionalPartOfX = x - (float)IntegerPartOfX;
4209 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4210 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4212 // IntegerPartOfX <<= 23;
4213 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4214 DAG.getConstant(23, TLI.getPointerTy()));
4216 if (LimitFloatPrecision <= 6) {
4217 // For floating-point precision of 6:
4219 // twoToFractionalPartOfX =
4221 // (0.735607626f + 0.252464424f * x) * x;
4223 // error 0.0144103317, which is 6 bits
4224 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4225 getF32Constant(DAG, 0x3e814304));
4226 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4227 getF32Constant(DAG, 0x3f3c50c8));
4228 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4229 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4230 getF32Constant(DAG, 0x3f7f5e7e));
4231 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
4232 SDValue TwoToFractionalPartOfX =
4233 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4235 result = DAG.getNode(ISD::BITCAST, dl,
4236 MVT::f32, TwoToFractionalPartOfX);
4237 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4238 // For floating-point precision of 12:
4240 // TwoToFractionalPartOfX =
4243 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4245 // error 0.000107046256, which is 13 to 14 bits
4246 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4247 getF32Constant(DAG, 0x3da235e3));
4248 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4249 getF32Constant(DAG, 0x3e65b8f3));
4250 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4251 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4252 getF32Constant(DAG, 0x3f324b07));
4253 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4254 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4255 getF32Constant(DAG, 0x3f7ff8fd));
4256 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
4257 SDValue TwoToFractionalPartOfX =
4258 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4260 result = DAG.getNode(ISD::BITCAST, dl,
4261 MVT::f32, TwoToFractionalPartOfX);
4262 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4263 // For floating-point precision of 18:
4265 // TwoToFractionalPartOfX =
4269 // (0.554906021e-1f +
4270 // (0.961591928e-2f +
4271 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4272 // error 2.47208000*10^(-7), which is better than 18 bits
4273 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4274 getF32Constant(DAG, 0x3924b03e));
4275 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4276 getF32Constant(DAG, 0x3ab24b87));
4277 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4278 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4279 getF32Constant(DAG, 0x3c1d8c17));
4280 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4281 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4282 getF32Constant(DAG, 0x3d634a1d));
4283 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4284 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4285 getF32Constant(DAG, 0x3e75fe14));
4286 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4287 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4288 getF32Constant(DAG, 0x3f317234));
4289 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4290 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4291 getF32Constant(DAG, 0x3f800000));
4292 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
4293 SDValue TwoToFractionalPartOfX =
4294 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4296 result = DAG.getNode(ISD::BITCAST, dl,
4297 MVT::f32, TwoToFractionalPartOfX);
4300 // No special expansion.
4301 result = DAG.getNode(ISD::FPOW, dl,
4302 getValue(I.getArgOperand(0)).getValueType(),
4303 getValue(I.getArgOperand(0)),
4304 getValue(I.getArgOperand(1)));
4307 setValue(&I, result);
4311 /// ExpandPowI - Expand a llvm.powi intrinsic.
4312 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4313 SelectionDAG &DAG) {
4314 // If RHS is a constant, we can expand this out to a multiplication tree,
4315 // otherwise we end up lowering to a call to __powidf2 (for example). When
4316 // optimizing for size, we only want to do this if the expansion would produce
4317 // a small number of multiplies, otherwise we do the full expansion.
4318 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4319 // Get the exponent as a positive value.
4320 unsigned Val = RHSC->getSExtValue();
4321 if ((int)Val < 0) Val = -Val;
4323 // powi(x, 0) -> 1.0
4325 return DAG.getConstantFP(1.0, LHS.getValueType());
4327 const Function *F = DAG.getMachineFunction().getFunction();
4328 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
4329 // If optimizing for size, don't insert too many multiplies. This
4330 // inserts up to 5 multiplies.
4331 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4332 // We use the simple binary decomposition method to generate the multiply
4333 // sequence. There are more optimal ways to do this (for example,
4334 // powi(x,15) generates one more multiply than it should), but this has
4335 // the benefit of being both really simple and much better than a libcall.
4336 SDValue Res; // Logically starts equal to 1.0
4337 SDValue CurSquare = LHS;
4341 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4343 Res = CurSquare; // 1.0*CurSquare.
4346 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4347 CurSquare, CurSquare);
4351 // If the original was negative, invert the result, producing 1/(x*x*x).
4352 if (RHSC->getSExtValue() < 0)
4353 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4354 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4359 // Otherwise, expand to a libcall.
4360 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4363 // getTruncatedArgReg - Find underlying register used for an truncated
4365 static unsigned getTruncatedArgReg(const SDValue &N) {
4366 if (N.getOpcode() != ISD::TRUNCATE)
4369 const SDValue &Ext = N.getOperand(0);
4370 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4371 const SDValue &CFR = Ext.getOperand(0);
4372 if (CFR.getOpcode() == ISD::CopyFromReg)
4373 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4375 if (CFR.getOpcode() == ISD::TRUNCATE)
4376 return getTruncatedArgReg(CFR);
4381 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4382 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4383 /// At the end of instruction selection, they will be inserted to the entry BB.
4385 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4388 const Argument *Arg = dyn_cast<Argument>(V);
4392 MachineFunction &MF = DAG.getMachineFunction();
4393 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4394 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4396 // Ignore inlined function arguments here.
4397 DIVariable DV(Variable);
4398 if (DV.isInlinedFnArgument(MF.getFunction()))
4402 // Some arguments' frame index is recorded during argument lowering.
4403 Offset = FuncInfo.getArgumentFrameIndex(Arg);
4405 Reg = TRI->getFrameRegister(MF);
4407 if (!Reg && N.getNode()) {
4408 if (N.getOpcode() == ISD::CopyFromReg)
4409 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4411 Reg = getTruncatedArgReg(N);
4412 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4413 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4414 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4421 // Check if ValueMap has reg number.
4422 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4423 if (VMI != FuncInfo.ValueMap.end())
4427 if (!Reg && N.getNode()) {
4428 // Check if frame index is available.
4429 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4430 if (FrameIndexSDNode *FINode =
4431 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4432 Reg = TRI->getFrameRegister(MF);
4433 Offset = FINode->getIndex();
4440 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4441 TII->get(TargetOpcode::DBG_VALUE))
4442 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
4443 FuncInfo.ArgDbgValues.push_back(&*MIB);
4447 // VisualStudio defines setjmp as _setjmp
4448 #if defined(_MSC_VER) && defined(setjmp) && \
4449 !defined(setjmp_undefined_for_msvc)
4450 # pragma push_macro("setjmp")
4452 # define setjmp_undefined_for_msvc
4455 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4456 /// we want to emit this as a call to a named external function, return the name
4457 /// otherwise lower it and return null.
4459 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4460 DebugLoc dl = getCurDebugLoc();
4463 switch (Intrinsic) {
4465 // By default, turn this into a target intrinsic node.
4466 visitTargetIntrinsic(I, Intrinsic);
4468 case Intrinsic::vastart: visitVAStart(I); return 0;
4469 case Intrinsic::vaend: visitVAEnd(I); return 0;
4470 case Intrinsic::vacopy: visitVACopy(I); return 0;
4471 case Intrinsic::returnaddress:
4472 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4473 getValue(I.getArgOperand(0))));
4475 case Intrinsic::frameaddress:
4476 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4477 getValue(I.getArgOperand(0))));
4479 case Intrinsic::setjmp:
4480 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4481 case Intrinsic::longjmp:
4482 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4483 case Intrinsic::memcpy: {
4484 // Assert for address < 256 since we support only user defined address
4486 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4488 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4490 "Unknown address space");
4491 SDValue Op1 = getValue(I.getArgOperand(0));
4492 SDValue Op2 = getValue(I.getArgOperand(1));
4493 SDValue Op3 = getValue(I.getArgOperand(2));
4494 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4495 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4496 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
4497 MachinePointerInfo(I.getArgOperand(0)),
4498 MachinePointerInfo(I.getArgOperand(1))));
4501 case Intrinsic::memset: {
4502 // Assert for address < 256 since we support only user defined address
4504 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4506 "Unknown address space");
4507 SDValue Op1 = getValue(I.getArgOperand(0));
4508 SDValue Op2 = getValue(I.getArgOperand(1));
4509 SDValue Op3 = getValue(I.getArgOperand(2));
4510 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4511 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4512 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4513 MachinePointerInfo(I.getArgOperand(0))));
4516 case Intrinsic::memmove: {
4517 // Assert for address < 256 since we support only user defined address
4519 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4521 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4523 "Unknown address space");
4524 SDValue Op1 = getValue(I.getArgOperand(0));
4525 SDValue Op2 = getValue(I.getArgOperand(1));
4526 SDValue Op3 = getValue(I.getArgOperand(2));
4527 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4528 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4529 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4530 MachinePointerInfo(I.getArgOperand(0)),
4531 MachinePointerInfo(I.getArgOperand(1))));
4534 case Intrinsic::dbg_declare: {
4535 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4536 MDNode *Variable = DI.getVariable();
4537 const Value *Address = DI.getAddress();
4538 if (!Address || !DIVariable(Variable).Verify())
4541 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4542 // but do not always have a corresponding SDNode built. The SDNodeOrder
4543 // absolute, but not relative, values are different depending on whether
4544 // debug info exists.
4547 // Check if address has undef value.
4548 if (isa<UndefValue>(Address) ||
4549 (Address->use_empty() && !isa<Argument>(Address))) {
4550 DEBUG(dbgs() << "Dropping debug info for " << DI);
4554 SDValue &N = NodeMap[Address];
4555 if (!N.getNode() && isa<Argument>(Address))
4556 // Check unused arguments map.
4557 N = UnusedArgNodeMap[Address];
4560 // Parameters are handled specially.
4562 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
4563 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4564 Address = BCI->getOperand(0);
4565 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4567 if (isParameter && !AI) {
4568 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4570 // Byval parameter. We have a frame index at this point.
4571 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4572 0, dl, SDNodeOrder);
4574 // Address is an argument, so try to emit its dbg value using
4575 // virtual register info from the FuncInfo.ValueMap.
4576 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4580 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4581 0, dl, SDNodeOrder);
4583 // Can't do anything with other non-AI cases yet.
4584 DEBUG(dbgs() << "Dropping debug info for " << DI);
4587 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4589 // If Address is an argument then try to emit its dbg value using
4590 // virtual register info from the FuncInfo.ValueMap.
4591 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4592 // If variable is pinned by a alloca in dominating bb then
4593 // use StaticAllocaMap.
4594 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4595 if (AI->getParent() != DI.getParent()) {
4596 DenseMap<const AllocaInst*, int>::iterator SI =
4597 FuncInfo.StaticAllocaMap.find(AI);
4598 if (SI != FuncInfo.StaticAllocaMap.end()) {
4599 SDV = DAG.getDbgValue(Variable, SI->second,
4600 0, dl, SDNodeOrder);
4601 DAG.AddDbgValue(SDV, 0, false);
4606 DEBUG(dbgs() << "Dropping debug info for " << DI);
4611 case Intrinsic::dbg_value: {
4612 const DbgValueInst &DI = cast<DbgValueInst>(I);
4613 if (!DIVariable(DI.getVariable()).Verify())
4616 MDNode *Variable = DI.getVariable();
4617 uint64_t Offset = DI.getOffset();
4618 const Value *V = DI.getValue();
4622 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4623 // but do not always have a corresponding SDNode built. The SDNodeOrder
4624 // absolute, but not relative, values are different depending on whether
4625 // debug info exists.
4628 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4629 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4630 DAG.AddDbgValue(SDV, 0, false);
4632 // Do not use getValue() in here; we don't want to generate code at
4633 // this point if it hasn't been done yet.
4634 SDValue N = NodeMap[V];
4635 if (!N.getNode() && isa<Argument>(V))
4636 // Check unused arguments map.
4637 N = UnusedArgNodeMap[V];
4639 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4640 SDV = DAG.getDbgValue(Variable, N.getNode(),
4641 N.getResNo(), Offset, dl, SDNodeOrder);
4642 DAG.AddDbgValue(SDV, N.getNode(), false);
4644 } else if (!V->use_empty() ) {
4645 // Do not call getValue(V) yet, as we don't want to generate code.
4646 // Remember it for later.
4647 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4648 DanglingDebugInfoMap[V] = DDI;
4650 // We may expand this to cover more cases. One case where we have no
4651 // data available is an unreferenced parameter.
4652 DEBUG(dbgs() << "Dropping debug info for " << DI);
4656 // Build a debug info table entry.
4657 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4658 V = BCI->getOperand(0);
4659 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4660 // Don't handle byval struct arguments or VLAs, for example.
4663 DenseMap<const AllocaInst*, int>::iterator SI =
4664 FuncInfo.StaticAllocaMap.find(AI);
4665 if (SI == FuncInfo.StaticAllocaMap.end())
4667 int FI = SI->second;
4669 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4670 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4671 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4674 case Intrinsic::eh_exception: {
4675 // Insert the EXCEPTIONADDR instruction.
4676 assert(FuncInfo.MBB->isLandingPad() &&
4677 "Call to eh.exception not in landing pad!");
4678 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4680 Ops[0] = DAG.getRoot();
4681 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4683 DAG.setRoot(Op.getValue(1));
4687 case Intrinsic::eh_selector: {
4688 MachineBasicBlock *CallMBB = FuncInfo.MBB;
4689 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4690 if (CallMBB->isLandingPad())
4691 AddCatchInfo(I, &MMI, CallMBB);
4694 FuncInfo.CatchInfoLost.insert(&I);
4696 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4697 unsigned Reg = TLI.getExceptionSelectorRegister();
4698 if (Reg) FuncInfo.MBB->addLiveIn(Reg);
4701 // Insert the EHSELECTION instruction.
4702 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4704 Ops[0] = getValue(I.getArgOperand(0));
4706 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4707 DAG.setRoot(Op.getValue(1));
4708 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4712 case Intrinsic::eh_typeid_for: {
4713 // Find the type id for the given typeinfo.
4714 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4715 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4716 Res = DAG.getConstant(TypeID, MVT::i32);
4721 case Intrinsic::eh_return_i32:
4722 case Intrinsic::eh_return_i64:
4723 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4724 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4727 getValue(I.getArgOperand(0)),
4728 getValue(I.getArgOperand(1))));
4730 case Intrinsic::eh_unwind_init:
4731 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4733 case Intrinsic::eh_dwarf_cfa: {
4734 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4735 TLI.getPointerTy());
4736 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4738 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4739 TLI.getPointerTy()),
4741 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4743 DAG.getConstant(0, TLI.getPointerTy()));
4744 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4748 case Intrinsic::eh_sjlj_callsite: {
4749 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4750 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4751 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4752 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4754 MMI.setCurrentCallSite(CI->getZExtValue());
4757 case Intrinsic::eh_sjlj_functioncontext: {
4758 // Get and store the index of the function context.
4759 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4761 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4762 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4763 MFI->setFunctionContextIndex(FI);
4766 case Intrinsic::eh_sjlj_setjmp: {
4769 Ops[1] = getValue(I.getArgOperand(0));
4770 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, dl,
4771 DAG.getVTList(MVT::i32, MVT::Other),
4773 setValue(&I, Op.getValue(0));
4774 DAG.setRoot(Op.getValue(1));
4777 case Intrinsic::eh_sjlj_longjmp: {
4778 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4779 getRoot(), getValue(I.getArgOperand(0))));
4783 case Intrinsic::x86_mmx_pslli_w:
4784 case Intrinsic::x86_mmx_pslli_d:
4785 case Intrinsic::x86_mmx_pslli_q:
4786 case Intrinsic::x86_mmx_psrli_w:
4787 case Intrinsic::x86_mmx_psrli_d:
4788 case Intrinsic::x86_mmx_psrli_q:
4789 case Intrinsic::x86_mmx_psrai_w:
4790 case Intrinsic::x86_mmx_psrai_d: {
4791 SDValue ShAmt = getValue(I.getArgOperand(1));
4792 if (isa<ConstantSDNode>(ShAmt)) {
4793 visitTargetIntrinsic(I, Intrinsic);
4796 unsigned NewIntrinsic = 0;
4797 EVT ShAmtVT = MVT::v2i32;
4798 switch (Intrinsic) {
4799 case Intrinsic::x86_mmx_pslli_w:
4800 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4802 case Intrinsic::x86_mmx_pslli_d:
4803 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4805 case Intrinsic::x86_mmx_pslli_q:
4806 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4808 case Intrinsic::x86_mmx_psrli_w:
4809 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4811 case Intrinsic::x86_mmx_psrli_d:
4812 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4814 case Intrinsic::x86_mmx_psrli_q:
4815 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4817 case Intrinsic::x86_mmx_psrai_w:
4818 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4820 case Intrinsic::x86_mmx_psrai_d:
4821 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4823 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4826 // The vector shift intrinsics with scalars uses 32b shift amounts but
4827 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4829 // We must do this early because v2i32 is not a legal type.
4830 DebugLoc dl = getCurDebugLoc();
4833 ShOps[1] = DAG.getConstant(0, MVT::i32);
4834 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4835 EVT DestVT = TLI.getValueType(I.getType());
4836 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
4837 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4838 DAG.getConstant(NewIntrinsic, MVT::i32),
4839 getValue(I.getArgOperand(0)), ShAmt);
4843 case Intrinsic::convertff:
4844 case Intrinsic::convertfsi:
4845 case Intrinsic::convertfui:
4846 case Intrinsic::convertsif:
4847 case Intrinsic::convertuif:
4848 case Intrinsic::convertss:
4849 case Intrinsic::convertsu:
4850 case Intrinsic::convertus:
4851 case Intrinsic::convertuu: {
4852 ISD::CvtCode Code = ISD::CVT_INVALID;
4853 switch (Intrinsic) {
4854 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4855 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4856 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4857 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4858 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4859 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4860 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4861 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4862 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4864 EVT DestVT = TLI.getValueType(I.getType());
4865 const Value *Op1 = I.getArgOperand(0);
4866 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4867 DAG.getValueType(DestVT),
4868 DAG.getValueType(getValue(Op1).getValueType()),
4869 getValue(I.getArgOperand(1)),
4870 getValue(I.getArgOperand(2)),
4875 case Intrinsic::sqrt:
4876 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4877 getValue(I.getArgOperand(0)).getValueType(),
4878 getValue(I.getArgOperand(0))));
4880 case Intrinsic::powi:
4881 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4882 getValue(I.getArgOperand(1)), DAG));
4884 case Intrinsic::sin:
4885 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4886 getValue(I.getArgOperand(0)).getValueType(),
4887 getValue(I.getArgOperand(0))));
4889 case Intrinsic::cos:
4890 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4891 getValue(I.getArgOperand(0)).getValueType(),
4892 getValue(I.getArgOperand(0))));
4894 case Intrinsic::log:
4897 case Intrinsic::log2:
4900 case Intrinsic::log10:
4903 case Intrinsic::exp:
4906 case Intrinsic::exp2:
4909 case Intrinsic::pow:
4912 case Intrinsic::fma:
4913 setValue(&I, DAG.getNode(ISD::FMA, dl,
4914 getValue(I.getArgOperand(0)).getValueType(),
4915 getValue(I.getArgOperand(0)),
4916 getValue(I.getArgOperand(1)),
4917 getValue(I.getArgOperand(2))));
4919 case Intrinsic::convert_to_fp16:
4920 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4921 MVT::i16, getValue(I.getArgOperand(0))));
4923 case Intrinsic::convert_from_fp16:
4924 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4925 MVT::f32, getValue(I.getArgOperand(0))));
4927 case Intrinsic::pcmarker: {
4928 SDValue Tmp = getValue(I.getArgOperand(0));
4929 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4932 case Intrinsic::readcyclecounter: {
4933 SDValue Op = getRoot();
4934 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4935 DAG.getVTList(MVT::i64, MVT::Other),
4938 DAG.setRoot(Res.getValue(1));
4941 case Intrinsic::bswap:
4942 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4943 getValue(I.getArgOperand(0)).getValueType(),
4944 getValue(I.getArgOperand(0))));
4946 case Intrinsic::cttz: {
4947 SDValue Arg = getValue(I.getArgOperand(0));
4948 EVT Ty = Arg.getValueType();
4949 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4952 case Intrinsic::ctlz: {
4953 SDValue Arg = getValue(I.getArgOperand(0));
4954 EVT Ty = Arg.getValueType();
4955 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4958 case Intrinsic::ctpop: {
4959 SDValue Arg = getValue(I.getArgOperand(0));
4960 EVT Ty = Arg.getValueType();
4961 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4964 case Intrinsic::stacksave: {
4965 SDValue Op = getRoot();
4966 Res = DAG.getNode(ISD::STACKSAVE, dl,
4967 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4969 DAG.setRoot(Res.getValue(1));
4972 case Intrinsic::stackrestore: {
4973 Res = getValue(I.getArgOperand(0));
4974 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4977 case Intrinsic::stackprotector: {
4978 // Emit code into the DAG to store the stack guard onto the stack.
4979 MachineFunction &MF = DAG.getMachineFunction();
4980 MachineFrameInfo *MFI = MF.getFrameInfo();
4981 EVT PtrTy = TLI.getPointerTy();
4983 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4984 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4986 int FI = FuncInfo.StaticAllocaMap[Slot];
4987 MFI->setStackProtectorIndex(FI);
4989 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4991 // Store the stack protector onto the stack.
4992 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4993 MachinePointerInfo::getFixedStack(FI),
4999 case Intrinsic::objectsize: {
5000 // If we don't know by now, we're never going to know.
5001 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5003 assert(CI && "Non-constant type in __builtin_object_size?");
5005 SDValue Arg = getValue(I.getCalledValue());
5006 EVT Ty = Arg.getValueType();
5009 Res = DAG.getConstant(-1ULL, Ty);
5011 Res = DAG.getConstant(0, Ty);
5016 case Intrinsic::var_annotation:
5017 // Discard annotate attributes
5020 case Intrinsic::init_trampoline: {
5021 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5025 Ops[1] = getValue(I.getArgOperand(0));
5026 Ops[2] = getValue(I.getArgOperand(1));
5027 Ops[3] = getValue(I.getArgOperand(2));
5028 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5029 Ops[5] = DAG.getSrcValue(F);
5031 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, dl, MVT::Other, Ops, 6);
5036 case Intrinsic::adjust_trampoline: {
5037 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, dl,
5039 getValue(I.getArgOperand(0))));
5042 case Intrinsic::gcroot:
5044 const Value *Alloca = I.getArgOperand(0);
5045 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5047 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5048 GFI->addStackRoot(FI->getIndex(), TypeMap);
5051 case Intrinsic::gcread:
5052 case Intrinsic::gcwrite:
5053 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5055 case Intrinsic::flt_rounds:
5056 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
5059 case Intrinsic::expect: {
5060 // Just replace __builtin_expect(exp, c) with EXP.
5061 setValue(&I, getValue(I.getArgOperand(0)));
5065 case Intrinsic::trap: {
5066 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5067 if (TrapFuncName.empty()) {
5068 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
5071 TargetLowering::ArgListTy Args;
5072 std::pair<SDValue, SDValue> Result =
5073 TLI.LowerCallTo(getRoot(), I.getType(),
5074 false, false, false, false, 0, CallingConv::C,
5075 /*isTailCall=*/false, /*isReturnValueUsed=*/true,
5076 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
5077 Args, DAG, getCurDebugLoc());
5078 DAG.setRoot(Result.second);
5081 case Intrinsic::uadd_with_overflow:
5082 return implVisitAluOverflow(I, ISD::UADDO);
5083 case Intrinsic::sadd_with_overflow:
5084 return implVisitAluOverflow(I, ISD::SADDO);
5085 case Intrinsic::usub_with_overflow:
5086 return implVisitAluOverflow(I, ISD::USUBO);
5087 case Intrinsic::ssub_with_overflow:
5088 return implVisitAluOverflow(I, ISD::SSUBO);
5089 case Intrinsic::umul_with_overflow:
5090 return implVisitAluOverflow(I, ISD::UMULO);
5091 case Intrinsic::smul_with_overflow:
5092 return implVisitAluOverflow(I, ISD::SMULO);
5094 case Intrinsic::prefetch: {
5096 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5098 Ops[1] = getValue(I.getArgOperand(0));
5099 Ops[2] = getValue(I.getArgOperand(1));
5100 Ops[3] = getValue(I.getArgOperand(2));
5101 Ops[4] = getValue(I.getArgOperand(3));
5102 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
5103 DAG.getVTList(MVT::Other),
5105 EVT::getIntegerVT(*Context, 8),
5106 MachinePointerInfo(I.getArgOperand(0)),
5108 false, /* volatile */
5110 rw==1)); /* write */
5114 case Intrinsic::invariant_start:
5115 case Intrinsic::lifetime_start:
5116 // Discard region information.
5117 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
5119 case Intrinsic::invariant_end:
5120 case Intrinsic::lifetime_end:
5121 // Discard region information.
5126 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5128 MachineBasicBlock *LandingPad) {
5129 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5130 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5131 Type *RetTy = FTy->getReturnType();
5132 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5133 MCSymbol *BeginLabel = 0;
5135 TargetLowering::ArgListTy Args;
5136 TargetLowering::ArgListEntry Entry;
5137 Args.reserve(CS.arg_size());
5139 // Check whether the function can return without sret-demotion.
5140 SmallVector<ISD::OutputArg, 4> Outs;
5141 SmallVector<uint64_t, 4> Offsets;
5142 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
5143 Outs, TLI, &Offsets);
5145 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
5146 DAG.getMachineFunction(),
5147 FTy->isVarArg(), Outs,
5150 SDValue DemoteStackSlot;
5151 int DemoteStackIdx = -100;
5153 if (!CanLowerReturn) {
5154 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
5155 FTy->getReturnType());
5156 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
5157 FTy->getReturnType());
5158 MachineFunction &MF = DAG.getMachineFunction();
5159 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5160 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
5162 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
5163 Entry.Node = DemoteStackSlot;
5164 Entry.Ty = StackSlotPtrType;
5165 Entry.isSExt = false;
5166 Entry.isZExt = false;
5167 Entry.isInReg = false;
5168 Entry.isSRet = true;
5169 Entry.isNest = false;
5170 Entry.isByVal = false;
5171 Entry.Alignment = Align;
5172 Args.push_back(Entry);
5173 RetTy = Type::getVoidTy(FTy->getContext());
5176 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5178 const Value *V = *i;
5181 if (V->getType()->isEmptyTy())
5184 SDValue ArgNode = getValue(V);
5185 Entry.Node = ArgNode; Entry.Ty = V->getType();
5187 unsigned attrInd = i - CS.arg_begin() + 1;
5188 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
5189 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
5190 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
5191 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
5192 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
5193 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
5194 Entry.Alignment = CS.getParamAlignment(attrInd);
5195 Args.push_back(Entry);
5199 // Insert a label before the invoke call to mark the try range. This can be
5200 // used to detect deletion of the invoke via the MachineModuleInfo.
5201 BeginLabel = MMI.getContext().CreateTempSymbol();
5203 // For SjLj, keep track of which landing pads go with which invokes
5204 // so as to maintain the ordering of pads in the LSDA.
5205 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5206 if (CallSiteIndex) {
5207 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5208 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5210 // Now that the call site is handled, stop tracking it.
5211 MMI.setCurrentCallSite(0);
5214 // Both PendingLoads and PendingExports must be flushed here;
5215 // this call might not return.
5217 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
5220 // Check if target-independent constraints permit a tail call here.
5221 // Target-dependent constraints are checked within TLI.LowerCallTo.
5223 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
5226 // If there's a possibility that fast-isel has already selected some amount
5227 // of the current basic block, don't emit a tail call.
5228 if (isTailCall && TM.Options.EnableFastISel)
5231 std::pair<SDValue,SDValue> Result =
5232 TLI.LowerCallTo(getRoot(), RetTy,
5233 CS.paramHasAttr(0, Attribute::SExt),
5234 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
5235 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
5236 CS.getCallingConv(),
5238 !CS.getInstruction()->use_empty(),
5239 Callee, Args, DAG, getCurDebugLoc());
5240 assert((isTailCall || Result.second.getNode()) &&
5241 "Non-null chain expected with non-tail call!");
5242 assert((Result.second.getNode() || !Result.first.getNode()) &&
5243 "Null value expected with tail call!");
5244 if (Result.first.getNode()) {
5245 setValue(CS.getInstruction(), Result.first);
5246 } else if (!CanLowerReturn && Result.second.getNode()) {
5247 // The instruction result is the result of loading from the
5248 // hidden sret parameter.
5249 SmallVector<EVT, 1> PVTs;
5250 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5252 ComputeValueVTs(TLI, PtrRetTy, PVTs);
5253 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5254 EVT PtrVT = PVTs[0];
5255 unsigned NumValues = Outs.size();
5256 SmallVector<SDValue, 4> Values(NumValues);
5257 SmallVector<SDValue, 4> Chains(NumValues);
5259 for (unsigned i = 0; i < NumValues; ++i) {
5260 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5262 DAG.getConstant(Offsets[i], PtrVT));
5263 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second,
5265 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5266 false, false, false, 1);
5268 Chains[i] = L.getValue(1);
5271 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5272 MVT::Other, &Chains[0], NumValues);
5273 PendingLoads.push_back(Chain);
5275 // Collect the legal value parts into potentially illegal values
5276 // that correspond to the original function's return values.
5277 SmallVector<EVT, 4> RetTys;
5278 RetTy = FTy->getReturnType();
5279 ComputeValueVTs(TLI, RetTy, RetTys);
5280 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5281 SmallVector<SDValue, 4> ReturnValues;
5282 unsigned CurReg = 0;
5283 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5285 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
5286 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
5288 SDValue ReturnValue =
5289 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
5290 RegisterVT, VT, AssertOp);
5291 ReturnValues.push_back(ReturnValue);
5295 setValue(CS.getInstruction(),
5296 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
5297 DAG.getVTList(&RetTys[0], RetTys.size()),
5298 &ReturnValues[0], ReturnValues.size()));
5301 // Assign order to nodes here. If the call does not produce a result, it won't
5302 // be mapped to a SDNode and visit() will not assign it an order number.
5303 if (!Result.second.getNode()) {
5304 // As a special case, a null chain means that a tail call has been emitted and
5305 // the DAG root is already updated.
5308 AssignOrderingToNode(DAG.getRoot().getNode());
5310 DAG.setRoot(Result.second);
5312 AssignOrderingToNode(Result.second.getNode());
5316 // Insert a label at the end of the invoke call to mark the try range. This
5317 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5318 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5319 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
5321 // Inform MachineModuleInfo of range.
5322 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5326 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5327 /// value is equal or not-equal to zero.
5328 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5329 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5331 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5332 if (IC->isEquality())
5333 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5334 if (C->isNullValue())
5336 // Unknown instruction.
5342 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5344 SelectionDAGBuilder &Builder) {
5346 // Check to see if this load can be trivially constant folded, e.g. if the
5347 // input is from a string literal.
5348 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5349 // Cast pointer to the type we really want to load.
5350 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5351 PointerType::getUnqual(LoadTy));
5353 if (const Constant *LoadCst =
5354 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5356 return Builder.getValue(LoadCst);
5359 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5360 // still constant memory, the input chain can be the entry node.
5362 bool ConstantMemory = false;
5364 // Do not serialize (non-volatile) loads of constant memory with anything.
5365 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5366 Root = Builder.DAG.getEntryNode();
5367 ConstantMemory = true;
5369 // Do not serialize non-volatile loads against each other.
5370 Root = Builder.DAG.getRoot();
5373 SDValue Ptr = Builder.getValue(PtrVal);
5374 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
5375 Ptr, MachinePointerInfo(PtrVal),
5377 false /*nontemporal*/,
5378 false /*isinvariant*/, 1 /* align=1 */);
5380 if (!ConstantMemory)
5381 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5386 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5387 /// If so, return true and lower it, otherwise return false and it will be
5388 /// lowered like a normal call.
5389 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5390 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5391 if (I.getNumArgOperands() != 3)
5394 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5395 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5396 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5397 !I.getType()->isIntegerTy())
5400 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
5402 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5403 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5404 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5405 bool ActuallyDoIt = true;
5408 switch (Size->getZExtValue()) {
5410 LoadVT = MVT::Other;
5412 ActuallyDoIt = false;
5416 LoadTy = Type::getInt16Ty(Size->getContext());
5420 LoadTy = Type::getInt32Ty(Size->getContext());
5424 LoadTy = Type::getInt64Ty(Size->getContext());
5428 LoadVT = MVT::v4i32;
5429 LoadTy = Type::getInt32Ty(Size->getContext());
5430 LoadTy = VectorType::get(LoadTy, 4);
5435 // This turns into unaligned loads. We only do this if the target natively
5436 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5437 // we'll only produce a small number of byte loads.
5439 // Require that we can find a legal MVT, and only do this if the target
5440 // supports unaligned loads of that type. Expanding into byte loads would
5442 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5443 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5444 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5445 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5446 ActuallyDoIt = false;
5450 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5451 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5453 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5455 EVT CallVT = TLI.getValueType(I.getType(), true);
5456 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5466 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5467 // Handle inline assembly differently.
5468 if (isa<InlineAsm>(I.getCalledValue())) {
5473 // See if any floating point values are being passed to this function. This is
5474 // used to emit an undefined reference to fltused on Windows.
5476 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
5477 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5478 if (FT->isVarArg() &&
5479 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
5480 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
5481 Type* T = I.getArgOperand(i)->getType();
5482 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
5484 if (!i->isFloatingPointTy()) continue;
5485 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
5491 const char *RenameFn = 0;
5492 if (Function *F = I.getCalledFunction()) {
5493 if (F->isDeclaration()) {
5494 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5495 if (unsigned IID = II->getIntrinsicID(F)) {
5496 RenameFn = visitIntrinsicCall(I, IID);
5501 if (unsigned IID = F->getIntrinsicID()) {
5502 RenameFn = visitIntrinsicCall(I, IID);
5508 // Check for well-known libc/libm calls. If the function is internal, it
5509 // can't be a library call.
5510 if (!F->hasLocalLinkage() && F->hasName()) {
5511 StringRef Name = F->getName();
5512 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
5513 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5514 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5515 I.getType() == I.getArgOperand(0)->getType() &&
5516 I.getType() == I.getArgOperand(1)->getType()) {
5517 SDValue LHS = getValue(I.getArgOperand(0));
5518 SDValue RHS = getValue(I.getArgOperand(1));
5519 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5520 LHS.getValueType(), LHS, RHS));
5523 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5524 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5525 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5526 I.getType() == I.getArgOperand(0)->getType()) {
5527 SDValue Tmp = getValue(I.getArgOperand(0));
5528 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
5529 Tmp.getValueType(), Tmp));
5532 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5533 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5534 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5535 I.getType() == I.getArgOperand(0)->getType() &&
5536 I.onlyReadsMemory()) {
5537 SDValue Tmp = getValue(I.getArgOperand(0));
5538 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5539 Tmp.getValueType(), Tmp));
5542 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5543 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5544 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5545 I.getType() == I.getArgOperand(0)->getType() &&
5546 I.onlyReadsMemory()) {
5547 SDValue Tmp = getValue(I.getArgOperand(0));
5548 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5549 Tmp.getValueType(), Tmp));
5552 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5553 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5554 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5555 I.getType() == I.getArgOperand(0)->getType() &&
5556 I.onlyReadsMemory()) {
5557 SDValue Tmp = getValue(I.getArgOperand(0));
5558 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5559 Tmp.getValueType(), Tmp));
5562 } else if (Name == "floor" || Name == "floorf" || Name == "floorl") {
5563 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5564 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5565 I.getType() == I.getArgOperand(0)->getType()) {
5566 SDValue Tmp = getValue(I.getArgOperand(0));
5567 setValue(&I, DAG.getNode(ISD::FFLOOR, getCurDebugLoc(),
5568 Tmp.getValueType(), Tmp));
5571 } else if (Name == "nearbyint" || Name == "nearbyintf" ||
5572 Name == "nearbyintl") {
5573 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5574 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5575 I.getType() == I.getArgOperand(0)->getType()) {
5576 SDValue Tmp = getValue(I.getArgOperand(0));
5577 setValue(&I, DAG.getNode(ISD::FNEARBYINT, getCurDebugLoc(),
5578 Tmp.getValueType(), Tmp));
5581 } else if (Name == "ceil" || Name == "ceilf" || Name == "ceill") {
5582 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5583 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5584 I.getType() == I.getArgOperand(0)->getType()) {
5585 SDValue Tmp = getValue(I.getArgOperand(0));
5586 setValue(&I, DAG.getNode(ISD::FCEIL, getCurDebugLoc(),
5587 Tmp.getValueType(), Tmp));
5590 } else if (Name == "rint" || Name == "rintf" || Name == "rintl") {
5591 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5592 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5593 I.getType() == I.getArgOperand(0)->getType()) {
5594 SDValue Tmp = getValue(I.getArgOperand(0));
5595 setValue(&I, DAG.getNode(ISD::FRINT, getCurDebugLoc(),
5596 Tmp.getValueType(), Tmp));
5599 } else if (Name == "trunc" || Name == "truncf" || Name == "truncl") {
5600 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5601 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5602 I.getType() == I.getArgOperand(0)->getType()) {
5603 SDValue Tmp = getValue(I.getArgOperand(0));
5604 setValue(&I, DAG.getNode(ISD::FTRUNC, getCurDebugLoc(),
5605 Tmp.getValueType(), Tmp));
5609 } else if (Name == "memcmp") {
5610 if (visitMemCmpCall(I))
5618 Callee = getValue(I.getCalledValue());
5620 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5622 // Check if we can potentially perform a tail call. More detailed checking is
5623 // be done within LowerCallTo, after more information about the call is known.
5624 LowerCallTo(&I, Callee, I.isTailCall());
5629 /// AsmOperandInfo - This contains information for each constraint that we are
5631 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5633 /// CallOperand - If this is the result output operand or a clobber
5634 /// this is null, otherwise it is the incoming operand to the CallInst.
5635 /// This gets modified as the asm is processed.
5636 SDValue CallOperand;
5638 /// AssignedRegs - If this is a register or register class operand, this
5639 /// contains the set of register corresponding to the operand.
5640 RegsForValue AssignedRegs;
5642 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5643 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5646 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5647 /// busy in OutputRegs/InputRegs.
5648 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5649 std::set<unsigned> &OutputRegs,
5650 std::set<unsigned> &InputRegs,
5651 const TargetRegisterInfo &TRI) const {
5653 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5654 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5657 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5658 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5662 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5663 /// corresponds to. If there is no Value* for this operand, it returns
5665 EVT getCallOperandValEVT(LLVMContext &Context,
5666 const TargetLowering &TLI,
5667 const TargetData *TD) const {
5668 if (CallOperandVal == 0) return MVT::Other;
5670 if (isa<BasicBlock>(CallOperandVal))
5671 return TLI.getPointerTy();
5673 llvm::Type *OpTy = CallOperandVal->getType();
5675 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5676 // If this is an indirect operand, the operand is a pointer to the
5679 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5681 report_fatal_error("Indirect operand for inline asm not a pointer!");
5682 OpTy = PtrTy->getElementType();
5685 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5686 if (StructType *STy = dyn_cast<StructType>(OpTy))
5687 if (STy->getNumElements() == 1)
5688 OpTy = STy->getElementType(0);
5690 // If OpTy is not a single value, it may be a struct/union that we
5691 // can tile with integers.
5692 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5693 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5702 OpTy = IntegerType::get(Context, BitSize);
5707 return TLI.getValueType(OpTy, true);
5711 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5713 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5714 const TargetRegisterInfo &TRI) {
5715 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5717 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5718 for (; *Aliases; ++Aliases)
5719 Regs.insert(*Aliases);
5723 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5725 } // end anonymous namespace
5727 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5728 /// specified operand. We prefer to assign virtual registers, to allow the
5729 /// register allocator to handle the assignment process. However, if the asm
5730 /// uses features that we can't model on machineinstrs, we have SDISel do the
5731 /// allocation. This produces generally horrible, but correct, code.
5733 /// OpInfo describes the operand.
5734 /// Input and OutputRegs are the set of already allocated physical registers.
5736 static void GetRegistersForValue(SelectionDAG &DAG,
5737 const TargetLowering &TLI,
5739 SDISelAsmOperandInfo &OpInfo,
5740 std::set<unsigned> &OutputRegs,
5741 std::set<unsigned> &InputRegs) {
5742 LLVMContext &Context = *DAG.getContext();
5744 // Compute whether this value requires an input register, an output register,
5746 bool isOutReg = false;
5747 bool isInReg = false;
5748 switch (OpInfo.Type) {
5749 case InlineAsm::isOutput:
5752 // If there is an input constraint that matches this, we need to reserve
5753 // the input register so no other inputs allocate to it.
5754 isInReg = OpInfo.hasMatchingInput();
5756 case InlineAsm::isInput:
5760 case InlineAsm::isClobber:
5767 MachineFunction &MF = DAG.getMachineFunction();
5768 SmallVector<unsigned, 4> Regs;
5770 // If this is a constraint for a single physreg, or a constraint for a
5771 // register class, find it.
5772 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5773 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5774 OpInfo.ConstraintVT);
5776 unsigned NumRegs = 1;
5777 if (OpInfo.ConstraintVT != MVT::Other) {
5778 // If this is a FP input in an integer register (or visa versa) insert a bit
5779 // cast of the input value. More generally, handle any case where the input
5780 // value disagrees with the register class we plan to stick this in.
5781 if (OpInfo.Type == InlineAsm::isInput &&
5782 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5783 // Try to convert to the first EVT that the reg class contains. If the
5784 // types are identical size, use a bitcast to convert (e.g. two differing
5786 EVT RegVT = *PhysReg.second->vt_begin();
5787 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5788 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5789 RegVT, OpInfo.CallOperand);
5790 OpInfo.ConstraintVT = RegVT;
5791 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5792 // If the input is a FP value and we want it in FP registers, do a
5793 // bitcast to the corresponding integer type. This turns an f64 value
5794 // into i64, which can be passed with two i32 values on a 32-bit
5796 RegVT = EVT::getIntegerVT(Context,
5797 OpInfo.ConstraintVT.getSizeInBits());
5798 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5799 RegVT, OpInfo.CallOperand);
5800 OpInfo.ConstraintVT = RegVT;
5804 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5808 EVT ValueVT = OpInfo.ConstraintVT;
5810 // If this is a constraint for a specific physical register, like {r17},
5812 if (unsigned AssignedReg = PhysReg.first) {
5813 const TargetRegisterClass *RC = PhysReg.second;
5814 if (OpInfo.ConstraintVT == MVT::Other)
5815 ValueVT = *RC->vt_begin();
5817 // Get the actual register value type. This is important, because the user
5818 // may have asked for (e.g.) the AX register in i32 type. We need to
5819 // remember that AX is actually i16 to get the right extension.
5820 RegVT = *RC->vt_begin();
5822 // This is a explicit reference to a physical register.
5823 Regs.push_back(AssignedReg);
5825 // If this is an expanded reference, add the rest of the regs to Regs.
5827 TargetRegisterClass::iterator I = RC->begin();
5828 for (; *I != AssignedReg; ++I)
5829 assert(I != RC->end() && "Didn't find reg!");
5831 // Already added the first reg.
5833 for (; NumRegs; --NumRegs, ++I) {
5834 assert(I != RC->end() && "Ran out of registers to allocate!");
5839 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5840 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5841 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5845 // Otherwise, if this was a reference to an LLVM register class, create vregs
5846 // for this reference.
5847 if (const TargetRegisterClass *RC = PhysReg.second) {
5848 RegVT = *RC->vt_begin();
5849 if (OpInfo.ConstraintVT == MVT::Other)
5852 // Create the appropriate number of virtual registers.
5853 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5854 for (; NumRegs; --NumRegs)
5855 Regs.push_back(RegInfo.createVirtualRegister(RC));
5857 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5861 // Otherwise, we couldn't allocate enough registers for this.
5864 /// visitInlineAsm - Handle a call to an InlineAsm object.
5866 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5867 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5869 /// ConstraintOperands - Information about all of the constraints.
5870 SDISelAsmOperandInfoVector ConstraintOperands;
5872 std::set<unsigned> OutputRegs, InputRegs;
5874 TargetLowering::AsmOperandInfoVector
5875 TargetConstraints = TLI.ParseConstraints(CS);
5877 bool hasMemory = false;
5879 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5880 unsigned ResNo = 0; // ResNo - The result number of the next output.
5881 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5882 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5883 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5885 EVT OpVT = MVT::Other;
5887 // Compute the value type for each operand.
5888 switch (OpInfo.Type) {
5889 case InlineAsm::isOutput:
5890 // Indirect outputs just consume an argument.
5891 if (OpInfo.isIndirect) {
5892 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5896 // The return value of the call is this value. As such, there is no
5897 // corresponding argument.
5898 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5899 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
5900 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5902 assert(ResNo == 0 && "Asm only has one result!");
5903 OpVT = TLI.getValueType(CS.getType());
5907 case InlineAsm::isInput:
5908 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5910 case InlineAsm::isClobber:
5915 // If this is an input or an indirect output, process the call argument.
5916 // BasicBlocks are labels, currently appearing only in asm's.
5917 if (OpInfo.CallOperandVal) {
5918 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5919 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5921 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5924 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5927 OpInfo.ConstraintVT = OpVT;
5929 // Indirect operand accesses access memory.
5930 if (OpInfo.isIndirect)
5933 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5934 TargetLowering::ConstraintType
5935 CType = TLI.getConstraintType(OpInfo.Codes[j]);
5936 if (CType == TargetLowering::C_Memory) {
5944 SDValue Chain, Flag;
5946 // We won't need to flush pending loads if this asm doesn't touch
5947 // memory and is nonvolatile.
5948 if (hasMemory || IA->hasSideEffects())
5951 Chain = DAG.getRoot();
5953 // Second pass over the constraints: compute which constraint option to use
5954 // and assign registers to constraints that want a specific physreg.
5955 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5956 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5958 // If this is an output operand with a matching input operand, look up the
5959 // matching input. If their types mismatch, e.g. one is an integer, the
5960 // other is floating point, or their sizes are different, flag it as an
5962 if (OpInfo.hasMatchingInput()) {
5963 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5965 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5966 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
5967 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5968 OpInfo.ConstraintVT);
5969 std::pair<unsigned, const TargetRegisterClass*> InputRC =
5970 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
5971 Input.ConstraintVT);
5972 if ((OpInfo.ConstraintVT.isInteger() !=
5973 Input.ConstraintVT.isInteger()) ||
5974 (MatchRC.second != InputRC.second)) {
5975 report_fatal_error("Unsupported asm: input constraint"
5976 " with a matching output constraint of"
5977 " incompatible type!");
5979 Input.ConstraintVT = OpInfo.ConstraintVT;
5983 // Compute the constraint code and ConstraintType to use.
5984 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5986 // If this is a memory input, and if the operand is not indirect, do what we
5987 // need to to provide an address for the memory input.
5988 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5989 !OpInfo.isIndirect) {
5990 assert((OpInfo.isMultipleAlternative ||
5991 (OpInfo.Type == InlineAsm::isInput)) &&
5992 "Can only indirectify direct input operands!");
5994 // Memory operands really want the address of the value. If we don't have
5995 // an indirect input, put it in the constpool if we can, otherwise spill
5996 // it to a stack slot.
5997 // TODO: This isn't quite right. We need to handle these according to
5998 // the addressing mode that the constraint wants. Also, this may take
5999 // an additional register for the computation and we don't want that
6002 // If the operand is a float, integer, or vector constant, spill to a
6003 // constant pool entry to get its address.
6004 const Value *OpVal = OpInfo.CallOperandVal;
6005 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6006 isa<ConstantVector>(OpVal)) {
6007 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6008 TLI.getPointerTy());
6010 // Otherwise, create a stack slot and emit a store to it before the
6012 Type *Ty = OpVal->getType();
6013 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
6014 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
6015 MachineFunction &MF = DAG.getMachineFunction();
6016 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6017 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
6018 Chain = DAG.getStore(Chain, getCurDebugLoc(),
6019 OpInfo.CallOperand, StackSlot,
6020 MachinePointerInfo::getFixedStack(SSFI),
6022 OpInfo.CallOperand = StackSlot;
6025 // There is no longer a Value* corresponding to this operand.
6026 OpInfo.CallOperandVal = 0;
6028 // It is now an indirect operand.
6029 OpInfo.isIndirect = true;
6032 // If this constraint is for a specific register, allocate it before
6034 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6035 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
6039 // Second pass - Loop over all of the operands, assigning virtual or physregs
6040 // to register class operands.
6041 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6042 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6044 // C_Register operands have already been allocated, Other/Memory don't need
6046 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6047 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
6051 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6052 std::vector<SDValue> AsmNodeOperands;
6053 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6054 AsmNodeOperands.push_back(
6055 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6056 TLI.getPointerTy()));
6058 // If we have a !srcloc metadata node associated with it, we want to attach
6059 // this to the ultimately generated inline asm machineinstr. To do this, we
6060 // pass in the third operand as this (potentially null) inline asm MDNode.
6061 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6062 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6064 // Remember the HasSideEffect and AlignStack bits as operand 3.
6065 unsigned ExtraInfo = 0;
6066 if (IA->hasSideEffects())
6067 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6068 if (IA->isAlignStack())
6069 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6070 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6071 TLI.getPointerTy()));
6073 // Loop over all of the inputs, copying the operand values into the
6074 // appropriate registers and processing the output regs.
6075 RegsForValue RetValRegs;
6077 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6078 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6080 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6081 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6083 switch (OpInfo.Type) {
6084 case InlineAsm::isOutput: {
6085 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6086 OpInfo.ConstraintType != TargetLowering::C_Register) {
6087 // Memory output, or 'other' output (e.g. 'X' constraint).
6088 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6090 // Add information to the INLINEASM node to know about this output.
6091 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6092 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6093 TLI.getPointerTy()));
6094 AsmNodeOperands.push_back(OpInfo.CallOperand);
6098 // Otherwise, this is a register or register class output.
6100 // Copy the output from the appropriate register. Find a register that
6102 if (OpInfo.AssignedRegs.Regs.empty())
6103 report_fatal_error("Couldn't allocate output reg for constraint '" +
6104 Twine(OpInfo.ConstraintCode) + "'!");
6106 // If this is an indirect operand, store through the pointer after the
6108 if (OpInfo.isIndirect) {
6109 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6110 OpInfo.CallOperandVal));
6112 // This is the result value of the call.
6113 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6114 // Concatenate this output onto the outputs list.
6115 RetValRegs.append(OpInfo.AssignedRegs);
6118 // Add information to the INLINEASM node to know that this register is
6120 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
6121 InlineAsm::Kind_RegDefEarlyClobber :
6122 InlineAsm::Kind_RegDef,
6129 case InlineAsm::isInput: {
6130 SDValue InOperandVal = OpInfo.CallOperand;
6132 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6133 // If this is required to match an output register we have already set,
6134 // just use its register.
6135 unsigned OperandNo = OpInfo.getMatchedOperand();
6137 // Scan until we find the definition we already emitted of this operand.
6138 // When we find it, create a RegsForValue operand.
6139 unsigned CurOp = InlineAsm::Op_FirstOperand;
6140 for (; OperandNo; --OperandNo) {
6141 // Advance to the next operand.
6143 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6144 assert((InlineAsm::isRegDefKind(OpFlag) ||
6145 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6146 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6147 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6151 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6152 if (InlineAsm::isRegDefKind(OpFlag) ||
6153 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6154 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6155 if (OpInfo.isIndirect) {
6156 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6157 LLVMContext &Ctx = *DAG.getContext();
6158 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6159 " don't know how to handle tied "
6160 "indirect register inputs");
6163 RegsForValue MatchedRegs;
6164 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6165 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
6166 MatchedRegs.RegVTs.push_back(RegVT);
6167 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6168 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6170 MatchedRegs.Regs.push_back
6171 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
6173 // Use the produced MatchedRegs object to
6174 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6176 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6177 true, OpInfo.getMatchedOperand(),
6178 DAG, AsmNodeOperands);
6182 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6183 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6184 "Unexpected number of operands");
6185 // Add information to the INLINEASM node to know about this input.
6186 // See InlineAsm.h isUseOperandTiedToDef.
6187 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6188 OpInfo.getMatchedOperand());
6189 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6190 TLI.getPointerTy()));
6191 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6195 // Treat indirect 'X' constraint as memory.
6196 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6198 OpInfo.ConstraintType = TargetLowering::C_Memory;
6200 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6201 std::vector<SDValue> Ops;
6202 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6205 report_fatal_error("Invalid operand for inline asm constraint '" +
6206 Twine(OpInfo.ConstraintCode) + "'!");
6208 // Add information to the INLINEASM node to know about this input.
6209 unsigned ResOpType =
6210 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6211 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6212 TLI.getPointerTy()));
6213 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6217 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6218 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6219 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6220 "Memory operands expect pointer values");
6222 // Add information to the INLINEASM node to know about this input.
6223 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6224 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6225 TLI.getPointerTy()));
6226 AsmNodeOperands.push_back(InOperandVal);
6230 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6231 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6232 "Unknown constraint type!");
6233 assert(!OpInfo.isIndirect &&
6234 "Don't know how to handle indirect register inputs yet!");
6236 // Copy the input into the appropriate registers.
6237 if (OpInfo.AssignedRegs.Regs.empty())
6238 report_fatal_error("Couldn't allocate input reg for constraint '" +
6239 Twine(OpInfo.ConstraintCode) + "'!");
6241 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6244 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6245 DAG, AsmNodeOperands);
6248 case InlineAsm::isClobber: {
6249 // Add the clobbered value to the operand list, so that the register
6250 // allocator is aware that the physreg got clobbered.
6251 if (!OpInfo.AssignedRegs.Regs.empty())
6252 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6260 // Finish up input operands. Set the input chain and add the flag last.
6261 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6262 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6264 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
6265 DAG.getVTList(MVT::Other, MVT::Glue),
6266 &AsmNodeOperands[0], AsmNodeOperands.size());
6267 Flag = Chain.getValue(1);
6269 // If this asm returns a register value, copy the result from that register
6270 // and set it as the value of the call.
6271 if (!RetValRegs.Regs.empty()) {
6272 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6275 // FIXME: Why don't we do this for inline asms with MRVs?
6276 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6277 EVT ResultType = TLI.getValueType(CS.getType());
6279 // If any of the results of the inline asm is a vector, it may have the
6280 // wrong width/num elts. This can happen for register classes that can
6281 // contain multiple different value types. The preg or vreg allocated may
6282 // not have the same VT as was expected. Convert it to the right type
6283 // with bit_convert.
6284 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6285 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
6288 } else if (ResultType != Val.getValueType() &&
6289 ResultType.isInteger() && Val.getValueType().isInteger()) {
6290 // If a result value was tied to an input value, the computed result may
6291 // have a wider width than the expected result. Extract the relevant
6293 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6296 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6299 setValue(CS.getInstruction(), Val);
6300 // Don't need to use this as a chain in this case.
6301 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6305 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6307 // Process indirect outputs, first output all of the flagged copies out of
6309 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6310 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6311 const Value *Ptr = IndirectStoresToEmit[i].second;
6312 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6314 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6317 // Emit the non-flagged stores from the physregs.
6318 SmallVector<SDValue, 8> OutChains;
6319 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6320 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6321 StoresToEmit[i].first,
6322 getValue(StoresToEmit[i].second),
6323 MachinePointerInfo(StoresToEmit[i].second),
6325 OutChains.push_back(Val);
6328 if (!OutChains.empty())
6329 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6330 &OutChains[0], OutChains.size());
6335 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6336 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6337 MVT::Other, getRoot(),
6338 getValue(I.getArgOperand(0)),
6339 DAG.getSrcValue(I.getArgOperand(0))));
6342 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6343 const TargetData &TD = *TLI.getTargetData();
6344 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6345 getRoot(), getValue(I.getOperand(0)),
6346 DAG.getSrcValue(I.getOperand(0)),
6347 TD.getABITypeAlignment(I.getType()));
6349 DAG.setRoot(V.getValue(1));
6352 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6353 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6354 MVT::Other, getRoot(),
6355 getValue(I.getArgOperand(0)),
6356 DAG.getSrcValue(I.getArgOperand(0))));
6359 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6360 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6361 MVT::Other, getRoot(),
6362 getValue(I.getArgOperand(0)),
6363 getValue(I.getArgOperand(1)),
6364 DAG.getSrcValue(I.getArgOperand(0)),
6365 DAG.getSrcValue(I.getArgOperand(1))));
6368 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6369 /// implementation, which just calls LowerCall.
6370 /// FIXME: When all targets are
6371 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6372 std::pair<SDValue, SDValue>
6373 TargetLowering::LowerCallTo(SDValue Chain, Type *RetTy,
6374 bool RetSExt, bool RetZExt, bool isVarArg,
6375 bool isInreg, unsigned NumFixedArgs,
6376 CallingConv::ID CallConv, bool isTailCall,
6377 bool isReturnValueUsed,
6379 ArgListTy &Args, SelectionDAG &DAG,
6380 DebugLoc dl) const {
6381 // Handle all of the outgoing arguments.
6382 SmallVector<ISD::OutputArg, 32> Outs;
6383 SmallVector<SDValue, 32> OutVals;
6384 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6385 SmallVector<EVT, 4> ValueVTs;
6386 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6387 for (unsigned Value = 0, NumValues = ValueVTs.size();
6388 Value != NumValues; ++Value) {
6389 EVT VT = ValueVTs[Value];
6390 Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6391 SDValue Op = SDValue(Args[i].Node.getNode(),
6392 Args[i].Node.getResNo() + Value);
6393 ISD::ArgFlagsTy Flags;
6394 unsigned OriginalAlignment =
6395 getTargetData()->getABITypeAlignment(ArgTy);
6401 if (Args[i].isInReg)
6405 if (Args[i].isByVal) {
6407 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6408 Type *ElementTy = Ty->getElementType();
6409 Flags.setByValSize(getTargetData()->getTypeAllocSize(ElementTy));
6410 // For ByVal, alignment should come from FE. BE will guess if this
6411 // info is not there but there are cases it cannot get right.
6412 unsigned FrameAlign;
6413 if (Args[i].Alignment)
6414 FrameAlign = Args[i].Alignment;
6416 FrameAlign = getByValTypeAlignment(ElementTy);
6417 Flags.setByValAlign(FrameAlign);
6421 Flags.setOrigAlign(OriginalAlignment);
6423 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6424 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6425 SmallVector<SDValue, 4> Parts(NumParts);
6426 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6429 ExtendKind = ISD::SIGN_EXTEND;
6430 else if (Args[i].isZExt)
6431 ExtendKind = ISD::ZERO_EXTEND;
6433 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
6434 PartVT, ExtendKind);
6436 for (unsigned j = 0; j != NumParts; ++j) {
6437 // if it isn't first piece, alignment must be 1
6438 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
6440 if (NumParts > 1 && j == 0)
6441 MyFlags.Flags.setSplit();
6443 MyFlags.Flags.setOrigAlign(1);
6445 Outs.push_back(MyFlags);
6446 OutVals.push_back(Parts[j]);
6451 // Handle the incoming return values from the call.
6452 SmallVector<ISD::InputArg, 32> Ins;
6453 SmallVector<EVT, 4> RetTys;
6454 ComputeValueVTs(*this, RetTy, RetTys);
6455 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6457 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6458 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6459 for (unsigned i = 0; i != NumRegs; ++i) {
6460 ISD::InputArg MyFlags;
6461 MyFlags.VT = RegisterVT.getSimpleVT();
6462 MyFlags.Used = isReturnValueUsed;
6464 MyFlags.Flags.setSExt();
6466 MyFlags.Flags.setZExt();
6468 MyFlags.Flags.setInReg();
6469 Ins.push_back(MyFlags);
6473 SmallVector<SDValue, 4> InVals;
6474 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6475 Outs, OutVals, Ins, dl, DAG, InVals);
6477 // Verify that the target's LowerCall behaved as expected.
6478 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6479 "LowerCall didn't return a valid chain!");
6480 assert((!isTailCall || InVals.empty()) &&
6481 "LowerCall emitted a return value for a tail call!");
6482 assert((isTailCall || InVals.size() == Ins.size()) &&
6483 "LowerCall didn't emit the correct number of values!");
6485 // For a tail call, the return value is merely live-out and there aren't
6486 // any nodes in the DAG representing it. Return a special value to
6487 // indicate that a tail call has been emitted and no more Instructions
6488 // should be processed in the current block.
6491 return std::make_pair(SDValue(), SDValue());
6494 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6495 assert(InVals[i].getNode() &&
6496 "LowerCall emitted a null value!");
6497 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6498 "LowerCall emitted a value with the wrong type!");
6501 // Collect the legal value parts into potentially illegal values
6502 // that correspond to the original function's return values.
6503 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6505 AssertOp = ISD::AssertSext;
6507 AssertOp = ISD::AssertZext;
6508 SmallVector<SDValue, 4> ReturnValues;
6509 unsigned CurReg = 0;
6510 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6512 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6513 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6515 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
6516 NumRegs, RegisterVT, VT,
6521 // For a function returning void, there is no return value. We can't create
6522 // such a node, so we just return a null return value in that case. In
6523 // that case, nothing will actually look at the value.
6524 if (ReturnValues.empty())
6525 return std::make_pair(SDValue(), Chain);
6527 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6528 DAG.getVTList(&RetTys[0], RetTys.size()),
6529 &ReturnValues[0], ReturnValues.size());
6530 return std::make_pair(Res, Chain);
6533 void TargetLowering::LowerOperationWrapper(SDNode *N,
6534 SmallVectorImpl<SDValue> &Results,
6535 SelectionDAG &DAG) const {
6536 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6538 Results.push_back(Res);
6541 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6542 llvm_unreachable("LowerOperation not implemented for this target!");
6547 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6548 SDValue Op = getNonRegisterValue(V);
6549 assert((Op.getOpcode() != ISD::CopyFromReg ||
6550 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6551 "Copy from a reg to the same reg!");
6552 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6554 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6555 SDValue Chain = DAG.getEntryNode();
6556 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
6557 PendingExports.push_back(Chain);
6560 #include "llvm/CodeGen/SelectionDAGISel.h"
6562 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6563 /// entry block, return true. This includes arguments used by switches, since
6564 /// the switch may expand into multiple basic blocks.
6565 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
6566 // With FastISel active, we may be splitting blocks, so force creation
6567 // of virtual registers for all non-dead arguments.
6569 return A->use_empty();
6571 const BasicBlock *Entry = A->getParent()->begin();
6572 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6574 const User *U = *UI;
6575 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6576 return false; // Use not in entry block.
6581 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
6582 // If this is the entry block, emit arguments.
6583 const Function &F = *LLVMBB->getParent();
6584 SelectionDAG &DAG = SDB->DAG;
6585 DebugLoc dl = SDB->getCurDebugLoc();
6586 const TargetData *TD = TLI.getTargetData();
6587 SmallVector<ISD::InputArg, 16> Ins;
6589 // Check whether the function can return without sret-demotion.
6590 SmallVector<ISD::OutputArg, 4> Outs;
6591 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6594 if (!FuncInfo->CanLowerReturn) {
6595 // Put in an sret pointer parameter before all the other parameters.
6596 SmallVector<EVT, 1> ValueVTs;
6597 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6599 // NOTE: Assuming that a pointer will never break down to more than one VT
6601 ISD::ArgFlagsTy Flags;
6603 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
6604 ISD::InputArg RetArg(Flags, RegisterVT, true);
6605 Ins.push_back(RetArg);
6608 // Set up the incoming argument description vector.
6610 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
6611 I != E; ++I, ++Idx) {
6612 SmallVector<EVT, 4> ValueVTs;
6613 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6614 bool isArgValueUsed = !I->use_empty();
6615 for (unsigned Value = 0, NumValues = ValueVTs.size();
6616 Value != NumValues; ++Value) {
6617 EVT VT = ValueVTs[Value];
6618 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6619 ISD::ArgFlagsTy Flags;
6620 unsigned OriginalAlignment =
6621 TD->getABITypeAlignment(ArgTy);
6623 if (F.paramHasAttr(Idx, Attribute::ZExt))
6625 if (F.paramHasAttr(Idx, Attribute::SExt))
6627 if (F.paramHasAttr(Idx, Attribute::InReg))
6629 if (F.paramHasAttr(Idx, Attribute::StructRet))
6631 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6633 PointerType *Ty = cast<PointerType>(I->getType());
6634 Type *ElementTy = Ty->getElementType();
6635 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
6636 // For ByVal, alignment should be passed from FE. BE will guess if
6637 // this info is not there but there are cases it cannot get right.
6638 unsigned FrameAlign;
6639 if (F.getParamAlignment(Idx))
6640 FrameAlign = F.getParamAlignment(Idx);
6642 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6643 Flags.setByValAlign(FrameAlign);
6645 if (F.paramHasAttr(Idx, Attribute::Nest))
6647 Flags.setOrigAlign(OriginalAlignment);
6649 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6650 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6651 for (unsigned i = 0; i != NumRegs; ++i) {
6652 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6653 if (NumRegs > 1 && i == 0)
6654 MyFlags.Flags.setSplit();
6655 // if it isn't first piece, alignment must be 1
6657 MyFlags.Flags.setOrigAlign(1);
6658 Ins.push_back(MyFlags);
6663 // Call the target to set up the argument values.
6664 SmallVector<SDValue, 8> InVals;
6665 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6669 // Verify that the target's LowerFormalArguments behaved as expected.
6670 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6671 "LowerFormalArguments didn't return a valid chain!");
6672 assert(InVals.size() == Ins.size() &&
6673 "LowerFormalArguments didn't emit the correct number of values!");
6675 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6676 assert(InVals[i].getNode() &&
6677 "LowerFormalArguments emitted a null value!");
6678 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6679 "LowerFormalArguments emitted a value with the wrong type!");
6683 // Update the DAG with the new chain value resulting from argument lowering.
6684 DAG.setRoot(NewRoot);
6686 // Set up the argument values.
6689 if (!FuncInfo->CanLowerReturn) {
6690 // Create a virtual register for the sret pointer, and put in a copy
6691 // from the sret argument into it.
6692 SmallVector<EVT, 1> ValueVTs;
6693 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6694 EVT VT = ValueVTs[0];
6695 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6696 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6697 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6698 RegVT, VT, AssertOp);
6700 MachineFunction& MF = SDB->DAG.getMachineFunction();
6701 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6702 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6703 FuncInfo->DemoteRegister = SRetReg;
6704 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6706 DAG.setRoot(NewRoot);
6708 // i indexes lowered arguments. Bump it past the hidden sret argument.
6709 // Idx indexes LLVM arguments. Don't touch it.
6713 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6715 SmallVector<SDValue, 4> ArgValues;
6716 SmallVector<EVT, 4> ValueVTs;
6717 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6718 unsigned NumValues = ValueVTs.size();
6720 // If this argument is unused then remember its value. It is used to generate
6721 // debugging information.
6722 if (I->use_empty() && NumValues)
6723 SDB->setUnusedArgValue(I, InVals[i]);
6725 for (unsigned Val = 0; Val != NumValues; ++Val) {
6726 EVT VT = ValueVTs[Val];
6727 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6728 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6730 if (!I->use_empty()) {
6731 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6732 if (F.paramHasAttr(Idx, Attribute::SExt))
6733 AssertOp = ISD::AssertSext;
6734 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6735 AssertOp = ISD::AssertZext;
6737 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6738 NumParts, PartVT, VT,
6745 // We don't need to do anything else for unused arguments.
6746 if (ArgValues.empty())
6749 // Note down frame index.
6750 if (FrameIndexSDNode *FI =
6751 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
6752 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
6754 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6755 SDB->getCurDebugLoc());
6757 SDB->setValue(I, Res);
6758 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
6759 if (LoadSDNode *LNode =
6760 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
6761 if (FrameIndexSDNode *FI =
6762 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6763 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
6766 // If this argument is live outside of the entry block, insert a copy from
6767 // wherever we got it to the vreg that other BB's will reference it as.
6768 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
6769 // If we can, though, try to skip creating an unnecessary vreg.
6770 // FIXME: This isn't very clean... it would be nice to make this more
6771 // general. It's also subtly incompatible with the hacks FastISel
6773 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6774 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6775 FuncInfo->ValueMap[I] = Reg;
6779 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
6780 FuncInfo->InitializeRegForValue(I);
6781 SDB->CopyToExportRegsIfNeeded(I);
6785 assert(i == InVals.size() && "Argument register count mismatch!");
6787 // Finally, if the target has anything special to do, allow it to do so.
6788 // FIXME: this should insert code into the DAG!
6789 EmitFunctionEntryCode();
6792 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6793 /// ensure constants are generated when needed. Remember the virtual registers
6794 /// that need to be added to the Machine PHI nodes as input. We cannot just
6795 /// directly add them, because expansion might result in multiple MBB's for one
6796 /// BB. As such, the start of the BB might correspond to a different MBB than
6800 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6801 const TerminatorInst *TI = LLVMBB->getTerminator();
6803 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6805 // Check successor nodes' PHI nodes that expect a constant to be available
6807 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6808 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6809 if (!isa<PHINode>(SuccBB->begin())) continue;
6810 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6812 // If this terminator has multiple identical successors (common for
6813 // switches), only handle each succ once.
6814 if (!SuccsHandled.insert(SuccMBB)) continue;
6816 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6818 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6819 // nodes and Machine PHI nodes, but the incoming operands have not been
6821 for (BasicBlock::const_iterator I = SuccBB->begin();
6822 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6823 // Ignore dead phi's.
6824 if (PN->use_empty()) continue;
6827 if (PN->getType()->isEmptyTy())
6831 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6833 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6834 unsigned &RegOut = ConstantsOut[C];
6836 RegOut = FuncInfo.CreateRegs(C->getType());
6837 CopyValueToVirtualRegister(C, RegOut);
6841 DenseMap<const Value *, unsigned>::iterator I =
6842 FuncInfo.ValueMap.find(PHIOp);
6843 if (I != FuncInfo.ValueMap.end())
6846 assert(isa<AllocaInst>(PHIOp) &&
6847 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6848 "Didn't codegen value into a register!??");
6849 Reg = FuncInfo.CreateRegs(PHIOp->getType());
6850 CopyValueToVirtualRegister(PHIOp, Reg);
6854 // Remember that this register needs to added to the machine PHI node as
6855 // the input for this MBB.
6856 SmallVector<EVT, 4> ValueVTs;
6857 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6858 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6859 EVT VT = ValueVTs[vti];
6860 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6861 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6862 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6863 Reg += NumRegisters;
6867 ConstantsOut.clear();