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 "SelectionDAGBuilder.h"
16 #include "SDNodeDbgValue.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/StackMaps.h"
37 #include "llvm/DebugInfo.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetFrameLowering.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetIntrinsicInfo.h"
58 #include "llvm/Target/TargetLibraryInfo.h"
59 #include "llvm/Target/TargetLowering.h"
60 #include "llvm/Target/TargetOptions.h"
61 #include "llvm/Target/TargetSelectionDAGInfo.h"
65 /// LimitFloatPrecision - Generate low-precision inline sequences for
66 /// some float libcalls (6, 8 or 12 bits).
67 static unsigned LimitFloatPrecision;
69 static cl::opt<unsigned, true>
70 LimitFPPrecision("limit-float-precision",
71 cl::desc("Generate low-precision inline sequences "
72 "for some float libcalls"),
73 cl::location(LimitFloatPrecision),
76 // Limit the width of DAG chains. This is important in general to prevent
77 // prevent DAG-based analysis from blowing up. For example, alias analysis and
78 // load clustering may not complete in reasonable time. It is difficult to
79 // recognize and avoid this situation within each individual analysis, and
80 // future analyses are likely to have the same behavior. Limiting DAG width is
81 // the safe approach, and will be especially important with global DAGs.
83 // MaxParallelChains default is arbitrarily high to avoid affecting
84 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
85 // sequence over this should have been converted to llvm.memcpy by the
86 // frontend. It easy to induce this behavior with .ll code such as:
87 // %buffer = alloca [4096 x i8]
88 // %data = load [4096 x i8]* %argPtr
89 // store [4096 x i8] %data, [4096 x i8]* %buffer
90 static const unsigned MaxParallelChains = 64;
92 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
93 const SDValue *Parts, unsigned NumParts,
94 MVT PartVT, EVT ValueVT, const Value *V);
96 /// getCopyFromParts - Create a value that contains the specified legal parts
97 /// combined into the value they represent. If the parts combine to a type
98 /// larger then ValueVT then AssertOp can be used to specify whether the extra
99 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
100 /// (ISD::AssertSext).
101 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
102 const SDValue *Parts,
103 unsigned NumParts, MVT PartVT, EVT ValueVT,
105 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
106 if (ValueVT.isVector())
107 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
110 assert(NumParts > 0 && "No parts to assemble!");
111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
112 SDValue Val = Parts[0];
115 // Assemble the value from multiple parts.
116 if (ValueVT.isInteger()) {
117 unsigned PartBits = PartVT.getSizeInBits();
118 unsigned ValueBits = ValueVT.getSizeInBits();
120 // Assemble the power of 2 part.
121 unsigned RoundParts = NumParts & (NumParts - 1) ?
122 1 << Log2_32(NumParts) : NumParts;
123 unsigned RoundBits = PartBits * RoundParts;
124 EVT RoundVT = RoundBits == ValueBits ?
125 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
128 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
130 if (RoundParts > 2) {
131 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
133 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
134 RoundParts / 2, PartVT, HalfVT, V);
136 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
137 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
140 if (TLI.isBigEndian())
143 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
145 if (RoundParts < NumParts) {
146 // Assemble the trailing non-power-of-2 part.
147 unsigned OddParts = NumParts - RoundParts;
148 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
149 Hi = getCopyFromParts(DAG, DL,
150 Parts + RoundParts, OddParts, PartVT, OddVT, V);
152 // Combine the round and odd parts.
154 if (TLI.isBigEndian())
156 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
157 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
158 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
159 DAG.getConstant(Lo.getValueType().getSizeInBits(),
160 TLI.getPointerTy()));
161 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
162 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
164 } else if (PartVT.isFloatingPoint()) {
165 // FP split into multiple FP parts (for ppcf128)
166 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
169 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
170 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
171 if (TLI.isBigEndian())
173 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
175 // FP split into integer parts (soft fp)
176 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
177 !PartVT.isVector() && "Unexpected split");
178 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
179 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
183 // There is now one part, held in Val. Correct it to match ValueVT.
184 EVT PartEVT = Val.getValueType();
186 if (PartEVT == ValueVT)
189 if (PartEVT.isInteger() && ValueVT.isInteger()) {
190 if (ValueVT.bitsLT(PartEVT)) {
191 // For a truncate, see if we have any information to
192 // indicate whether the truncated bits will always be
193 // zero or sign-extension.
194 if (AssertOp != ISD::DELETED_NODE)
195 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
196 DAG.getValueType(ValueVT));
197 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
199 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
202 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
203 // FP_ROUND's are always exact here.
204 if (ValueVT.bitsLT(Val.getValueType()))
205 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
206 DAG.getTargetConstant(1, TLI.getPointerTy()));
208 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
211 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
212 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
214 llvm_unreachable("Unknown mismatch!");
217 /// getCopyFromPartsVector - Create a value that contains the specified legal
218 /// parts combined into the value they represent. If the parts combine to a
219 /// type larger then ValueVT then AssertOp can be used to specify whether the
220 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
221 /// ValueVT (ISD::AssertSext).
222 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
223 const SDValue *Parts, unsigned NumParts,
224 MVT PartVT, EVT ValueVT, const Value *V) {
225 assert(ValueVT.isVector() && "Not a vector value");
226 assert(NumParts > 0 && "No parts to assemble!");
227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
228 SDValue Val = Parts[0];
230 // Handle a multi-element vector.
234 unsigned NumIntermediates;
236 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
237 NumIntermediates, RegisterVT);
238 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
239 NumParts = NumRegs; // Silence a compiler warning.
240 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
241 assert(RegisterVT == Parts[0].getSimpleValueType() &&
242 "Part type doesn't match part!");
244 // Assemble the parts into intermediate operands.
245 SmallVector<SDValue, 8> Ops(NumIntermediates);
246 if (NumIntermediates == NumParts) {
247 // If the register was not expanded, truncate or copy the value,
249 for (unsigned i = 0; i != NumParts; ++i)
250 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
251 PartVT, IntermediateVT, V);
252 } else if (NumParts > 0) {
253 // If the intermediate type was expanded, build the intermediate
254 // operands from the parts.
255 assert(NumParts % NumIntermediates == 0 &&
256 "Must expand into a divisible number of parts!");
257 unsigned Factor = NumParts / NumIntermediates;
258 for (unsigned i = 0; i != NumIntermediates; ++i)
259 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
260 PartVT, IntermediateVT, V);
263 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
264 // intermediate operands.
265 Val = DAG.getNode(IntermediateVT.isVector() ?
266 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
267 ValueVT, &Ops[0], NumIntermediates);
270 // There is now one part, held in Val. Correct it to match ValueVT.
271 EVT PartEVT = Val.getValueType();
273 if (PartEVT == ValueVT)
276 if (PartEVT.isVector()) {
277 // If the element type of the source/dest vectors are the same, but the
278 // parts vector has more elements than the value vector, then we have a
279 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
281 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
282 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
283 "Cannot narrow, it would be a lossy transformation");
284 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
285 DAG.getConstant(0, TLI.getVectorIdxTy()));
288 // Vector/Vector bitcast.
289 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
290 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
292 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
293 "Cannot handle this kind of promotion");
294 // Promoted vector extract
295 bool Smaller = ValueVT.bitsLE(PartEVT);
296 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
301 // Trivial bitcast if the types are the same size and the destination
302 // vector type is legal.
303 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
304 TLI.isTypeLegal(ValueVT))
305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
307 // Handle cases such as i8 -> <1 x i1>
308 if (ValueVT.getVectorNumElements() != 1) {
309 LLVMContext &Ctx = *DAG.getContext();
310 Twine ErrMsg("non-trivial scalar-to-vector conversion");
311 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
312 if (const CallInst *CI = dyn_cast<CallInst>(I))
313 if (isa<InlineAsm>(CI->getCalledValue()))
314 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
315 Ctx.emitError(I, ErrMsg);
317 Ctx.emitError(ErrMsg);
319 return DAG.getUNDEF(ValueVT);
322 if (ValueVT.getVectorNumElements() == 1 &&
323 ValueVT.getVectorElementType() != PartEVT) {
324 bool Smaller = ValueVT.bitsLE(PartEVT);
325 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
326 DL, ValueVT.getScalarType(), Val);
329 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
332 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
333 SDValue Val, SDValue *Parts, unsigned NumParts,
334 MVT PartVT, const Value *V);
336 /// getCopyToParts - Create a series of nodes that contain the specified value
337 /// split into legal parts. If the parts contain more bits than Val, then, for
338 /// integers, ExtendKind can be used to specify how to generate the extra bits.
339 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
340 SDValue Val, SDValue *Parts, unsigned NumParts,
341 MVT PartVT, const Value *V,
342 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
343 EVT ValueVT = Val.getValueType();
345 // Handle the vector case separately.
346 if (ValueVT.isVector())
347 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
350 unsigned PartBits = PartVT.getSizeInBits();
351 unsigned OrigNumParts = NumParts;
352 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
357 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
358 EVT PartEVT = PartVT;
359 if (PartEVT == ValueVT) {
360 assert(NumParts == 1 && "No-op copy with multiple parts!");
365 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
366 // If the parts cover more bits than the value has, promote the value.
367 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
368 assert(NumParts == 1 && "Do not know what to promote to!");
369 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
371 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
372 ValueVT.isInteger() &&
373 "Unknown mismatch!");
374 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
375 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
376 if (PartVT == MVT::x86mmx)
377 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
379 } else if (PartBits == ValueVT.getSizeInBits()) {
380 // Different types of the same size.
381 assert(NumParts == 1 && PartEVT != ValueVT);
382 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
383 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
384 // If the parts cover less bits than value has, truncate the value.
385 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
386 ValueVT.isInteger() &&
387 "Unknown mismatch!");
388 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
389 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
390 if (PartVT == MVT::x86mmx)
391 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
394 // The value may have changed - recompute ValueVT.
395 ValueVT = Val.getValueType();
396 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
397 "Failed to tile the value with PartVT!");
400 if (PartEVT != ValueVT) {
401 LLVMContext &Ctx = *DAG.getContext();
402 Twine ErrMsg("scalar-to-vector conversion failed");
403 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
404 if (const CallInst *CI = dyn_cast<CallInst>(I))
405 if (isa<InlineAsm>(CI->getCalledValue()))
406 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
407 Ctx.emitError(I, ErrMsg);
409 Ctx.emitError(ErrMsg);
417 // Expand the value into multiple parts.
418 if (NumParts & (NumParts - 1)) {
419 // The number of parts is not a power of 2. Split off and copy the tail.
420 assert(PartVT.isInteger() && ValueVT.isInteger() &&
421 "Do not know what to expand to!");
422 unsigned RoundParts = 1 << Log2_32(NumParts);
423 unsigned RoundBits = RoundParts * PartBits;
424 unsigned OddParts = NumParts - RoundParts;
425 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
426 DAG.getIntPtrConstant(RoundBits));
427 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
429 if (TLI.isBigEndian())
430 // The odd parts were reversed by getCopyToParts - unreverse them.
431 std::reverse(Parts + RoundParts, Parts + NumParts);
433 NumParts = RoundParts;
434 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
435 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
438 // The number of parts is a power of 2. Repeatedly bisect the value using
440 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
441 EVT::getIntegerVT(*DAG.getContext(),
442 ValueVT.getSizeInBits()),
445 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
446 for (unsigned i = 0; i < NumParts; i += StepSize) {
447 unsigned ThisBits = StepSize * PartBits / 2;
448 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
449 SDValue &Part0 = Parts[i];
450 SDValue &Part1 = Parts[i+StepSize/2];
452 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
453 ThisVT, Part0, DAG.getIntPtrConstant(1));
454 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
455 ThisVT, Part0, DAG.getIntPtrConstant(0));
457 if (ThisBits == PartBits && ThisVT != PartVT) {
458 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
459 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
464 if (TLI.isBigEndian())
465 std::reverse(Parts, Parts + OrigNumParts);
469 /// getCopyToPartsVector - Create a series of nodes that contain the specified
470 /// value split into legal parts.
471 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
472 SDValue Val, SDValue *Parts, unsigned NumParts,
473 MVT PartVT, const Value *V) {
474 EVT ValueVT = Val.getValueType();
475 assert(ValueVT.isVector() && "Not a vector");
476 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
479 EVT PartEVT = PartVT;
480 if (PartEVT == ValueVT) {
482 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
483 // Bitconvert vector->vector case.
484 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
485 } else if (PartVT.isVector() &&
486 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
487 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
488 EVT ElementVT = PartVT.getVectorElementType();
489 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
491 SmallVector<SDValue, 16> Ops;
492 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
493 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
494 ElementVT, Val, DAG.getConstant(i,
495 TLI.getVectorIdxTy())));
497 for (unsigned i = ValueVT.getVectorNumElements(),
498 e = PartVT.getVectorNumElements(); i != e; ++i)
499 Ops.push_back(DAG.getUNDEF(ElementVT));
501 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
503 // FIXME: Use CONCAT for 2x -> 4x.
505 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
506 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
507 } else if (PartVT.isVector() &&
508 PartEVT.getVectorElementType().bitsGE(
509 ValueVT.getVectorElementType()) &&
510 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
512 // Promoted vector extract
513 bool Smaller = PartEVT.bitsLE(ValueVT);
514 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
517 // Vector -> scalar conversion.
518 assert(ValueVT.getVectorNumElements() == 1 &&
519 "Only trivial vector-to-scalar conversions should get here!");
520 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
521 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
523 bool Smaller = ValueVT.bitsLE(PartVT);
524 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
532 // Handle a multi-element vector.
535 unsigned NumIntermediates;
536 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
538 NumIntermediates, RegisterVT);
539 unsigned NumElements = ValueVT.getVectorNumElements();
541 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
542 NumParts = NumRegs; // Silence a compiler warning.
543 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
545 // Split the vector into intermediate operands.
546 SmallVector<SDValue, 8> Ops(NumIntermediates);
547 for (unsigned i = 0; i != NumIntermediates; ++i) {
548 if (IntermediateVT.isVector())
549 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
551 DAG.getConstant(i * (NumElements / NumIntermediates),
552 TLI.getVectorIdxTy()));
554 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
556 DAG.getConstant(i, TLI.getVectorIdxTy()));
559 // Split the intermediate operands into legal parts.
560 if (NumParts == NumIntermediates) {
561 // If the register was not expanded, promote or copy the value,
563 for (unsigned i = 0; i != NumParts; ++i)
564 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
565 } else if (NumParts > 0) {
566 // If the intermediate type was expanded, split each the value into
568 assert(NumParts % NumIntermediates == 0 &&
569 "Must expand into a divisible number of parts!");
570 unsigned Factor = NumParts / NumIntermediates;
571 for (unsigned i = 0; i != NumIntermediates; ++i)
572 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
577 /// RegsForValue - This struct represents the registers (physical or virtual)
578 /// that a particular set of values is assigned, and the type information
579 /// about the value. The most common situation is to represent one value at a
580 /// time, but struct or array values are handled element-wise as multiple
581 /// values. The splitting of aggregates is performed recursively, so that we
582 /// never have aggregate-typed registers. The values at this point do not
583 /// necessarily have legal types, so each value may require one or more
584 /// registers of some legal type.
586 struct RegsForValue {
587 /// ValueVTs - The value types of the values, which may not be legal, and
588 /// may need be promoted or synthesized from one or more registers.
590 SmallVector<EVT, 4> ValueVTs;
592 /// RegVTs - The value types of the registers. This is the same size as
593 /// ValueVTs and it records, for each value, what the type of the assigned
594 /// register or registers are. (Individual values are never synthesized
595 /// from more than one type of register.)
597 /// With virtual registers, the contents of RegVTs is redundant with TLI's
598 /// getRegisterType member function, however when with physical registers
599 /// it is necessary to have a separate record of the types.
601 SmallVector<MVT, 4> RegVTs;
603 /// Regs - This list holds the registers assigned to the values.
604 /// Each legal or promoted value requires one register, and each
605 /// expanded value requires multiple registers.
607 SmallVector<unsigned, 4> Regs;
611 RegsForValue(const SmallVector<unsigned, 4> ®s,
612 MVT regvt, EVT valuevt)
613 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
615 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
616 unsigned Reg, Type *Ty) {
617 ComputeValueVTs(tli, Ty, ValueVTs);
619 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
620 EVT ValueVT = ValueVTs[Value];
621 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
622 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
623 for (unsigned i = 0; i != NumRegs; ++i)
624 Regs.push_back(Reg + i);
625 RegVTs.push_back(RegisterVT);
630 /// areValueTypesLegal - Return true if types of all the values are legal.
631 bool areValueTypesLegal(const TargetLowering &TLI) {
632 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
633 MVT RegisterVT = RegVTs[Value];
634 if (!TLI.isTypeLegal(RegisterVT))
640 /// append - Add the specified values to this one.
641 void append(const RegsForValue &RHS) {
642 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
643 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
644 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
647 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
648 /// this value and returns the result as a ValueVTs value. This uses
649 /// Chain/Flag as the input and updates them for the output Chain/Flag.
650 /// If the Flag pointer is NULL, no flag is used.
651 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
653 SDValue &Chain, SDValue *Flag,
654 const Value *V = 0) const;
656 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
657 /// specified value into the registers specified by this object. This uses
658 /// Chain/Flag as the input and updates them for the output Chain/Flag.
659 /// If the Flag pointer is NULL, no flag is used.
660 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
661 SDValue &Chain, SDValue *Flag, const Value *V) const;
663 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
664 /// operand list. This adds the code marker, matching input operand index
665 /// (if applicable), and includes the number of values added into it.
666 void AddInlineAsmOperands(unsigned Kind,
667 bool HasMatching, unsigned MatchingIdx,
669 std::vector<SDValue> &Ops) const;
673 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
674 /// this value and returns the result as a ValueVT value. This uses
675 /// Chain/Flag as the input and updates them for the output Chain/Flag.
676 /// If the Flag pointer is NULL, no flag is used.
677 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
678 FunctionLoweringInfo &FuncInfo,
680 SDValue &Chain, SDValue *Flag,
681 const Value *V) const {
682 // A Value with type {} or [0 x %t] needs no registers.
683 if (ValueVTs.empty())
686 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
688 // Assemble the legal parts into the final values.
689 SmallVector<SDValue, 4> Values(ValueVTs.size());
690 SmallVector<SDValue, 8> Parts;
691 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
692 // Copy the legal parts from the registers.
693 EVT ValueVT = ValueVTs[Value];
694 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
695 MVT RegisterVT = RegVTs[Value];
697 Parts.resize(NumRegs);
698 for (unsigned i = 0; i != NumRegs; ++i) {
701 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
703 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
704 *Flag = P.getValue(2);
707 Chain = P.getValue(1);
710 // If the source register was virtual and if we know something about it,
711 // add an assert node.
712 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
713 !RegisterVT.isInteger() || RegisterVT.isVector())
716 const FunctionLoweringInfo::LiveOutInfo *LOI =
717 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
721 unsigned RegSize = RegisterVT.getSizeInBits();
722 unsigned NumSignBits = LOI->NumSignBits;
723 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
725 if (NumZeroBits == RegSize) {
726 // The current value is a zero.
727 // Explicitly express that as it would be easier for
728 // optimizations to kick in.
729 Parts[i] = DAG.getConstant(0, RegisterVT);
733 // FIXME: We capture more information than the dag can represent. For
734 // now, just use the tightest assertzext/assertsext possible.
736 EVT FromVT(MVT::Other);
737 if (NumSignBits == RegSize)
738 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
739 else if (NumZeroBits >= RegSize-1)
740 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
741 else if (NumSignBits > RegSize-8)
742 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
743 else if (NumZeroBits >= RegSize-8)
744 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
745 else if (NumSignBits > RegSize-16)
746 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
747 else if (NumZeroBits >= RegSize-16)
748 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
749 else if (NumSignBits > RegSize-32)
750 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
751 else if (NumZeroBits >= RegSize-32)
752 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
756 // Add an assertion node.
757 assert(FromVT != MVT::Other);
758 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
759 RegisterVT, P, DAG.getValueType(FromVT));
762 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
763 NumRegs, RegisterVT, ValueVT, V);
768 return DAG.getNode(ISD::MERGE_VALUES, dl,
769 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
770 &Values[0], ValueVTs.size());
773 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
774 /// specified value into the registers specified by this object. This uses
775 /// Chain/Flag as the input and updates them for the output Chain/Flag.
776 /// If the Flag pointer is NULL, no flag is used.
777 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
778 SDValue &Chain, SDValue *Flag,
779 const Value *V) const {
780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
782 // Get the list of the values's legal parts.
783 unsigned NumRegs = Regs.size();
784 SmallVector<SDValue, 8> Parts(NumRegs);
785 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
786 EVT ValueVT = ValueVTs[Value];
787 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
788 MVT RegisterVT = RegVTs[Value];
789 ISD::NodeType ExtendKind =
790 TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
792 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
793 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
797 // Copy the parts into the registers.
798 SmallVector<SDValue, 8> Chains(NumRegs);
799 for (unsigned i = 0; i != NumRegs; ++i) {
802 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
804 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
805 *Flag = Part.getValue(1);
808 Chains[i] = Part.getValue(0);
811 if (NumRegs == 1 || Flag)
812 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
813 // flagged to it. That is the CopyToReg nodes and the user are considered
814 // a single scheduling unit. If we create a TokenFactor and return it as
815 // chain, then the TokenFactor is both a predecessor (operand) of the
816 // user as well as a successor (the TF operands are flagged to the user).
817 // c1, f1 = CopyToReg
818 // c2, f2 = CopyToReg
819 // c3 = TokenFactor c1, c2
822 Chain = Chains[NumRegs-1];
824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
827 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
828 /// operand list. This adds the code marker and includes the number of
829 /// values added into it.
830 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
831 unsigned MatchingIdx,
833 std::vector<SDValue> &Ops) const {
834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
836 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
838 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
839 else if (!Regs.empty() &&
840 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
841 // Put the register class of the virtual registers in the flag word. That
842 // way, later passes can recompute register class constraints for inline
843 // assembly as well as normal instructions.
844 // Don't do this for tied operands that can use the regclass information
846 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
847 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
848 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
851 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
854 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
855 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
856 MVT RegisterVT = RegVTs[Value];
857 for (unsigned i = 0; i != NumRegs; ++i) {
858 assert(Reg < Regs.size() && "Mismatch in # registers expected");
859 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
864 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
865 const TargetLibraryInfo *li) {
869 TD = DAG.getTarget().getDataLayout();
870 Context = DAG.getContext();
871 LPadToCallSiteMap.clear();
874 /// clear - Clear out the current SelectionDAG and the associated
875 /// state and prepare this SelectionDAGBuilder object to be used
876 /// for a new block. This doesn't clear out information about
877 /// additional blocks that are needed to complete switch lowering
878 /// or PHI node updating; that information is cleared out as it is
880 void SelectionDAGBuilder::clear() {
882 UnusedArgNodeMap.clear();
883 PendingLoads.clear();
884 PendingExports.clear();
889 /// clearDanglingDebugInfo - Clear the dangling debug information
890 /// map. This function is separated from the clear so that debug
891 /// information that is dangling in a basic block can be properly
892 /// resolved in a different basic block. This allows the
893 /// SelectionDAG to resolve dangling debug information attached
895 void SelectionDAGBuilder::clearDanglingDebugInfo() {
896 DanglingDebugInfoMap.clear();
899 /// getRoot - Return the current virtual root of the Selection DAG,
900 /// flushing any PendingLoad items. This must be done before emitting
901 /// a store or any other node that may need to be ordered after any
902 /// prior load instructions.
904 SDValue SelectionDAGBuilder::getRoot() {
905 if (PendingLoads.empty())
906 return DAG.getRoot();
908 if (PendingLoads.size() == 1) {
909 SDValue Root = PendingLoads[0];
911 PendingLoads.clear();
915 // Otherwise, we have to make a token factor node.
916 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
917 &PendingLoads[0], PendingLoads.size());
918 PendingLoads.clear();
923 /// getControlRoot - Similar to getRoot, but instead of flushing all the
924 /// PendingLoad items, flush all the PendingExports items. It is necessary
925 /// to do this before emitting a terminator instruction.
927 SDValue SelectionDAGBuilder::getControlRoot() {
928 SDValue Root = DAG.getRoot();
930 if (PendingExports.empty())
933 // Turn all of the CopyToReg chains into one factored node.
934 if (Root.getOpcode() != ISD::EntryToken) {
935 unsigned i = 0, e = PendingExports.size();
936 for (; i != e; ++i) {
937 assert(PendingExports[i].getNode()->getNumOperands() > 1);
938 if (PendingExports[i].getNode()->getOperand(0) == Root)
939 break; // Don't add the root if we already indirectly depend on it.
943 PendingExports.push_back(Root);
946 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
948 PendingExports.size());
949 PendingExports.clear();
954 void SelectionDAGBuilder::visit(const Instruction &I) {
955 // Set up outgoing PHI node register values before emitting the terminator.
956 if (isa<TerminatorInst>(&I))
957 HandlePHINodesInSuccessorBlocks(I.getParent());
963 visit(I.getOpcode(), I);
965 if (!isa<TerminatorInst>(&I) && !HasTailCall)
966 CopyToExportRegsIfNeeded(&I);
971 void SelectionDAGBuilder::visitPHI(const PHINode &) {
972 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
975 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
976 // Note: this doesn't use InstVisitor, because it has to work with
977 // ConstantExpr's in addition to instructions.
979 default: llvm_unreachable("Unknown instruction type encountered!");
980 // Build the switch statement using the Instruction.def file.
981 #define HANDLE_INST(NUM, OPCODE, CLASS) \
982 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
983 #include "llvm/IR/Instruction.def"
987 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
988 // generate the debug data structures now that we've seen its definition.
989 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
991 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
993 const DbgValueInst *DI = DDI.getDI();
994 DebugLoc dl = DDI.getdl();
995 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
996 MDNode *Variable = DI->getVariable();
997 uint64_t Offset = DI->getOffset();
1000 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
1001 SDV = DAG.getDbgValue(Variable, Val.getNode(),
1002 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
1003 DAG.AddDbgValue(SDV, Val.getNode(), false);
1006 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1007 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1011 /// getValue - Return an SDValue for the given Value.
1012 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1013 // If we already have an SDValue for this value, use it. It's important
1014 // to do this first, so that we don't create a CopyFromReg if we already
1015 // have a regular SDValue.
1016 SDValue &N = NodeMap[V];
1017 if (N.getNode()) return N;
1019 // If there's a virtual register allocated and initialized for this
1021 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1022 if (It != FuncInfo.ValueMap.end()) {
1023 unsigned InReg = It->second;
1024 RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(),
1025 InReg, V->getType());
1026 SDValue Chain = DAG.getEntryNode();
1027 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
1028 resolveDanglingDebugInfo(V, N);
1032 // Otherwise create a new SDValue and remember it.
1033 SDValue Val = getValueImpl(V);
1035 resolveDanglingDebugInfo(V, Val);
1039 /// getNonRegisterValue - Return an SDValue for the given Value, but
1040 /// don't look in FuncInfo.ValueMap for a virtual register.
1041 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1042 // If we already have an SDValue for this value, use it.
1043 SDValue &N = NodeMap[V];
1044 if (N.getNode()) return N;
1046 // Otherwise create a new SDValue and remember it.
1047 SDValue Val = getValueImpl(V);
1049 resolveDanglingDebugInfo(V, Val);
1053 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1054 /// Create an SDValue for the given value.
1055 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1056 const TargetLowering *TLI = TM.getTargetLowering();
1058 if (const Constant *C = dyn_cast<Constant>(V)) {
1059 EVT VT = TLI->getValueType(V->getType(), true);
1061 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1062 return DAG.getConstant(*CI, VT);
1064 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1065 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1067 if (isa<ConstantPointerNull>(C)) {
1068 unsigned AS = V->getType()->getPointerAddressSpace();
1069 return DAG.getConstant(0, TLI->getPointerTy(AS));
1072 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1073 return DAG.getConstantFP(*CFP, VT);
1075 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1076 return DAG.getUNDEF(VT);
1078 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1079 visit(CE->getOpcode(), *CE);
1080 SDValue N1 = NodeMap[V];
1081 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1085 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1086 SmallVector<SDValue, 4> Constants;
1087 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1089 SDNode *Val = getValue(*OI).getNode();
1090 // If the operand is an empty aggregate, there are no values.
1092 // Add each leaf value from the operand to the Constants list
1093 // to form a flattened list of all the values.
1094 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1095 Constants.push_back(SDValue(Val, i));
1098 return DAG.getMergeValues(&Constants[0], Constants.size(),
1102 if (const ConstantDataSequential *CDS =
1103 dyn_cast<ConstantDataSequential>(C)) {
1104 SmallVector<SDValue, 4> Ops;
1105 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1106 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1107 // Add each leaf value from the operand to the Constants list
1108 // to form a flattened list of all the values.
1109 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1110 Ops.push_back(SDValue(Val, i));
1113 if (isa<ArrayType>(CDS->getType()))
1114 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
1115 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1116 VT, &Ops[0], Ops.size());
1119 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1120 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1121 "Unknown struct or array constant!");
1123 SmallVector<EVT, 4> ValueVTs;
1124 ComputeValueVTs(*TLI, C->getType(), ValueVTs);
1125 unsigned NumElts = ValueVTs.size();
1127 return SDValue(); // empty struct
1128 SmallVector<SDValue, 4> Constants(NumElts);
1129 for (unsigned i = 0; i != NumElts; ++i) {
1130 EVT EltVT = ValueVTs[i];
1131 if (isa<UndefValue>(C))
1132 Constants[i] = DAG.getUNDEF(EltVT);
1133 else if (EltVT.isFloatingPoint())
1134 Constants[i] = DAG.getConstantFP(0, EltVT);
1136 Constants[i] = DAG.getConstant(0, EltVT);
1139 return DAG.getMergeValues(&Constants[0], NumElts,
1143 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1144 return DAG.getBlockAddress(BA, VT);
1146 VectorType *VecTy = cast<VectorType>(V->getType());
1147 unsigned NumElements = VecTy->getNumElements();
1149 // Now that we know the number and type of the elements, get that number of
1150 // elements into the Ops array based on what kind of constant it is.
1151 SmallVector<SDValue, 16> Ops;
1152 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1153 for (unsigned i = 0; i != NumElements; ++i)
1154 Ops.push_back(getValue(CV->getOperand(i)));
1156 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1157 EVT EltVT = TLI->getValueType(VecTy->getElementType());
1160 if (EltVT.isFloatingPoint())
1161 Op = DAG.getConstantFP(0, EltVT);
1163 Op = DAG.getConstant(0, EltVT);
1164 Ops.assign(NumElements, Op);
1167 // Create a BUILD_VECTOR node.
1168 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1169 VT, &Ops[0], Ops.size());
1172 // If this is a static alloca, generate it as the frameindex instead of
1174 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1175 DenseMap<const AllocaInst*, int>::iterator SI =
1176 FuncInfo.StaticAllocaMap.find(AI);
1177 if (SI != FuncInfo.StaticAllocaMap.end())
1178 return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
1181 // If this is an instruction which fast-isel has deferred, select it now.
1182 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1183 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1184 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
1185 SDValue Chain = DAG.getEntryNode();
1186 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
1189 llvm_unreachable("Can't get register for value!");
1192 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1193 const TargetLowering *TLI = TM.getTargetLowering();
1194 SDValue Chain = getControlRoot();
1195 SmallVector<ISD::OutputArg, 8> Outs;
1196 SmallVector<SDValue, 8> OutVals;
1198 if (!FuncInfo.CanLowerReturn) {
1199 unsigned DemoteReg = FuncInfo.DemoteRegister;
1200 const Function *F = I.getParent()->getParent();
1202 // Emit a store of the return value through the virtual register.
1203 // Leave Outs empty so that LowerReturn won't try to load return
1204 // registers the usual way.
1205 SmallVector<EVT, 1> PtrValueVTs;
1206 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
1209 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1210 SDValue RetOp = getValue(I.getOperand(0));
1212 SmallVector<EVT, 4> ValueVTs;
1213 SmallVector<uint64_t, 4> Offsets;
1214 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1215 unsigned NumValues = ValueVTs.size();
1217 SmallVector<SDValue, 4> Chains(NumValues);
1218 for (unsigned i = 0; i != NumValues; ++i) {
1219 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1220 RetPtr.getValueType(), RetPtr,
1221 DAG.getIntPtrConstant(Offsets[i]));
1223 DAG.getStore(Chain, getCurSDLoc(),
1224 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1225 // FIXME: better loc info would be nice.
1226 Add, MachinePointerInfo(), false, false, 0);
1229 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1230 MVT::Other, &Chains[0], NumValues);
1231 } else if (I.getNumOperands() != 0) {
1232 SmallVector<EVT, 4> ValueVTs;
1233 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
1234 unsigned NumValues = ValueVTs.size();
1236 SDValue RetOp = getValue(I.getOperand(0));
1237 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1238 EVT VT = ValueVTs[j];
1240 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1242 const Function *F = I.getParent()->getParent();
1243 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1245 ExtendKind = ISD::SIGN_EXTEND;
1246 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1248 ExtendKind = ISD::ZERO_EXTEND;
1250 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1251 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
1253 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
1254 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
1255 SmallVector<SDValue, 4> Parts(NumParts);
1256 getCopyToParts(DAG, getCurSDLoc(),
1257 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1258 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1260 // 'inreg' on function refers to return value
1261 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1262 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1266 // Propagate extension type if any
1267 if (ExtendKind == ISD::SIGN_EXTEND)
1269 else if (ExtendKind == ISD::ZERO_EXTEND)
1272 for (unsigned i = 0; i < NumParts; ++i) {
1273 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1274 VT, /*isfixed=*/true, 0, 0));
1275 OutVals.push_back(Parts[i]);
1281 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1282 CallingConv::ID CallConv =
1283 DAG.getMachineFunction().getFunction()->getCallingConv();
1284 Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
1285 Outs, OutVals, getCurSDLoc(),
1288 // Verify that the target's LowerReturn behaved as expected.
1289 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1290 "LowerReturn didn't return a valid chain!");
1292 // Update the DAG with the new chain value resulting from return lowering.
1296 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1297 /// created for it, emit nodes to copy the value into the virtual
1299 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1301 if (V->getType()->isEmptyTy())
1304 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1305 if (VMI != FuncInfo.ValueMap.end()) {
1306 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1307 CopyValueToVirtualRegister(V, VMI->second);
1311 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1312 /// the current basic block, add it to ValueMap now so that we'll get a
1314 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1315 // No need to export constants.
1316 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1318 // Already exported?
1319 if (FuncInfo.isExportedInst(V)) return;
1321 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1322 CopyValueToVirtualRegister(V, Reg);
1325 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1326 const BasicBlock *FromBB) {
1327 // The operands of the setcc have to be in this block. We don't know
1328 // how to export them from some other block.
1329 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1330 // Can export from current BB.
1331 if (VI->getParent() == FromBB)
1334 // Is already exported, noop.
1335 return FuncInfo.isExportedInst(V);
1338 // If this is an argument, we can export it if the BB is the entry block or
1339 // if it is already exported.
1340 if (isa<Argument>(V)) {
1341 if (FromBB == &FromBB->getParent()->getEntryBlock())
1344 // Otherwise, can only export this if it is already exported.
1345 return FuncInfo.isExportedInst(V);
1348 // Otherwise, constants can always be exported.
1352 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1353 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1354 const MachineBasicBlock *Dst) const {
1355 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1358 const BasicBlock *SrcBB = Src->getBasicBlock();
1359 const BasicBlock *DstBB = Dst->getBasicBlock();
1360 return BPI->getEdgeWeight(SrcBB, DstBB);
1363 void SelectionDAGBuilder::
1364 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1365 uint32_t Weight /* = 0 */) {
1367 Weight = getEdgeWeight(Src, Dst);
1368 Src->addSuccessor(Dst, Weight);
1372 static bool InBlock(const Value *V, const BasicBlock *BB) {
1373 if (const Instruction *I = dyn_cast<Instruction>(V))
1374 return I->getParent() == BB;
1378 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1379 /// This function emits a branch and is used at the leaves of an OR or an
1380 /// AND operator tree.
1383 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1384 MachineBasicBlock *TBB,
1385 MachineBasicBlock *FBB,
1386 MachineBasicBlock *CurBB,
1387 MachineBasicBlock *SwitchBB) {
1388 const BasicBlock *BB = CurBB->getBasicBlock();
1390 // If the leaf of the tree is a comparison, merge the condition into
1392 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1393 // The operands of the cmp have to be in this block. We don't know
1394 // how to export them from some other block. If this is the first block
1395 // of the sequence, no exporting is needed.
1396 if (CurBB == SwitchBB ||
1397 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1398 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1399 ISD::CondCode Condition;
1400 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1401 Condition = getICmpCondCode(IC->getPredicate());
1402 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1403 Condition = getFCmpCondCode(FC->getPredicate());
1404 if (TM.Options.NoNaNsFPMath)
1405 Condition = getFCmpCodeWithoutNaN(Condition);
1407 Condition = ISD::SETEQ; // silence warning.
1408 llvm_unreachable("Unknown compare instruction");
1411 CaseBlock CB(Condition, BOp->getOperand(0),
1412 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1413 SwitchCases.push_back(CB);
1418 // Create a CaseBlock record representing this branch.
1419 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1420 NULL, TBB, FBB, CurBB);
1421 SwitchCases.push_back(CB);
1424 /// FindMergedConditions - If Cond is an expression like
1425 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1426 MachineBasicBlock *TBB,
1427 MachineBasicBlock *FBB,
1428 MachineBasicBlock *CurBB,
1429 MachineBasicBlock *SwitchBB,
1431 // If this node is not part of the or/and tree, emit it as a branch.
1432 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1433 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1434 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1435 BOp->getParent() != CurBB->getBasicBlock() ||
1436 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1437 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1438 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1442 // Create TmpBB after CurBB.
1443 MachineFunction::iterator BBI = CurBB;
1444 MachineFunction &MF = DAG.getMachineFunction();
1445 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1446 CurBB->getParent()->insert(++BBI, TmpBB);
1448 if (Opc == Instruction::Or) {
1449 // Codegen X | Y as:
1457 // Emit the LHS condition.
1458 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1460 // Emit the RHS condition into TmpBB.
1461 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1463 assert(Opc == Instruction::And && "Unknown merge op!");
1464 // Codegen X & Y as:
1471 // This requires creation of TmpBB after CurBB.
1473 // Emit the LHS condition.
1474 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1476 // Emit the RHS condition into TmpBB.
1477 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1481 /// If the set of cases should be emitted as a series of branches, return true.
1482 /// If we should emit this as a bunch of and/or'd together conditions, return
1485 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1486 if (Cases.size() != 2) return true;
1488 // If this is two comparisons of the same values or'd or and'd together, they
1489 // will get folded into a single comparison, so don't emit two blocks.
1490 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1491 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1492 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1493 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1497 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1498 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1499 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1500 Cases[0].CC == Cases[1].CC &&
1501 isa<Constant>(Cases[0].CmpRHS) &&
1502 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1503 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1505 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1512 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1513 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1515 // Update machine-CFG edges.
1516 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1518 // Figure out which block is immediately after the current one.
1519 MachineBasicBlock *NextBlock = 0;
1520 MachineFunction::iterator BBI = BrMBB;
1521 if (++BBI != FuncInfo.MF->end())
1524 if (I.isUnconditional()) {
1525 // Update machine-CFG edges.
1526 BrMBB->addSuccessor(Succ0MBB);
1528 // If this is not a fall-through branch, emit the branch.
1529 if (Succ0MBB != NextBlock)
1530 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1531 MVT::Other, getControlRoot(),
1532 DAG.getBasicBlock(Succ0MBB)));
1537 // If this condition is one of the special cases we handle, do special stuff
1539 const Value *CondVal = I.getCondition();
1540 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1542 // If this is a series of conditions that are or'd or and'd together, emit
1543 // this as a sequence of branches instead of setcc's with and/or operations.
1544 // As long as jumps are not expensive, this should improve performance.
1545 // For example, instead of something like:
1558 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1559 if (!TM.getTargetLowering()->isJumpExpensive() &&
1561 (BOp->getOpcode() == Instruction::And ||
1562 BOp->getOpcode() == Instruction::Or)) {
1563 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1565 // If the compares in later blocks need to use values not currently
1566 // exported from this block, export them now. This block should always
1567 // be the first entry.
1568 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1570 // Allow some cases to be rejected.
1571 if (ShouldEmitAsBranches(SwitchCases)) {
1572 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1573 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1574 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1577 // Emit the branch for this block.
1578 visitSwitchCase(SwitchCases[0], BrMBB);
1579 SwitchCases.erase(SwitchCases.begin());
1583 // Okay, we decided not to do this, remove any inserted MBB's and clear
1585 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1586 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1588 SwitchCases.clear();
1592 // Create a CaseBlock record representing this branch.
1593 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1594 NULL, Succ0MBB, Succ1MBB, BrMBB);
1596 // Use visitSwitchCase to actually insert the fast branch sequence for this
1598 visitSwitchCase(CB, BrMBB);
1601 /// visitSwitchCase - Emits the necessary code to represent a single node in
1602 /// the binary search tree resulting from lowering a switch instruction.
1603 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1604 MachineBasicBlock *SwitchBB) {
1606 SDValue CondLHS = getValue(CB.CmpLHS);
1607 SDLoc dl = getCurSDLoc();
1609 // Build the setcc now.
1610 if (CB.CmpMHS == NULL) {
1611 // Fold "(X == true)" to X and "(X == false)" to !X to
1612 // handle common cases produced by branch lowering.
1613 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1614 CB.CC == ISD::SETEQ)
1616 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1617 CB.CC == ISD::SETEQ) {
1618 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1619 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1621 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1623 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1625 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1626 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1628 SDValue CmpOp = getValue(CB.CmpMHS);
1629 EVT VT = CmpOp.getValueType();
1631 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1632 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1635 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1636 VT, CmpOp, DAG.getConstant(Low, VT));
1637 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1638 DAG.getConstant(High-Low, VT), ISD::SETULE);
1642 // Update successor info
1643 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1644 // TrueBB and FalseBB are always different unless the incoming IR is
1645 // degenerate. This only happens when running llc on weird IR.
1646 if (CB.TrueBB != CB.FalseBB)
1647 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1649 // Set NextBlock to be the MBB immediately after the current one, if any.
1650 // This is used to avoid emitting unnecessary branches to the next block.
1651 MachineBasicBlock *NextBlock = 0;
1652 MachineFunction::iterator BBI = SwitchBB;
1653 if (++BBI != FuncInfo.MF->end())
1656 // If the lhs block is the next block, invert the condition so that we can
1657 // fall through to the lhs instead of the rhs block.
1658 if (CB.TrueBB == NextBlock) {
1659 std::swap(CB.TrueBB, CB.FalseBB);
1660 SDValue True = DAG.getConstant(1, Cond.getValueType());
1661 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1664 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1665 MVT::Other, getControlRoot(), Cond,
1666 DAG.getBasicBlock(CB.TrueBB));
1668 // Insert the false branch. Do this even if it's a fall through branch,
1669 // this makes it easier to do DAG optimizations which require inverting
1670 // the branch condition.
1671 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1672 DAG.getBasicBlock(CB.FalseBB));
1674 DAG.setRoot(BrCond);
1677 /// visitJumpTable - Emit JumpTable node in the current MBB
1678 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1679 // Emit the code for the jump table
1680 assert(JT.Reg != -1U && "Should lower JT Header first!");
1681 EVT PTy = TM.getTargetLowering()->getPointerTy();
1682 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1684 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1685 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1686 MVT::Other, Index.getValue(1),
1688 DAG.setRoot(BrJumpTable);
1691 /// visitJumpTableHeader - This function emits necessary code to produce index
1692 /// in the JumpTable from switch case.
1693 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1694 JumpTableHeader &JTH,
1695 MachineBasicBlock *SwitchBB) {
1696 // Subtract the lowest switch case value from the value being switched on and
1697 // conditional branch to default mbb if the result is greater than the
1698 // difference between smallest and largest cases.
1699 SDValue SwitchOp = getValue(JTH.SValue);
1700 EVT VT = SwitchOp.getValueType();
1701 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1702 DAG.getConstant(JTH.First, VT));
1704 // The SDNode we just created, which holds the value being switched on minus
1705 // the smallest case value, needs to be copied to a virtual register so it
1706 // can be used as an index into the jump table in a subsequent basic block.
1707 // This value may be smaller or larger than the target's pointer type, and
1708 // therefore require extension or truncating.
1709 const TargetLowering *TLI = TM.getTargetLowering();
1710 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
1712 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
1713 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1714 JumpTableReg, SwitchOp);
1715 JT.Reg = JumpTableReg;
1717 // Emit the range check for the jump table, and branch to the default block
1718 // for the switch statement if the value being switched on exceeds the largest
1719 // case in the switch.
1720 SDValue CMP = DAG.getSetCC(getCurSDLoc(),
1721 TLI->getSetCCResultType(*DAG.getContext(),
1722 Sub.getValueType()),
1724 DAG.getConstant(JTH.Last - JTH.First,VT),
1727 // Set NextBlock to be the MBB immediately after the current one, if any.
1728 // This is used to avoid emitting unnecessary branches to the next block.
1729 MachineBasicBlock *NextBlock = 0;
1730 MachineFunction::iterator BBI = SwitchBB;
1732 if (++BBI != FuncInfo.MF->end())
1735 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1736 MVT::Other, CopyTo, CMP,
1737 DAG.getBasicBlock(JT.Default));
1739 if (JT.MBB != NextBlock)
1740 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1741 DAG.getBasicBlock(JT.MBB));
1743 DAG.setRoot(BrCond);
1746 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1747 /// tail spliced into a stack protector check success bb.
1749 /// For a high level explanation of how this fits into the stack protector
1750 /// generation see the comment on the declaration of class
1751 /// StackProtectorDescriptor.
1752 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1753 MachineBasicBlock *ParentBB) {
1755 // First create the loads to the guard/stack slot for the comparison.
1756 const TargetLowering *TLI = TM.getTargetLowering();
1757 EVT PtrTy = TLI->getPointerTy();
1759 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1760 int FI = MFI->getStackProtectorIndex();
1762 const Value *IRGuard = SPD.getGuard();
1763 SDValue GuardPtr = getValue(IRGuard);
1764 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1767 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1768 SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1769 GuardPtr, MachinePointerInfo(IRGuard, 0),
1770 true, false, false, Align);
1772 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1774 MachinePointerInfo::getFixedStack(FI),
1775 true, false, false, Align);
1777 // Perform the comparison via a subtract/getsetcc.
1778 EVT VT = Guard.getValueType();
1779 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1781 SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
1782 TLI->getSetCCResultType(*DAG.getContext(),
1783 Sub.getValueType()),
1784 Sub, DAG.getConstant(0, VT),
1787 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1788 // branch to failure MBB.
1789 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1790 MVT::Other, StackSlot.getOperand(0),
1791 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1792 // Otherwise branch to success MBB.
1793 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1795 DAG.getBasicBlock(SPD.getSuccessMBB()));
1800 /// Codegen the failure basic block for a stack protector check.
1802 /// A failure stack protector machine basic block consists simply of a call to
1803 /// __stack_chk_fail().
1805 /// For a high level explanation of how this fits into the stack protector
1806 /// generation see the comment on the declaration of class
1807 /// StackProtectorDescriptor.
1809 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1810 const TargetLowering *TLI = TM.getTargetLowering();
1811 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
1812 MVT::isVoid, 0, 0, false, getCurSDLoc(),
1813 false, false).second;
1817 /// visitBitTestHeader - This function emits necessary code to produce value
1818 /// suitable for "bit tests"
1819 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1820 MachineBasicBlock *SwitchBB) {
1821 // Subtract the minimum value
1822 SDValue SwitchOp = getValue(B.SValue);
1823 EVT VT = SwitchOp.getValueType();
1824 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1825 DAG.getConstant(B.First, VT));
1828 const TargetLowering *TLI = TM.getTargetLowering();
1829 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
1830 TLI->getSetCCResultType(*DAG.getContext(),
1831 Sub.getValueType()),
1832 Sub, DAG.getConstant(B.Range, VT),
1835 // Determine the type of the test operands.
1836 bool UsePtrType = false;
1837 if (!TLI->isTypeLegal(VT))
1840 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1841 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1842 // Switch table case range are encoded into series of masks.
1843 // Just use pointer type, it's guaranteed to fit.
1849 VT = TLI->getPointerTy();
1850 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1853 B.RegVT = VT.getSimpleVT();
1854 B.Reg = FuncInfo.CreateReg(B.RegVT);
1855 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1858 // Set NextBlock to be the MBB immediately after the current one, if any.
1859 // This is used to avoid emitting unnecessary branches to the next block.
1860 MachineBasicBlock *NextBlock = 0;
1861 MachineFunction::iterator BBI = SwitchBB;
1862 if (++BBI != FuncInfo.MF->end())
1865 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1867 addSuccessorWithWeight(SwitchBB, B.Default);
1868 addSuccessorWithWeight(SwitchBB, MBB);
1870 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1871 MVT::Other, CopyTo, RangeCmp,
1872 DAG.getBasicBlock(B.Default));
1874 if (MBB != NextBlock)
1875 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1876 DAG.getBasicBlock(MBB));
1878 DAG.setRoot(BrRange);
1881 /// visitBitTestCase - this function produces one "bit test"
1882 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1883 MachineBasicBlock* NextMBB,
1884 uint32_t BranchWeightToNext,
1887 MachineBasicBlock *SwitchBB) {
1889 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1892 unsigned PopCount = CountPopulation_64(B.Mask);
1893 const TargetLowering *TLI = TM.getTargetLowering();
1894 if (PopCount == 1) {
1895 // Testing for a single bit; just compare the shift count with what it
1896 // would need to be to shift a 1 bit in that position.
1897 Cmp = DAG.getSetCC(getCurSDLoc(),
1898 TLI->getSetCCResultType(*DAG.getContext(), VT),
1900 DAG.getConstant(countTrailingZeros(B.Mask), VT),
1902 } else if (PopCount == BB.Range) {
1903 // There is only one zero bit in the range, test for it directly.
1904 Cmp = DAG.getSetCC(getCurSDLoc(),
1905 TLI->getSetCCResultType(*DAG.getContext(), VT),
1907 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1910 // Make desired shift
1911 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1912 DAG.getConstant(1, VT), ShiftOp);
1914 // Emit bit tests and jumps
1915 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1916 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1917 Cmp = DAG.getSetCC(getCurSDLoc(),
1918 TLI->getSetCCResultType(*DAG.getContext(), VT),
1919 AndOp, DAG.getConstant(0, VT),
1923 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1924 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1925 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1926 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1928 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1929 MVT::Other, getControlRoot(),
1930 Cmp, DAG.getBasicBlock(B.TargetBB));
1932 // Set NextBlock to be the MBB immediately after the current one, if any.
1933 // This is used to avoid emitting unnecessary branches to the next block.
1934 MachineBasicBlock *NextBlock = 0;
1935 MachineFunction::iterator BBI = SwitchBB;
1936 if (++BBI != FuncInfo.MF->end())
1939 if (NextMBB != NextBlock)
1940 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1941 DAG.getBasicBlock(NextMBB));
1946 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1947 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1949 // Retrieve successors.
1950 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1951 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1953 const Value *Callee(I.getCalledValue());
1954 const Function *Fn = dyn_cast<Function>(Callee);
1955 if (isa<InlineAsm>(Callee))
1957 else if (Fn && Fn->isIntrinsic()) {
1958 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
1959 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
1961 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1963 // If the value of the invoke is used outside of its defining block, make it
1964 // available as a virtual register.
1965 CopyToExportRegsIfNeeded(&I);
1967 // Update successor info
1968 addSuccessorWithWeight(InvokeMBB, Return);
1969 addSuccessorWithWeight(InvokeMBB, LandingPad);
1971 // Drop into normal successor.
1972 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1973 MVT::Other, getControlRoot(),
1974 DAG.getBasicBlock(Return)));
1977 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1978 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1981 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1982 assert(FuncInfo.MBB->isLandingPad() &&
1983 "Call to landingpad not in landing pad!");
1985 MachineBasicBlock *MBB = FuncInfo.MBB;
1986 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1987 AddLandingPadInfo(LP, MMI, MBB);
1989 // If there aren't registers to copy the values into (e.g., during SjLj
1990 // exceptions), then don't bother to create these DAG nodes.
1991 const TargetLowering *TLI = TM.getTargetLowering();
1992 if (TLI->getExceptionPointerRegister() == 0 &&
1993 TLI->getExceptionSelectorRegister() == 0)
1996 SmallVector<EVT, 2> ValueVTs;
1997 ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
1998 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2000 // Get the two live-in registers as SDValues. The physregs have already been
2001 // copied into virtual registers.
2003 Ops[0] = DAG.getZExtOrTrunc(
2004 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2005 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
2006 getCurSDLoc(), ValueVTs[0]);
2007 Ops[1] = DAG.getZExtOrTrunc(
2008 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2009 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
2010 getCurSDLoc(), ValueVTs[1]);
2013 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2014 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
2019 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2020 /// small case ranges).
2021 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2022 CaseRecVector& WorkList,
2024 MachineBasicBlock *Default,
2025 MachineBasicBlock *SwitchBB) {
2026 // Size is the number of Cases represented by this range.
2027 size_t Size = CR.Range.second - CR.Range.first;
2031 // Get the MachineFunction which holds the current MBB. This is used when
2032 // inserting any additional MBBs necessary to represent the switch.
2033 MachineFunction *CurMF = FuncInfo.MF;
2035 // Figure out which block is immediately after the current one.
2036 MachineBasicBlock *NextBlock = 0;
2037 MachineFunction::iterator BBI = CR.CaseBB;
2039 if (++BBI != FuncInfo.MF->end())
2042 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2043 // If any two of the cases has the same destination, and if one value
2044 // is the same as the other, but has one bit unset that the other has set,
2045 // use bit manipulation to do two compares at once. For example:
2046 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2047 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2048 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2049 if (Size == 2 && CR.CaseBB == SwitchBB) {
2050 Case &Small = *CR.Range.first;
2051 Case &Big = *(CR.Range.second-1);
2053 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2054 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2055 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2057 // Check that there is only one bit different.
2058 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2059 (SmallValue | BigValue) == BigValue) {
2060 // Isolate the common bit.
2061 APInt CommonBit = BigValue & ~SmallValue;
2062 assert((SmallValue | CommonBit) == BigValue &&
2063 CommonBit.countPopulation() == 1 && "Not a common bit?");
2065 SDValue CondLHS = getValue(SV);
2066 EVT VT = CondLHS.getValueType();
2067 SDLoc DL = getCurSDLoc();
2069 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2070 DAG.getConstant(CommonBit, VT));
2071 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2072 Or, DAG.getConstant(BigValue, VT),
2075 // Update successor info.
2076 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2077 addSuccessorWithWeight(SwitchBB, Small.BB,
2078 Small.ExtraWeight + Big.ExtraWeight);
2079 addSuccessorWithWeight(SwitchBB, Default,
2080 // The default destination is the first successor in IR.
2081 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2083 // Insert the true branch.
2084 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2085 getControlRoot(), Cond,
2086 DAG.getBasicBlock(Small.BB));
2088 // Insert the false branch.
2089 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2090 DAG.getBasicBlock(Default));
2092 DAG.setRoot(BrCond);
2098 // Order cases by weight so the most likely case will be checked first.
2099 uint32_t UnhandledWeights = 0;
2101 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2102 uint32_t IWeight = I->ExtraWeight;
2103 UnhandledWeights += IWeight;
2104 for (CaseItr J = CR.Range.first; J < I; ++J) {
2105 uint32_t JWeight = J->ExtraWeight;
2106 if (IWeight > JWeight)
2111 // Rearrange the case blocks so that the last one falls through if possible.
2112 Case &BackCase = *(CR.Range.second-1);
2114 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2115 // The last case block won't fall through into 'NextBlock' if we emit the
2116 // branches in this order. See if rearranging a case value would help.
2117 // We start at the bottom as it's the case with the least weight.
2118 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2119 if (I->BB == NextBlock) {
2120 std::swap(*I, BackCase);
2125 // Create a CaseBlock record representing a conditional branch to
2126 // the Case's target mbb if the value being switched on SV is equal
2128 MachineBasicBlock *CurBlock = CR.CaseBB;
2129 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2130 MachineBasicBlock *FallThrough;
2132 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2133 CurMF->insert(BBI, FallThrough);
2135 // Put SV in a virtual register to make it available from the new blocks.
2136 ExportFromCurrentBlock(SV);
2138 // If the last case doesn't match, go to the default block.
2139 FallThrough = Default;
2142 const Value *RHS, *LHS, *MHS;
2144 if (I->High == I->Low) {
2145 // This is just small small case range :) containing exactly 1 case
2147 LHS = SV; RHS = I->High; MHS = NULL;
2150 LHS = I->Low; MHS = SV; RHS = I->High;
2153 // The false weight should be sum of all un-handled cases.
2154 UnhandledWeights -= I->ExtraWeight;
2155 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2157 /* trueweight */ I->ExtraWeight,
2158 /* falseweight */ UnhandledWeights);
2160 // If emitting the first comparison, just call visitSwitchCase to emit the
2161 // code into the current block. Otherwise, push the CaseBlock onto the
2162 // vector to be later processed by SDISel, and insert the node's MBB
2163 // before the next MBB.
2164 if (CurBlock == SwitchBB)
2165 visitSwitchCase(CB, SwitchBB);
2167 SwitchCases.push_back(CB);
2169 CurBlock = FallThrough;
2175 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2176 return TLI.supportJumpTables() &&
2177 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2178 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
2181 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2182 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2183 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2184 return (LastExt - FirstExt + 1ULL);
2187 /// handleJTSwitchCase - Emit jumptable for current switch case range
2188 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2189 CaseRecVector &WorkList,
2191 MachineBasicBlock *Default,
2192 MachineBasicBlock *SwitchBB) {
2193 Case& FrontCase = *CR.Range.first;
2194 Case& BackCase = *(CR.Range.second-1);
2196 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2197 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2199 APInt TSize(First.getBitWidth(), 0);
2200 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2203 const TargetLowering *TLI = TM.getTargetLowering();
2204 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
2207 APInt Range = ComputeRange(First, Last);
2208 // The density is TSize / Range. Require at least 40%.
2209 // It should not be possible for IntTSize to saturate for sane code, but make
2210 // sure we handle Range saturation correctly.
2211 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2212 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2213 if (IntTSize * 10 < IntRange * 4)
2216 DEBUG(dbgs() << "Lowering jump table\n"
2217 << "First entry: " << First << ". Last entry: " << Last << '\n'
2218 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2220 // Get the MachineFunction which holds the current MBB. This is used when
2221 // inserting any additional MBBs necessary to represent the switch.
2222 MachineFunction *CurMF = FuncInfo.MF;
2224 // Figure out which block is immediately after the current one.
2225 MachineFunction::iterator BBI = CR.CaseBB;
2228 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2230 // Create a new basic block to hold the code for loading the address
2231 // of the jump table, and jumping to it. Update successor information;
2232 // we will either branch to the default case for the switch, or the jump
2234 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2235 CurMF->insert(BBI, JumpTableBB);
2237 addSuccessorWithWeight(CR.CaseBB, Default);
2238 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2240 // Build a vector of destination BBs, corresponding to each target
2241 // of the jump table. If the value of the jump table slot corresponds to
2242 // a case statement, push the case's BB onto the vector, otherwise, push
2244 std::vector<MachineBasicBlock*> DestBBs;
2246 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2247 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2248 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2250 if (Low.sle(TEI) && TEI.sle(High)) {
2251 DestBBs.push_back(I->BB);
2255 DestBBs.push_back(Default);
2259 // Calculate weight for each unique destination in CR.
2260 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2262 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2263 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2264 DestWeights.find(I->BB);
2265 if (Itr != DestWeights.end())
2266 Itr->second += I->ExtraWeight;
2268 DestWeights[I->BB] = I->ExtraWeight;
2271 // Update successor info. Add one edge to each unique successor.
2272 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2273 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2274 E = DestBBs.end(); I != E; ++I) {
2275 if (!SuccsHandled[(*I)->getNumber()]) {
2276 SuccsHandled[(*I)->getNumber()] = true;
2277 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2278 DestWeights.find(*I);
2279 addSuccessorWithWeight(JumpTableBB, *I,
2280 Itr != DestWeights.end() ? Itr->second : 0);
2284 // Create a jump table index for this jump table.
2285 unsigned JTEncoding = TLI->getJumpTableEncoding();
2286 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2287 ->createJumpTableIndex(DestBBs);
2289 // Set the jump table information so that we can codegen it as a second
2290 // MachineBasicBlock
2291 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2292 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2293 if (CR.CaseBB == SwitchBB)
2294 visitJumpTableHeader(JT, JTH, SwitchBB);
2296 JTCases.push_back(JumpTableBlock(JTH, JT));
2300 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2302 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2303 CaseRecVector& WorkList,
2305 MachineBasicBlock* Default,
2306 MachineBasicBlock* SwitchBB) {
2307 // Get the MachineFunction which holds the current MBB. This is used when
2308 // inserting any additional MBBs necessary to represent the switch.
2309 MachineFunction *CurMF = FuncInfo.MF;
2311 // Figure out which block is immediately after the current one.
2312 MachineFunction::iterator BBI = CR.CaseBB;
2315 Case& FrontCase = *CR.Range.first;
2316 Case& BackCase = *(CR.Range.second-1);
2317 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2319 // Size is the number of Cases represented by this range.
2320 unsigned Size = CR.Range.second - CR.Range.first;
2322 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2323 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2325 CaseItr Pivot = CR.Range.first + Size/2;
2327 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2328 // (heuristically) allow us to emit JumpTable's later.
2329 APInt TSize(First.getBitWidth(), 0);
2330 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2334 APInt LSize = FrontCase.size();
2335 APInt RSize = TSize-LSize;
2336 DEBUG(dbgs() << "Selecting best pivot: \n"
2337 << "First: " << First << ", Last: " << Last <<'\n'
2338 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2339 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2341 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2342 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2343 APInt Range = ComputeRange(LEnd, RBegin);
2344 assert((Range - 2ULL).isNonNegative() &&
2345 "Invalid case distance");
2346 // Use volatile double here to avoid excess precision issues on some hosts,
2347 // e.g. that use 80-bit X87 registers.
2348 volatile double LDensity =
2349 (double)LSize.roundToDouble() /
2350 (LEnd - First + 1ULL).roundToDouble();
2351 volatile double RDensity =
2352 (double)RSize.roundToDouble() /
2353 (Last - RBegin + 1ULL).roundToDouble();
2354 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
2355 // Should always split in some non-trivial place
2356 DEBUG(dbgs() <<"=>Step\n"
2357 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2358 << "LDensity: " << LDensity
2359 << ", RDensity: " << RDensity << '\n'
2360 << "Metric: " << Metric << '\n');
2361 if (FMetric < Metric) {
2364 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2371 const TargetLowering *TLI = TM.getTargetLowering();
2372 if (areJTsAllowed(*TLI)) {
2373 // If our case is dense we *really* should handle it earlier!
2374 assert((FMetric > 0) && "Should handle dense range earlier!");
2376 Pivot = CR.Range.first + Size/2;
2379 CaseRange LHSR(CR.Range.first, Pivot);
2380 CaseRange RHSR(Pivot, CR.Range.second);
2381 const Constant *C = Pivot->Low;
2382 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2384 // We know that we branch to the LHS if the Value being switched on is
2385 // less than the Pivot value, C. We use this to optimize our binary
2386 // tree a bit, by recognizing that if SV is greater than or equal to the
2387 // LHS's Case Value, and that Case Value is exactly one less than the
2388 // Pivot's Value, then we can branch directly to the LHS's Target,
2389 // rather than creating a leaf node for it.
2390 if ((LHSR.second - LHSR.first) == 1 &&
2391 LHSR.first->High == CR.GE &&
2392 cast<ConstantInt>(C)->getValue() ==
2393 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2394 TrueBB = LHSR.first->BB;
2396 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2397 CurMF->insert(BBI, TrueBB);
2398 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2400 // Put SV in a virtual register to make it available from the new blocks.
2401 ExportFromCurrentBlock(SV);
2404 // Similar to the optimization above, if the Value being switched on is
2405 // known to be less than the Constant CR.LT, and the current Case Value
2406 // is CR.LT - 1, then we can branch directly to the target block for
2407 // the current Case Value, rather than emitting a RHS leaf node for it.
2408 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2409 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2410 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2411 FalseBB = RHSR.first->BB;
2413 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2414 CurMF->insert(BBI, FalseBB);
2415 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2417 // Put SV in a virtual register to make it available from the new blocks.
2418 ExportFromCurrentBlock(SV);
2421 // Create a CaseBlock record representing a conditional branch to
2422 // the LHS node if the value being switched on SV is less than C.
2423 // Otherwise, branch to LHS.
2424 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2426 if (CR.CaseBB == SwitchBB)
2427 visitSwitchCase(CB, SwitchBB);
2429 SwitchCases.push_back(CB);
2434 /// handleBitTestsSwitchCase - if current case range has few destination and
2435 /// range span less, than machine word bitwidth, encode case range into series
2436 /// of masks and emit bit tests with these masks.
2437 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2438 CaseRecVector& WorkList,
2440 MachineBasicBlock* Default,
2441 MachineBasicBlock* SwitchBB) {
2442 const TargetLowering *TLI = TM.getTargetLowering();
2443 EVT PTy = TLI->getPointerTy();
2444 unsigned IntPtrBits = PTy.getSizeInBits();
2446 Case& FrontCase = *CR.Range.first;
2447 Case& BackCase = *(CR.Range.second-1);
2449 // Get the MachineFunction which holds the current MBB. This is used when
2450 // inserting any additional MBBs necessary to represent the switch.
2451 MachineFunction *CurMF = FuncInfo.MF;
2453 // If target does not have legal shift left, do not emit bit tests at all.
2454 if (!TLI->isOperationLegal(ISD::SHL, PTy))
2458 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2460 // Single case counts one, case range - two.
2461 numCmps += (I->Low == I->High ? 1 : 2);
2464 // Count unique destinations
2465 SmallSet<MachineBasicBlock*, 4> Dests;
2466 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2467 Dests.insert(I->BB);
2468 if (Dests.size() > 3)
2469 // Don't bother the code below, if there are too much unique destinations
2472 DEBUG(dbgs() << "Total number of unique destinations: "
2473 << Dests.size() << '\n'
2474 << "Total number of comparisons: " << numCmps << '\n');
2476 // Compute span of values.
2477 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2478 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2479 APInt cmpRange = maxValue - minValue;
2481 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2482 << "Low bound: " << minValue << '\n'
2483 << "High bound: " << maxValue << '\n');
2485 if (cmpRange.uge(IntPtrBits) ||
2486 (!(Dests.size() == 1 && numCmps >= 3) &&
2487 !(Dests.size() == 2 && numCmps >= 5) &&
2488 !(Dests.size() >= 3 && numCmps >= 6)))
2491 DEBUG(dbgs() << "Emitting bit tests\n");
2492 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2494 // Optimize the case where all the case values fit in a
2495 // word without having to subtract minValue. In this case,
2496 // we can optimize away the subtraction.
2497 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2498 cmpRange = maxValue;
2500 lowBound = minValue;
2503 CaseBitsVector CasesBits;
2504 unsigned i, count = 0;
2506 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2507 MachineBasicBlock* Dest = I->BB;
2508 for (i = 0; i < count; ++i)
2509 if (Dest == CasesBits[i].BB)
2513 assert((count < 3) && "Too much destinations to test!");
2514 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2518 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2519 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2521 uint64_t lo = (lowValue - lowBound).getZExtValue();
2522 uint64_t hi = (highValue - lowBound).getZExtValue();
2523 CasesBits[i].ExtraWeight += I->ExtraWeight;
2525 for (uint64_t j = lo; j <= hi; j++) {
2526 CasesBits[i].Mask |= 1ULL << j;
2527 CasesBits[i].Bits++;
2531 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2535 // Figure out which block is immediately after the current one.
2536 MachineFunction::iterator BBI = CR.CaseBB;
2539 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2541 DEBUG(dbgs() << "Cases:\n");
2542 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2543 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2544 << ", Bits: " << CasesBits[i].Bits
2545 << ", BB: " << CasesBits[i].BB << '\n');
2547 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2548 CurMF->insert(BBI, CaseBB);
2549 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2551 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2553 // Put SV in a virtual register to make it available from the new blocks.
2554 ExportFromCurrentBlock(SV);
2557 BitTestBlock BTB(lowBound, cmpRange, SV,
2558 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2559 CR.CaseBB, Default, BTC);
2561 if (CR.CaseBB == SwitchBB)
2562 visitBitTestHeader(BTB, SwitchBB);
2564 BitTestCases.push_back(BTB);
2569 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2570 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2571 const SwitchInst& SI) {
2574 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2575 // Start with "simple" cases
2576 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2578 const BasicBlock *SuccBB = i.getCaseSuccessor();
2579 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2581 uint32_t ExtraWeight =
2582 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2584 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2585 SMBB, ExtraWeight));
2587 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2589 // Merge case into clusters
2590 if (Cases.size() >= 2)
2591 // Must recompute end() each iteration because it may be
2592 // invalidated by erase if we hold on to it
2593 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2594 J != Cases.end(); ) {
2595 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2596 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2597 MachineBasicBlock* nextBB = J->BB;
2598 MachineBasicBlock* currentBB = I->BB;
2600 // If the two neighboring cases go to the same destination, merge them
2601 // into a single case.
2602 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2604 I->ExtraWeight += J->ExtraWeight;
2611 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2612 if (I->Low != I->High)
2613 // A range counts double, since it requires two compares.
2620 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2621 MachineBasicBlock *Last) {
2623 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2624 if (JTCases[i].first.HeaderBB == First)
2625 JTCases[i].first.HeaderBB = Last;
2627 // Update BitTestCases.
2628 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2629 if (BitTestCases[i].Parent == First)
2630 BitTestCases[i].Parent = Last;
2633 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2634 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2636 // Figure out which block is immediately after the current one.
2637 MachineBasicBlock *NextBlock = 0;
2638 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2640 // If there is only the default destination, branch to it if it is not the
2641 // next basic block. Otherwise, just fall through.
2642 if (!SI.getNumCases()) {
2643 // Update machine-CFG edges.
2645 // If this is not a fall-through branch, emit the branch.
2646 SwitchMBB->addSuccessor(Default);
2647 if (Default != NextBlock)
2648 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2649 MVT::Other, getControlRoot(),
2650 DAG.getBasicBlock(Default)));
2655 // If there are any non-default case statements, create a vector of Cases
2656 // representing each one, and sort the vector so that we can efficiently
2657 // create a binary search tree from them.
2659 size_t numCmps = Clusterify(Cases, SI);
2660 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2661 << ". Total compares: " << numCmps << '\n');
2664 // Get the Value to be switched on and default basic blocks, which will be
2665 // inserted into CaseBlock records, representing basic blocks in the binary
2667 const Value *SV = SI.getCondition();
2669 // Push the initial CaseRec onto the worklist
2670 CaseRecVector WorkList;
2671 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2672 CaseRange(Cases.begin(),Cases.end())));
2674 while (!WorkList.empty()) {
2675 // Grab a record representing a case range to process off the worklist
2676 CaseRec CR = WorkList.back();
2677 WorkList.pop_back();
2679 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2682 // If the range has few cases (two or less) emit a series of specific
2684 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2687 // If the switch has more than N blocks, and is at least 40% dense, and the
2688 // target supports indirect branches, then emit a jump table rather than
2689 // lowering the switch to a binary tree of conditional branches.
2690 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2691 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2694 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2695 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2696 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2700 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2701 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2703 // Update machine-CFG edges with unique successors.
2704 SmallSet<BasicBlock*, 32> Done;
2705 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2706 BasicBlock *BB = I.getSuccessor(i);
2707 bool Inserted = Done.insert(BB);
2711 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2712 addSuccessorWithWeight(IndirectBrMBB, Succ);
2715 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2716 MVT::Other, getControlRoot(),
2717 getValue(I.getAddress())));
2720 void SelectionDAGBuilder::visitFSub(const User &I) {
2721 // -0.0 - X --> fneg
2722 Type *Ty = I.getType();
2723 if (isa<Constant>(I.getOperand(0)) &&
2724 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2725 SDValue Op2 = getValue(I.getOperand(1));
2726 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2727 Op2.getValueType(), Op2));
2731 visitBinary(I, ISD::FSUB);
2734 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2735 SDValue Op1 = getValue(I.getOperand(0));
2736 SDValue Op2 = getValue(I.getOperand(1));
2737 setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
2738 Op1.getValueType(), Op1, Op2));
2741 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2742 SDValue Op1 = getValue(I.getOperand(0));
2743 SDValue Op2 = getValue(I.getOperand(1));
2745 EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
2747 // Coerce the shift amount to the right type if we can.
2748 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2749 unsigned ShiftSize = ShiftTy.getSizeInBits();
2750 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2751 SDLoc DL = getCurSDLoc();
2753 // If the operand is smaller than the shift count type, promote it.
2754 if (ShiftSize > Op2Size)
2755 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2757 // If the operand is larger than the shift count type but the shift
2758 // count type has enough bits to represent any shift value, truncate
2759 // it now. This is a common case and it exposes the truncate to
2760 // optimization early.
2761 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2762 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2763 // Otherwise we'll need to temporarily settle for some other convenient
2764 // type. Type legalization will make adjustments once the shiftee is split.
2766 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2769 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
2770 Op1.getValueType(), Op1, Op2));
2773 void SelectionDAGBuilder::visitSDiv(const User &I) {
2774 SDValue Op1 = getValue(I.getOperand(0));
2775 SDValue Op2 = getValue(I.getOperand(1));
2777 // Turn exact SDivs into multiplications.
2778 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2780 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2781 !isa<ConstantSDNode>(Op1) &&
2782 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2783 setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
2784 getCurSDLoc(), DAG));
2786 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2790 void SelectionDAGBuilder::visitICmp(const User &I) {
2791 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2792 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2793 predicate = IC->getPredicate();
2794 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2795 predicate = ICmpInst::Predicate(IC->getPredicate());
2796 SDValue Op1 = getValue(I.getOperand(0));
2797 SDValue Op2 = getValue(I.getOperand(1));
2798 ISD::CondCode Opcode = getICmpCondCode(predicate);
2800 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2801 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2804 void SelectionDAGBuilder::visitFCmp(const User &I) {
2805 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2806 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2807 predicate = FC->getPredicate();
2808 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2809 predicate = FCmpInst::Predicate(FC->getPredicate());
2810 SDValue Op1 = getValue(I.getOperand(0));
2811 SDValue Op2 = getValue(I.getOperand(1));
2812 ISD::CondCode Condition = getFCmpCondCode(predicate);
2813 if (TM.Options.NoNaNsFPMath)
2814 Condition = getFCmpCodeWithoutNaN(Condition);
2815 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2816 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2819 void SelectionDAGBuilder::visitSelect(const User &I) {
2820 SmallVector<EVT, 4> ValueVTs;
2821 ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
2822 unsigned NumValues = ValueVTs.size();
2823 if (NumValues == 0) return;
2825 SmallVector<SDValue, 4> Values(NumValues);
2826 SDValue Cond = getValue(I.getOperand(0));
2827 SDValue TrueVal = getValue(I.getOperand(1));
2828 SDValue FalseVal = getValue(I.getOperand(2));
2829 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2830 ISD::VSELECT : ISD::SELECT;
2832 for (unsigned i = 0; i != NumValues; ++i)
2833 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2834 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2836 SDValue(TrueVal.getNode(),
2837 TrueVal.getResNo() + i),
2838 SDValue(FalseVal.getNode(),
2839 FalseVal.getResNo() + i));
2841 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2842 DAG.getVTList(&ValueVTs[0], NumValues),
2843 &Values[0], NumValues));
2846 void SelectionDAGBuilder::visitTrunc(const User &I) {
2847 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2848 SDValue N = getValue(I.getOperand(0));
2849 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2850 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2853 void SelectionDAGBuilder::visitZExt(const User &I) {
2854 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2855 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2856 SDValue N = getValue(I.getOperand(0));
2857 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2858 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2861 void SelectionDAGBuilder::visitSExt(const User &I) {
2862 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2863 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2864 SDValue N = getValue(I.getOperand(0));
2865 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2866 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2869 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2870 // FPTrunc is never a no-op cast, no need to check
2871 SDValue N = getValue(I.getOperand(0));
2872 const TargetLowering *TLI = TM.getTargetLowering();
2873 EVT DestVT = TLI->getValueType(I.getType());
2874 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
2876 DAG.getTargetConstant(0, TLI->getPointerTy())));
2879 void SelectionDAGBuilder::visitFPExt(const User &I) {
2880 // FPExt is never a no-op cast, no need to check
2881 SDValue N = getValue(I.getOperand(0));
2882 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2883 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2886 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2887 // FPToUI is never a no-op cast, no need to check
2888 SDValue N = getValue(I.getOperand(0));
2889 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2890 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2893 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2894 // FPToSI is never a no-op cast, no need to check
2895 SDValue N = getValue(I.getOperand(0));
2896 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2897 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2900 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2901 // UIToFP is never a no-op cast, no need to check
2902 SDValue N = getValue(I.getOperand(0));
2903 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2904 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2907 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2908 // SIToFP is never a no-op cast, no need to check
2909 SDValue N = getValue(I.getOperand(0));
2910 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2911 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2914 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2915 // What to do depends on the size of the integer and the size of the pointer.
2916 // We can either truncate, zero extend, or no-op, accordingly.
2917 SDValue N = getValue(I.getOperand(0));
2918 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2919 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2922 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2923 // What to do depends on the size of the integer and the size of the pointer.
2924 // We can either truncate, zero extend, or no-op, accordingly.
2925 SDValue N = getValue(I.getOperand(0));
2926 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2927 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2930 void SelectionDAGBuilder::visitBitCast(const User &I) {
2931 SDValue N = getValue(I.getOperand(0));
2932 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2934 // BitCast assures us that source and destination are the same size so this is
2935 // either a BITCAST or a no-op.
2936 if (DestVT != N.getValueType())
2937 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
2938 DestVT, N)); // convert types.
2940 setValue(&I, N); // noop cast.
2943 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2944 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2945 const Value *SV = I.getOperand(0);
2946 SDValue N = getValue(SV);
2947 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2949 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2950 unsigned DestAS = I.getType()->getPointerAddressSpace();
2952 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2953 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2958 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2959 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2960 SDValue InVec = getValue(I.getOperand(0));
2961 SDValue InVal = getValue(I.getOperand(1));
2962 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
2963 getCurSDLoc(), TLI.getVectorIdxTy());
2964 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2965 TM.getTargetLowering()->getValueType(I.getType()),
2966 InVec, InVal, InIdx));
2969 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2970 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2971 SDValue InVec = getValue(I.getOperand(0));
2972 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
2973 getCurSDLoc(), TLI.getVectorIdxTy());
2974 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2975 TM.getTargetLowering()->getValueType(I.getType()),
2979 // Utility for visitShuffleVector - Return true if every element in Mask,
2980 // beginning from position Pos and ending in Pos+Size, falls within the
2981 // specified sequential range [L, L+Pos). or is undef.
2982 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2983 unsigned Pos, unsigned Size, int Low) {
2984 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2985 if (Mask[i] >= 0 && Mask[i] != Low)
2990 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2991 SDValue Src1 = getValue(I.getOperand(0));
2992 SDValue Src2 = getValue(I.getOperand(1));
2994 SmallVector<int, 8> Mask;
2995 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2996 unsigned MaskNumElts = Mask.size();
2998 const TargetLowering *TLI = TM.getTargetLowering();
2999 EVT VT = TLI->getValueType(I.getType());
3000 EVT SrcVT = Src1.getValueType();
3001 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3003 if (SrcNumElts == MaskNumElts) {
3004 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3009 // Normalize the shuffle vector since mask and vector length don't match.
3010 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3011 // Mask is longer than the source vectors and is a multiple of the source
3012 // vectors. We can use concatenate vector to make the mask and vectors
3014 if (SrcNumElts*2 == MaskNumElts) {
3015 // First check for Src1 in low and Src2 in high
3016 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3017 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3018 // The shuffle is concatenating two vectors together.
3019 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3023 // Then check for Src2 in low and Src1 in high
3024 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3025 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3026 // The shuffle is concatenating two vectors together.
3027 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3033 // Pad both vectors with undefs to make them the same length as the mask.
3034 unsigned NumConcat = MaskNumElts / SrcNumElts;
3035 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3036 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3037 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3039 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3040 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3044 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3046 &MOps1[0], NumConcat);
3047 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3049 &MOps2[0], NumConcat);
3051 // Readjust mask for new input vector length.
3052 SmallVector<int, 8> MappedOps;
3053 for (unsigned i = 0; i != MaskNumElts; ++i) {
3055 if (Idx >= (int)SrcNumElts)
3056 Idx -= SrcNumElts - MaskNumElts;
3057 MappedOps.push_back(Idx);
3060 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3065 if (SrcNumElts > MaskNumElts) {
3066 // Analyze the access pattern of the vector to see if we can extract
3067 // two subvectors and do the shuffle. The analysis is done by calculating
3068 // the range of elements the mask access on both vectors.
3069 int MinRange[2] = { static_cast<int>(SrcNumElts),
3070 static_cast<int>(SrcNumElts)};
3071 int MaxRange[2] = {-1, -1};
3073 for (unsigned i = 0; i != MaskNumElts; ++i) {
3079 if (Idx >= (int)SrcNumElts) {
3083 if (Idx > MaxRange[Input])
3084 MaxRange[Input] = Idx;
3085 if (Idx < MinRange[Input])
3086 MinRange[Input] = Idx;
3089 // Check if the access is smaller than the vector size and can we find
3090 // a reasonable extract index.
3091 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3093 int StartIdx[2]; // StartIdx to extract from
3094 for (unsigned Input = 0; Input < 2; ++Input) {
3095 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3096 RangeUse[Input] = 0; // Unused
3097 StartIdx[Input] = 0;
3101 // Find a good start index that is a multiple of the mask length. Then
3102 // see if the rest of the elements are in range.
3103 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3104 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3105 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3106 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3109 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3110 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3113 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3114 // Extract appropriate subvector and generate a vector shuffle
3115 for (unsigned Input = 0; Input < 2; ++Input) {
3116 SDValue &Src = Input == 0 ? Src1 : Src2;
3117 if (RangeUse[Input] == 0)
3118 Src = DAG.getUNDEF(VT);
3120 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
3121 Src, DAG.getConstant(StartIdx[Input],
3122 TLI->getVectorIdxTy()));
3125 // Calculate new mask.
3126 SmallVector<int, 8> MappedOps;
3127 for (unsigned i = 0; i != MaskNumElts; ++i) {
3130 if (Idx < (int)SrcNumElts)
3133 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3135 MappedOps.push_back(Idx);
3138 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3144 // We can't use either concat vectors or extract subvectors so fall back to
3145 // replacing the shuffle with extract and build vector.
3146 // to insert and build vector.
3147 EVT EltVT = VT.getVectorElementType();
3148 EVT IdxVT = TLI->getVectorIdxTy();
3149 SmallVector<SDValue,8> Ops;
3150 for (unsigned i = 0; i != MaskNumElts; ++i) {
3155 Res = DAG.getUNDEF(EltVT);
3157 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3158 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3160 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3161 EltVT, Src, DAG.getConstant(Idx, IdxVT));
3167 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
3168 VT, &Ops[0], Ops.size()));
3171 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3172 const Value *Op0 = I.getOperand(0);
3173 const Value *Op1 = I.getOperand(1);
3174 Type *AggTy = I.getType();
3175 Type *ValTy = Op1->getType();
3176 bool IntoUndef = isa<UndefValue>(Op0);
3177 bool FromUndef = isa<UndefValue>(Op1);
3179 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3181 const TargetLowering *TLI = TM.getTargetLowering();
3182 SmallVector<EVT, 4> AggValueVTs;
3183 ComputeValueVTs(*TLI, AggTy, AggValueVTs);
3184 SmallVector<EVT, 4> ValValueVTs;
3185 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3187 unsigned NumAggValues = AggValueVTs.size();
3188 unsigned NumValValues = ValValueVTs.size();
3189 SmallVector<SDValue, 4> Values(NumAggValues);
3191 SDValue Agg = getValue(Op0);
3193 // Copy the beginning value(s) from the original aggregate.
3194 for (; i != LinearIndex; ++i)
3195 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3196 SDValue(Agg.getNode(), Agg.getResNo() + i);
3197 // Copy values from the inserted value(s).
3199 SDValue Val = getValue(Op1);
3200 for (; i != LinearIndex + NumValValues; ++i)
3201 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3202 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3204 // Copy remaining value(s) from the original aggregate.
3205 for (; i != NumAggValues; ++i)
3206 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3207 SDValue(Agg.getNode(), Agg.getResNo() + i);
3209 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3210 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3211 &Values[0], NumAggValues));
3214 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3215 const Value *Op0 = I.getOperand(0);
3216 Type *AggTy = Op0->getType();
3217 Type *ValTy = I.getType();
3218 bool OutOfUndef = isa<UndefValue>(Op0);
3220 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3222 const TargetLowering *TLI = TM.getTargetLowering();
3223 SmallVector<EVT, 4> ValValueVTs;
3224 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3226 unsigned NumValValues = ValValueVTs.size();
3228 // Ignore a extractvalue that produces an empty object
3229 if (!NumValValues) {
3230 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3234 SmallVector<SDValue, 4> Values(NumValValues);
3236 SDValue Agg = getValue(Op0);
3237 // Copy out the selected value(s).
3238 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3239 Values[i - LinearIndex] =
3241 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3242 SDValue(Agg.getNode(), Agg.getResNo() + i);
3244 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3245 DAG.getVTList(&ValValueVTs[0], NumValValues),
3246 &Values[0], NumValValues));
3249 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3250 Value *Op0 = I.getOperand(0);
3251 // Note that the pointer operand may be a vector of pointers. Take the scalar
3252 // element which holds a pointer.
3253 Type *Ty = Op0->getType()->getScalarType();
3254 unsigned AS = Ty->getPointerAddressSpace();
3255 SDValue N = getValue(Op0);
3257 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3259 const Value *Idx = *OI;
3260 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3261 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3264 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
3265 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3266 DAG.getConstant(Offset, N.getValueType()));
3269 Ty = StTy->getElementType(Field);
3271 Ty = cast<SequentialType>(Ty)->getElementType();
3273 // If this is a constant subscript, handle it quickly.
3274 const TargetLowering *TLI = TM.getTargetLowering();
3275 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3276 if (CI->isZero()) continue;
3278 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3280 EVT PTy = TLI->getPointerTy(AS);
3281 unsigned PtrBits = PTy.getSizeInBits();
3283 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3284 DAG.getConstant(Offs, MVT::i64));
3286 OffsVal = DAG.getConstant(Offs, PTy);
3288 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3293 // N = N + Idx * ElementSize;
3294 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
3295 TD->getTypeAllocSize(Ty));
3296 SDValue IdxN = getValue(Idx);
3298 // If the index is smaller or larger than intptr_t, truncate or extend
3300 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3302 // If this is a multiply by a power of two, turn it into a shl
3303 // immediately. This is a very common case.
3304 if (ElementSize != 1) {
3305 if (ElementSize.isPowerOf2()) {
3306 unsigned Amt = ElementSize.logBase2();
3307 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3308 N.getValueType(), IdxN,
3309 DAG.getConstant(Amt, IdxN.getValueType()));
3311 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3312 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3313 N.getValueType(), IdxN, Scale);
3317 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3318 N.getValueType(), N, IdxN);
3325 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3326 // If this is a fixed sized alloca in the entry block of the function,
3327 // allocate it statically on the stack.
3328 if (FuncInfo.StaticAllocaMap.count(&I))
3329 return; // getValue will auto-populate this.
3331 Type *Ty = I.getAllocatedType();
3332 const TargetLowering *TLI = TM.getTargetLowering();
3333 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
3335 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
3338 SDValue AllocSize = getValue(I.getArraySize());
3340 EVT IntPtr = TLI->getPointerTy();
3341 if (AllocSize.getValueType() != IntPtr)
3342 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3344 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3346 DAG.getConstant(TySize, IntPtr));
3348 // Handle alignment. If the requested alignment is less than or equal to
3349 // the stack alignment, ignore it. If the size is greater than or equal to
3350 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3351 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3352 if (Align <= StackAlign)
3355 // Round the size of the allocation up to the stack alignment size
3356 // by add SA-1 to the size.
3357 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3358 AllocSize.getValueType(), AllocSize,
3359 DAG.getIntPtrConstant(StackAlign-1));
3361 // Mask out the low bits for alignment purposes.
3362 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3363 AllocSize.getValueType(), AllocSize,
3364 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3366 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3367 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3368 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
3371 DAG.setRoot(DSA.getValue(1));
3373 // Inform the Frame Information that we have just allocated a variable-sized
3375 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3378 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3380 return visitAtomicLoad(I);
3382 const Value *SV = I.getOperand(0);
3383 SDValue Ptr = getValue(SV);
3385 Type *Ty = I.getType();
3387 bool isVolatile = I.isVolatile();
3388 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3389 bool isInvariant = I.getMetadata("invariant.load") != 0;
3390 unsigned Alignment = I.getAlignment();
3391 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3392 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3394 SmallVector<EVT, 4> ValueVTs;
3395 SmallVector<uint64_t, 4> Offsets;
3396 ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
3397 unsigned NumValues = ValueVTs.size();
3402 bool ConstantMemory = false;
3403 if (isVolatile || NumValues > MaxParallelChains)
3404 // Serialize volatile loads with other side effects.
3406 else if (AA->pointsToConstantMemory(
3407 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3408 // Do not serialize (non-volatile) loads of constant memory with anything.
3409 Root = DAG.getEntryNode();
3410 ConstantMemory = true;
3412 // Do not serialize non-volatile loads against each other.
3413 Root = DAG.getRoot();
3416 const TargetLowering *TLI = TM.getTargetLowering();
3418 Root = TLI->prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3420 SmallVector<SDValue, 4> Values(NumValues);
3421 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3423 EVT PtrVT = Ptr.getValueType();
3424 unsigned ChainI = 0;
3425 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3426 // Serializing loads here may result in excessive register pressure, and
3427 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3428 // could recover a bit by hoisting nodes upward in the chain by recognizing
3429 // they are side-effect free or do not alias. The optimizer should really
3430 // avoid this case by converting large object/array copies to llvm.memcpy
3431 // (MaxParallelChains should always remain as failsafe).
3432 if (ChainI == MaxParallelChains) {
3433 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3434 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3435 MVT::Other, &Chains[0], ChainI);
3439 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3441 DAG.getConstant(Offsets[i], PtrVT));
3442 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3443 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3444 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3448 Chains[ChainI] = L.getValue(1);
3451 if (!ConstantMemory) {
3452 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3453 MVT::Other, &Chains[0], ChainI);
3457 PendingLoads.push_back(Chain);
3460 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3461 DAG.getVTList(&ValueVTs[0], NumValues),
3462 &Values[0], NumValues));
3465 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3467 return visitAtomicStore(I);
3469 const Value *SrcV = I.getOperand(0);
3470 const Value *PtrV = I.getOperand(1);
3472 SmallVector<EVT, 4> ValueVTs;
3473 SmallVector<uint64_t, 4> Offsets;
3474 ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
3475 unsigned NumValues = ValueVTs.size();
3479 // Get the lowered operands. Note that we do this after
3480 // checking if NumResults is zero, because with zero results
3481 // the operands won't have values in the map.
3482 SDValue Src = getValue(SrcV);
3483 SDValue Ptr = getValue(PtrV);
3485 SDValue Root = getRoot();
3486 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3488 EVT PtrVT = Ptr.getValueType();
3489 bool isVolatile = I.isVolatile();
3490 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3491 unsigned Alignment = I.getAlignment();
3492 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3494 unsigned ChainI = 0;
3495 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3496 // See visitLoad comments.
3497 if (ChainI == MaxParallelChains) {
3498 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3499 MVT::Other, &Chains[0], ChainI);
3503 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3504 DAG.getConstant(Offsets[i], PtrVT));
3505 SDValue St = DAG.getStore(Root, getCurSDLoc(),
3506 SDValue(Src.getNode(), Src.getResNo() + i),
3507 Add, MachinePointerInfo(PtrV, Offsets[i]),
3508 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3509 Chains[ChainI] = St;
3512 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3513 MVT::Other, &Chains[0], ChainI);
3514 DAG.setRoot(StoreNode);
3517 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
3518 SynchronizationScope Scope,
3519 bool Before, SDLoc dl,
3521 const TargetLowering &TLI) {
3522 // Fence, if necessary
3524 if (Order == AcquireRelease || Order == SequentiallyConsistent)
3526 else if (Order == Acquire || Order == Monotonic)
3529 if (Order == AcquireRelease)
3531 else if (Order == Release || Order == Monotonic)
3536 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3537 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
3538 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3541 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3542 SDLoc dl = getCurSDLoc();
3543 AtomicOrdering Order = I.getOrdering();
3544 SynchronizationScope Scope = I.getSynchScope();
3546 SDValue InChain = getRoot();
3548 const TargetLowering *TLI = TM.getTargetLowering();
3549 if (TLI->getInsertFencesForAtomic())
3550 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3554 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
3555 getValue(I.getCompareOperand()).getSimpleValueType(),
3557 getValue(I.getPointerOperand()),
3558 getValue(I.getCompareOperand()),
3559 getValue(I.getNewValOperand()),
3560 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
3561 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3564 SDValue OutChain = L.getValue(1);
3566 if (TLI->getInsertFencesForAtomic())
3567 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3571 DAG.setRoot(OutChain);
3574 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3575 SDLoc dl = getCurSDLoc();
3577 switch (I.getOperation()) {
3578 default: llvm_unreachable("Unknown atomicrmw operation");
3579 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3580 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3581 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3582 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3583 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3584 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3585 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3586 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3587 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3588 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3589 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3591 AtomicOrdering Order = I.getOrdering();
3592 SynchronizationScope Scope = I.getSynchScope();
3594 SDValue InChain = getRoot();
3596 const TargetLowering *TLI = TM.getTargetLowering();
3597 if (TLI->getInsertFencesForAtomic())
3598 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3602 DAG.getAtomic(NT, dl,
3603 getValue(I.getValOperand()).getSimpleValueType(),
3605 getValue(I.getPointerOperand()),
3606 getValue(I.getValOperand()),
3607 I.getPointerOperand(), 0 /* Alignment */,
3608 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3611 SDValue OutChain = L.getValue(1);
3613 if (TLI->getInsertFencesForAtomic())
3614 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3618 DAG.setRoot(OutChain);
3621 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3622 SDLoc dl = getCurSDLoc();
3623 const TargetLowering *TLI = TM.getTargetLowering();
3626 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
3627 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
3628 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
3631 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3632 SDLoc dl = getCurSDLoc();
3633 AtomicOrdering Order = I.getOrdering();
3634 SynchronizationScope Scope = I.getSynchScope();
3636 SDValue InChain = getRoot();
3638 const TargetLowering *TLI = TM.getTargetLowering();
3639 EVT VT = TLI->getValueType(I.getType());
3641 if (I.getAlignment() < VT.getSizeInBits() / 8)
3642 report_fatal_error("Cannot generate unaligned atomic load");
3644 InChain = TLI->prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3646 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3647 getValue(I.getPointerOperand()),
3648 I.getPointerOperand(), I.getAlignment(),
3649 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3652 SDValue OutChain = L.getValue(1);
3654 if (TLI->getInsertFencesForAtomic())
3655 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3659 DAG.setRoot(OutChain);
3662 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3663 SDLoc dl = getCurSDLoc();
3665 AtomicOrdering Order = I.getOrdering();
3666 SynchronizationScope Scope = I.getSynchScope();
3668 SDValue InChain = getRoot();
3670 const TargetLowering *TLI = TM.getTargetLowering();
3671 EVT VT = TLI->getValueType(I.getValueOperand()->getType());
3673 if (I.getAlignment() < VT.getSizeInBits() / 8)
3674 report_fatal_error("Cannot generate unaligned atomic store");
3676 if (TLI->getInsertFencesForAtomic())
3677 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3681 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3683 getValue(I.getPointerOperand()),
3684 getValue(I.getValueOperand()),
3685 I.getPointerOperand(), I.getAlignment(),
3686 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3689 if (TLI->getInsertFencesForAtomic())
3690 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3693 DAG.setRoot(OutChain);
3696 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3698 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3699 unsigned Intrinsic) {
3700 bool HasChain = !I.doesNotAccessMemory();
3701 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3703 // Build the operand list.
3704 SmallVector<SDValue, 8> Ops;
3705 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3707 // We don't need to serialize loads against other loads.
3708 Ops.push_back(DAG.getRoot());
3710 Ops.push_back(getRoot());
3714 // Info is set by getTgtMemInstrinsic
3715 TargetLowering::IntrinsicInfo Info;
3716 const TargetLowering *TLI = TM.getTargetLowering();
3717 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
3719 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3720 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3721 Info.opc == ISD::INTRINSIC_W_CHAIN)
3722 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
3724 // Add all operands of the call to the operand list.
3725 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3726 SDValue Op = getValue(I.getArgOperand(i));
3730 SmallVector<EVT, 4> ValueVTs;
3731 ComputeValueVTs(*TLI, I.getType(), ValueVTs);
3734 ValueVTs.push_back(MVT::Other);
3736 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3740 if (IsTgtIntrinsic) {
3741 // This is target intrinsic that touches memory
3742 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3743 VTs, &Ops[0], Ops.size(),
3745 MachinePointerInfo(Info.ptrVal, Info.offset),
3746 Info.align, Info.vol,
3747 Info.readMem, Info.writeMem);
3748 } else if (!HasChain) {
3749 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
3750 VTs, &Ops[0], Ops.size());
3751 } else if (!I.getType()->isVoidTy()) {
3752 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
3753 VTs, &Ops[0], Ops.size());
3755 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
3756 VTs, &Ops[0], Ops.size());
3760 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3762 PendingLoads.push_back(Chain);
3767 if (!I.getType()->isVoidTy()) {
3768 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3769 EVT VT = TLI->getValueType(PTy);
3770 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3773 setValue(&I, Result);
3777 /// GetSignificand - Get the significand and build it into a floating-point
3778 /// number with exponent of 1:
3780 /// Op = (Op & 0x007fffff) | 0x3f800000;
3782 /// where Op is the hexadecimal representation of floating point value.
3784 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3785 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3786 DAG.getConstant(0x007fffff, MVT::i32));
3787 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3788 DAG.getConstant(0x3f800000, MVT::i32));
3789 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3792 /// GetExponent - Get the exponent:
3794 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3796 /// where Op is the hexadecimal representation of floating point value.
3798 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3800 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3801 DAG.getConstant(0x7f800000, MVT::i32));
3802 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3803 DAG.getConstant(23, TLI.getPointerTy()));
3804 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3805 DAG.getConstant(127, MVT::i32));
3806 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3809 /// getF32Constant - Get 32-bit floating point constant.
3811 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3812 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3816 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3817 /// limited-precision mode.
3818 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3819 const TargetLowering &TLI) {
3820 if (Op.getValueType() == MVT::f32 &&
3821 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3823 // Put the exponent in the right bit position for later addition to the
3826 // #define LOG2OFe 1.4426950f
3827 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3828 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3829 getF32Constant(DAG, 0x3fb8aa3b));
3830 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3832 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3833 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3834 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3836 // IntegerPartOfX <<= 23;
3837 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3838 DAG.getConstant(23, TLI.getPointerTy()));
3840 SDValue TwoToFracPartOfX;
3841 if (LimitFloatPrecision <= 6) {
3842 // For floating-point precision of 6:
3844 // TwoToFractionalPartOfX =
3846 // (0.735607626f + 0.252464424f * x) * x;
3848 // error 0.0144103317, which is 6 bits
3849 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3850 getF32Constant(DAG, 0x3e814304));
3851 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3852 getF32Constant(DAG, 0x3f3c50c8));
3853 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3854 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3855 getF32Constant(DAG, 0x3f7f5e7e));
3856 } else if (LimitFloatPrecision <= 12) {
3857 // For floating-point precision of 12:
3859 // TwoToFractionalPartOfX =
3862 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3864 // 0.000107046256 error, which is 13 to 14 bits
3865 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3866 getF32Constant(DAG, 0x3da235e3));
3867 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3868 getF32Constant(DAG, 0x3e65b8f3));
3869 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3870 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3871 getF32Constant(DAG, 0x3f324b07));
3872 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3873 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3874 getF32Constant(DAG, 0x3f7ff8fd));
3875 } else { // LimitFloatPrecision <= 18
3876 // For floating-point precision of 18:
3878 // TwoToFractionalPartOfX =
3882 // (0.554906021e-1f +
3883 // (0.961591928e-2f +
3884 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3886 // error 2.47208000*10^(-7), which is better than 18 bits
3887 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3888 getF32Constant(DAG, 0x3924b03e));
3889 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3890 getF32Constant(DAG, 0x3ab24b87));
3891 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3892 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3893 getF32Constant(DAG, 0x3c1d8c17));
3894 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3895 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3896 getF32Constant(DAG, 0x3d634a1d));
3897 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3898 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3899 getF32Constant(DAG, 0x3e75fe14));
3900 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3901 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3902 getF32Constant(DAG, 0x3f317234));
3903 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3904 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3905 getF32Constant(DAG, 0x3f800000));
3908 // Add the exponent into the result in integer domain.
3909 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
3910 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3911 DAG.getNode(ISD::ADD, dl, MVT::i32,
3912 t13, IntegerPartOfX));
3915 // No special expansion.
3916 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3919 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3920 /// limited-precision mode.
3921 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3922 const TargetLowering &TLI) {
3923 if (Op.getValueType() == MVT::f32 &&
3924 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3925 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3927 // Scale the exponent by log(2) [0.69314718f].
3928 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3929 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3930 getF32Constant(DAG, 0x3f317218));
3932 // Get the significand and build it into a floating-point number with
3934 SDValue X = GetSignificand(DAG, Op1, dl);
3936 SDValue LogOfMantissa;
3937 if (LimitFloatPrecision <= 6) {
3938 // For floating-point precision of 6:
3942 // (1.4034025f - 0.23903021f * x) * x;
3944 // error 0.0034276066, which is better than 8 bits
3945 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3946 getF32Constant(DAG, 0xbe74c456));
3947 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3948 getF32Constant(DAG, 0x3fb3a2b1));
3949 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3950 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3951 getF32Constant(DAG, 0x3f949a29));
3952 } else if (LimitFloatPrecision <= 12) {
3953 // For floating-point precision of 12:
3959 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3961 // error 0.000061011436, which is 14 bits
3962 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3963 getF32Constant(DAG, 0xbd67b6d6));
3964 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3965 getF32Constant(DAG, 0x3ee4f4b8));
3966 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3967 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3968 getF32Constant(DAG, 0x3fbc278b));
3969 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3970 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3971 getF32Constant(DAG, 0x40348e95));
3972 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3973 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3974 getF32Constant(DAG, 0x3fdef31a));
3975 } else { // LimitFloatPrecision <= 18
3976 // For floating-point precision of 18:
3984 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3986 // error 0.0000023660568, which is better than 18 bits
3987 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3988 getF32Constant(DAG, 0xbc91e5ac));
3989 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3990 getF32Constant(DAG, 0x3e4350aa));
3991 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3992 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3993 getF32Constant(DAG, 0x3f60d3e3));
3994 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3995 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3996 getF32Constant(DAG, 0x4011cdf0));
3997 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3998 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3999 getF32Constant(DAG, 0x406cfd1c));
4000 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4001 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4002 getF32Constant(DAG, 0x408797cb));
4003 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4004 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4005 getF32Constant(DAG, 0x4006dcab));
4008 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4011 // No special expansion.
4012 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4015 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4016 /// limited-precision mode.
4017 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4018 const TargetLowering &TLI) {
4019 if (Op.getValueType() == MVT::f32 &&
4020 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4021 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4023 // Get the exponent.
4024 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4026 // Get the significand and build it into a floating-point number with
4028 SDValue X = GetSignificand(DAG, Op1, dl);
4030 // Different possible minimax approximations of significand in
4031 // floating-point for various degrees of accuracy over [1,2].
4032 SDValue Log2ofMantissa;
4033 if (LimitFloatPrecision <= 6) {
4034 // For floating-point precision of 6:
4036 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4038 // error 0.0049451742, which is more than 7 bits
4039 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4040 getF32Constant(DAG, 0xbeb08fe0));
4041 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4042 getF32Constant(DAG, 0x40019463));
4043 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4044 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4045 getF32Constant(DAG, 0x3fd6633d));
4046 } else if (LimitFloatPrecision <= 12) {
4047 // For floating-point precision of 12:
4053 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4055 // error 0.0000876136000, which is better than 13 bits
4056 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4057 getF32Constant(DAG, 0xbda7262e));
4058 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4059 getF32Constant(DAG, 0x3f25280b));
4060 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4061 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4062 getF32Constant(DAG, 0x4007b923));
4063 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4064 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4065 getF32Constant(DAG, 0x40823e2f));
4066 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4067 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4068 getF32Constant(DAG, 0x4020d29c));
4069 } else { // LimitFloatPrecision <= 18
4070 // For floating-point precision of 18:
4079 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4081 // error 0.0000018516, which is better than 18 bits
4082 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4083 getF32Constant(DAG, 0xbcd2769e));
4084 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4085 getF32Constant(DAG, 0x3e8ce0b9));
4086 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4087 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4088 getF32Constant(DAG, 0x3fa22ae7));
4089 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4090 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4091 getF32Constant(DAG, 0x40525723));
4092 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4093 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4094 getF32Constant(DAG, 0x40aaf200));
4095 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4096 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4097 getF32Constant(DAG, 0x40c39dad));
4098 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4099 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4100 getF32Constant(DAG, 0x4042902c));
4103 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4106 // No special expansion.
4107 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4110 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4111 /// limited-precision mode.
4112 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4113 const TargetLowering &TLI) {
4114 if (Op.getValueType() == MVT::f32 &&
4115 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4116 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4118 // Scale the exponent by log10(2) [0.30102999f].
4119 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4120 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4121 getF32Constant(DAG, 0x3e9a209a));
4123 // Get the significand and build it into a floating-point number with
4125 SDValue X = GetSignificand(DAG, Op1, dl);
4127 SDValue Log10ofMantissa;
4128 if (LimitFloatPrecision <= 6) {
4129 // For floating-point precision of 6:
4131 // Log10ofMantissa =
4133 // (0.60948995f - 0.10380950f * x) * x;
4135 // error 0.0014886165, which is 6 bits
4136 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4137 getF32Constant(DAG, 0xbdd49a13));
4138 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4139 getF32Constant(DAG, 0x3f1c0789));
4140 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4141 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4142 getF32Constant(DAG, 0x3f011300));
4143 } else if (LimitFloatPrecision <= 12) {
4144 // For floating-point precision of 12:
4146 // Log10ofMantissa =
4149 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4151 // error 0.00019228036, which is better than 12 bits
4152 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4153 getF32Constant(DAG, 0x3d431f31));
4154 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4155 getF32Constant(DAG, 0x3ea21fb2));
4156 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4157 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4158 getF32Constant(DAG, 0x3f6ae232));
4159 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4160 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4161 getF32Constant(DAG, 0x3f25f7c3));
4162 } else { // LimitFloatPrecision <= 18
4163 // For floating-point precision of 18:
4165 // Log10ofMantissa =
4170 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4172 // error 0.0000037995730, which is better than 18 bits
4173 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4174 getF32Constant(DAG, 0x3c5d51ce));
4175 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4176 getF32Constant(DAG, 0x3e00685a));
4177 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4178 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4179 getF32Constant(DAG, 0x3efb6798));
4180 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4181 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4182 getF32Constant(DAG, 0x3f88d192));
4183 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4184 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4185 getF32Constant(DAG, 0x3fc4316c));
4186 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4187 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4188 getF32Constant(DAG, 0x3f57ce70));
4191 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4194 // No special expansion.
4195 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4198 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4199 /// limited-precision mode.
4200 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4201 const TargetLowering &TLI) {
4202 if (Op.getValueType() == MVT::f32 &&
4203 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4204 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4206 // FractionalPartOfX = x - (float)IntegerPartOfX;
4207 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4208 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4210 // IntegerPartOfX <<= 23;
4211 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4212 DAG.getConstant(23, TLI.getPointerTy()));
4214 SDValue TwoToFractionalPartOfX;
4215 if (LimitFloatPrecision <= 6) {
4216 // For floating-point precision of 6:
4218 // TwoToFractionalPartOfX =
4220 // (0.735607626f + 0.252464424f * x) * x;
4222 // error 0.0144103317, which is 6 bits
4223 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4224 getF32Constant(DAG, 0x3e814304));
4225 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4226 getF32Constant(DAG, 0x3f3c50c8));
4227 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4228 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4229 getF32Constant(DAG, 0x3f7f5e7e));
4230 } else if (LimitFloatPrecision <= 12) {
4231 // For floating-point precision of 12:
4233 // TwoToFractionalPartOfX =
4236 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4238 // error 0.000107046256, which is 13 to 14 bits
4239 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4240 getF32Constant(DAG, 0x3da235e3));
4241 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4242 getF32Constant(DAG, 0x3e65b8f3));
4243 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4244 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4245 getF32Constant(DAG, 0x3f324b07));
4246 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4247 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4248 getF32Constant(DAG, 0x3f7ff8fd));
4249 } else { // LimitFloatPrecision <= 18
4250 // For floating-point precision of 18:
4252 // TwoToFractionalPartOfX =
4256 // (0.554906021e-1f +
4257 // (0.961591928e-2f +
4258 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4259 // error 2.47208000*10^(-7), which is better than 18 bits
4260 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4261 getF32Constant(DAG, 0x3924b03e));
4262 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4263 getF32Constant(DAG, 0x3ab24b87));
4264 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4265 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4266 getF32Constant(DAG, 0x3c1d8c17));
4267 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4268 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4269 getF32Constant(DAG, 0x3d634a1d));
4270 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4271 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4272 getF32Constant(DAG, 0x3e75fe14));
4273 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4274 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4275 getF32Constant(DAG, 0x3f317234));
4276 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4277 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4278 getF32Constant(DAG, 0x3f800000));
4281 // Add the exponent into the result in integer domain.
4282 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4283 TwoToFractionalPartOfX);
4284 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4285 DAG.getNode(ISD::ADD, dl, MVT::i32,
4286 t13, IntegerPartOfX));
4289 // No special expansion.
4290 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4293 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4294 /// limited-precision mode with x == 10.0f.
4295 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4296 SelectionDAG &DAG, const TargetLowering &TLI) {
4297 bool IsExp10 = false;
4298 if (LHS.getValueType() == MVT::f32 && LHS.getValueType() == MVT::f32 &&
4299 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4300 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4302 IsExp10 = LHSC->isExactlyValue(Ten);
4307 // Put the exponent in the right bit position for later addition to the
4310 // #define LOG2OF10 3.3219281f
4311 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4312 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4313 getF32Constant(DAG, 0x40549a78));
4314 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4316 // FractionalPartOfX = x - (float)IntegerPartOfX;
4317 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4318 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4320 // IntegerPartOfX <<= 23;
4321 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4322 DAG.getConstant(23, TLI.getPointerTy()));
4324 SDValue TwoToFractionalPartOfX;
4325 if (LimitFloatPrecision <= 6) {
4326 // For floating-point precision of 6:
4328 // twoToFractionalPartOfX =
4330 // (0.735607626f + 0.252464424f * x) * x;
4332 // error 0.0144103317, which is 6 bits
4333 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4334 getF32Constant(DAG, 0x3e814304));
4335 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4336 getF32Constant(DAG, 0x3f3c50c8));
4337 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4338 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4339 getF32Constant(DAG, 0x3f7f5e7e));
4340 } else if (LimitFloatPrecision <= 12) {
4341 // For floating-point precision of 12:
4343 // TwoToFractionalPartOfX =
4346 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4348 // error 0.000107046256, which is 13 to 14 bits
4349 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4350 getF32Constant(DAG, 0x3da235e3));
4351 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4352 getF32Constant(DAG, 0x3e65b8f3));
4353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4354 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4355 getF32Constant(DAG, 0x3f324b07));
4356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4357 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4358 getF32Constant(DAG, 0x3f7ff8fd));
4359 } else { // LimitFloatPrecision <= 18
4360 // For floating-point precision of 18:
4362 // TwoToFractionalPartOfX =
4366 // (0.554906021e-1f +
4367 // (0.961591928e-2f +
4368 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4369 // error 2.47208000*10^(-7), which is better than 18 bits
4370 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4371 getF32Constant(DAG, 0x3924b03e));
4372 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4373 getF32Constant(DAG, 0x3ab24b87));
4374 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4375 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4376 getF32Constant(DAG, 0x3c1d8c17));
4377 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4378 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4379 getF32Constant(DAG, 0x3d634a1d));
4380 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4381 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4382 getF32Constant(DAG, 0x3e75fe14));
4383 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4384 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4385 getF32Constant(DAG, 0x3f317234));
4386 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4387 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4388 getF32Constant(DAG, 0x3f800000));
4391 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
4392 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4393 DAG.getNode(ISD::ADD, dl, MVT::i32,
4394 t13, IntegerPartOfX));
4397 // No special expansion.
4398 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4402 /// ExpandPowI - Expand a llvm.powi intrinsic.
4403 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4404 SelectionDAG &DAG) {
4405 // If RHS is a constant, we can expand this out to a multiplication tree,
4406 // otherwise we end up lowering to a call to __powidf2 (for example). When
4407 // optimizing for size, we only want to do this if the expansion would produce
4408 // a small number of multiplies, otherwise we do the full expansion.
4409 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4410 // Get the exponent as a positive value.
4411 unsigned Val = RHSC->getSExtValue();
4412 if ((int)Val < 0) Val = -Val;
4414 // powi(x, 0) -> 1.0
4416 return DAG.getConstantFP(1.0, LHS.getValueType());
4418 const Function *F = DAG.getMachineFunction().getFunction();
4419 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4420 Attribute::OptimizeForSize) ||
4421 // If optimizing for size, don't insert too many multiplies. This
4422 // inserts up to 5 multiplies.
4423 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4424 // We use the simple binary decomposition method to generate the multiply
4425 // sequence. There are more optimal ways to do this (for example,
4426 // powi(x,15) generates one more multiply than it should), but this has
4427 // the benefit of being both really simple and much better than a libcall.
4428 SDValue Res; // Logically starts equal to 1.0
4429 SDValue CurSquare = LHS;
4433 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4435 Res = CurSquare; // 1.0*CurSquare.
4438 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4439 CurSquare, CurSquare);
4443 // If the original was negative, invert the result, producing 1/(x*x*x).
4444 if (RHSC->getSExtValue() < 0)
4445 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4446 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4451 // Otherwise, expand to a libcall.
4452 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4455 // getTruncatedArgReg - Find underlying register used for an truncated
4457 static unsigned getTruncatedArgReg(const SDValue &N) {
4458 if (N.getOpcode() != ISD::TRUNCATE)
4461 const SDValue &Ext = N.getOperand(0);
4462 if (Ext.getOpcode() == ISD::AssertZext ||
4463 Ext.getOpcode() == ISD::AssertSext) {
4464 const SDValue &CFR = Ext.getOperand(0);
4465 if (CFR.getOpcode() == ISD::CopyFromReg)
4466 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4467 if (CFR.getOpcode() == ISD::TRUNCATE)
4468 return getTruncatedArgReg(CFR);
4473 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4474 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4475 /// At the end of instruction selection, they will be inserted to the entry BB.
4477 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4480 const Argument *Arg = dyn_cast<Argument>(V);
4484 MachineFunction &MF = DAG.getMachineFunction();
4485 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4487 // Ignore inlined function arguments here.
4488 DIVariable DV(Variable);
4489 if (DV.isInlinedFnArgument(MF.getFunction()))
4492 Optional<MachineOperand> Op;
4493 // Some arguments' frame index is recorded during argument lowering.
4494 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4495 Op = MachineOperand::CreateFI(FI);
4497 if (!Op && N.getNode()) {
4499 if (N.getOpcode() == ISD::CopyFromReg)
4500 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4502 Reg = getTruncatedArgReg(N);
4503 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4504 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4505 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4510 Op = MachineOperand::CreateReg(Reg, false);
4514 // Check if ValueMap has reg number.
4515 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4516 if (VMI != FuncInfo.ValueMap.end())
4517 Op = MachineOperand::CreateReg(VMI->second, false);
4520 if (!Op && N.getNode())
4521 // Check if frame index is available.
4522 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4523 if (FrameIndexSDNode *FINode =
4524 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4525 Op = MachineOperand::CreateFI(FINode->getIndex());
4530 // FIXME: This does not handle register-indirect values at offset 0.
4531 bool IsIndirect = Offset != 0;
4533 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
4534 TII->get(TargetOpcode::DBG_VALUE),
4536 Op->getReg(), Offset, Variable));
4538 FuncInfo.ArgDbgValues.push_back(
4539 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4540 .addOperand(*Op).addImm(Offset).addMetadata(Variable));
4545 // VisualStudio defines setjmp as _setjmp
4546 #if defined(_MSC_VER) && defined(setjmp) && \
4547 !defined(setjmp_undefined_for_msvc)
4548 # pragma push_macro("setjmp")
4550 # define setjmp_undefined_for_msvc
4553 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4554 /// we want to emit this as a call to a named external function, return the name
4555 /// otherwise lower it and return null.
4557 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4558 const TargetLowering *TLI = TM.getTargetLowering();
4559 SDLoc sdl = getCurSDLoc();
4560 DebugLoc dl = getCurDebugLoc();
4563 switch (Intrinsic) {
4565 // By default, turn this into a target intrinsic node.
4566 visitTargetIntrinsic(I, Intrinsic);
4568 case Intrinsic::vastart: visitVAStart(I); return 0;
4569 case Intrinsic::vaend: visitVAEnd(I); return 0;
4570 case Intrinsic::vacopy: visitVACopy(I); return 0;
4571 case Intrinsic::returnaddress:
4572 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
4573 getValue(I.getArgOperand(0))));
4575 case Intrinsic::frameaddress:
4576 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
4577 getValue(I.getArgOperand(0))));
4579 case Intrinsic::setjmp:
4580 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
4581 case Intrinsic::longjmp:
4582 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
4583 case Intrinsic::memcpy: {
4584 // Assert for address < 256 since we support only user defined address
4586 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4588 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4590 "Unknown address space");
4591 SDValue Op1 = getValue(I.getArgOperand(0));
4592 SDValue Op2 = getValue(I.getArgOperand(1));
4593 SDValue Op3 = getValue(I.getArgOperand(2));
4594 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4596 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4597 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4598 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
4599 MachinePointerInfo(I.getArgOperand(0)),
4600 MachinePointerInfo(I.getArgOperand(1))));
4603 case Intrinsic::memset: {
4604 // Assert for address < 256 since we support only user defined address
4606 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4608 "Unknown address space");
4609 SDValue Op1 = getValue(I.getArgOperand(0));
4610 SDValue Op2 = getValue(I.getArgOperand(1));
4611 SDValue Op3 = getValue(I.getArgOperand(2));
4612 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4614 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4615 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4616 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4617 MachinePointerInfo(I.getArgOperand(0))));
4620 case Intrinsic::memmove: {
4621 // Assert for address < 256 since we support only user defined address
4623 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4625 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4627 "Unknown address space");
4628 SDValue Op1 = getValue(I.getArgOperand(0));
4629 SDValue Op2 = getValue(I.getArgOperand(1));
4630 SDValue Op3 = getValue(I.getArgOperand(2));
4631 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4633 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4634 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4635 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4636 MachinePointerInfo(I.getArgOperand(0)),
4637 MachinePointerInfo(I.getArgOperand(1))));
4640 case Intrinsic::dbg_declare: {
4641 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4642 MDNode *Variable = DI.getVariable();
4643 const Value *Address = DI.getAddress();
4644 DIVariable DIVar(Variable);
4645 assert((!DIVar || DIVar.isVariable()) &&
4646 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4647 if (!Address || !DIVar) {
4648 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4652 // Check if address has undef value.
4653 if (isa<UndefValue>(Address) ||
4654 (Address->use_empty() && !isa<Argument>(Address))) {
4655 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4659 SDValue &N = NodeMap[Address];
4660 if (!N.getNode() && isa<Argument>(Address))
4661 // Check unused arguments map.
4662 N = UnusedArgNodeMap[Address];
4665 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4666 Address = BCI->getOperand(0);
4667 // Parameters are handled specially.
4669 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4670 isa<Argument>(Address));
4672 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4674 if (isParameter && !AI) {
4675 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4677 // Byval parameter. We have a frame index at this point.
4678 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4679 0, dl, SDNodeOrder);
4681 // Address is an argument, so try to emit its dbg value using
4682 // virtual register info from the FuncInfo.ValueMap.
4683 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4687 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4688 0, dl, SDNodeOrder);
4690 // Can't do anything with other non-AI cases yet.
4691 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4692 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4693 DEBUG(Address->dump());
4696 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4698 // If Address is an argument then try to emit its dbg value using
4699 // virtual register info from the FuncInfo.ValueMap.
4700 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4701 // If variable is pinned by a alloca in dominating bb then
4702 // use StaticAllocaMap.
4703 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4704 if (AI->getParent() != DI.getParent()) {
4705 DenseMap<const AllocaInst*, int>::iterator SI =
4706 FuncInfo.StaticAllocaMap.find(AI);
4707 if (SI != FuncInfo.StaticAllocaMap.end()) {
4708 SDV = DAG.getDbgValue(Variable, SI->second,
4709 0, dl, SDNodeOrder);
4710 DAG.AddDbgValue(SDV, 0, false);
4715 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4720 case Intrinsic::dbg_value: {
4721 const DbgValueInst &DI = cast<DbgValueInst>(I);
4722 DIVariable DIVar(DI.getVariable());
4723 assert((!DIVar || DIVar.isVariable()) &&
4724 "Variable in DbgValueInst should be either null or a DIVariable.");
4728 MDNode *Variable = DI.getVariable();
4729 uint64_t Offset = DI.getOffset();
4730 const Value *V = DI.getValue();
4735 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4736 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4737 DAG.AddDbgValue(SDV, 0, false);
4739 // Do not use getValue() in here; we don't want to generate code at
4740 // this point if it hasn't been done yet.
4741 SDValue N = NodeMap[V];
4742 if (!N.getNode() && isa<Argument>(V))
4743 // Check unused arguments map.
4744 N = UnusedArgNodeMap[V];
4746 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4747 SDV = DAG.getDbgValue(Variable, N.getNode(),
4748 N.getResNo(), Offset, dl, SDNodeOrder);
4749 DAG.AddDbgValue(SDV, N.getNode(), false);
4751 } else if (!V->use_empty() ) {
4752 // Do not call getValue(V) yet, as we don't want to generate code.
4753 // Remember it for later.
4754 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4755 DanglingDebugInfoMap[V] = DDI;
4757 // We may expand this to cover more cases. One case where we have no
4758 // data available is an unreferenced parameter.
4759 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4763 // Build a debug info table entry.
4764 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4765 V = BCI->getOperand(0);
4766 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4767 // Don't handle byval struct arguments or VLAs, for example.
4769 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4770 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4773 DenseMap<const AllocaInst*, int>::iterator SI =
4774 FuncInfo.StaticAllocaMap.find(AI);
4775 if (SI == FuncInfo.StaticAllocaMap.end())
4777 int FI = SI->second;
4779 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4780 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4781 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4785 case Intrinsic::eh_typeid_for: {
4786 // Find the type id for the given typeinfo.
4787 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4788 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4789 Res = DAG.getConstant(TypeID, MVT::i32);
4794 case Intrinsic::eh_return_i32:
4795 case Intrinsic::eh_return_i64:
4796 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4797 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4800 getValue(I.getArgOperand(0)),
4801 getValue(I.getArgOperand(1))));
4803 case Intrinsic::eh_unwind_init:
4804 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4806 case Intrinsic::eh_dwarf_cfa: {
4807 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4808 TLI->getPointerTy());
4809 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4810 CfaArg.getValueType(),
4811 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4812 CfaArg.getValueType()),
4814 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
4815 TLI->getPointerTy(),
4816 DAG.getConstant(0, TLI->getPointerTy()));
4817 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4821 case Intrinsic::eh_sjlj_callsite: {
4822 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4823 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4824 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4825 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4827 MMI.setCurrentCallSite(CI->getZExtValue());
4830 case Intrinsic::eh_sjlj_functioncontext: {
4831 // Get and store the index of the function context.
4832 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4834 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4835 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4836 MFI->setFunctionContextIndex(FI);
4839 case Intrinsic::eh_sjlj_setjmp: {
4842 Ops[1] = getValue(I.getArgOperand(0));
4843 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4844 DAG.getVTList(MVT::i32, MVT::Other),
4846 setValue(&I, Op.getValue(0));
4847 DAG.setRoot(Op.getValue(1));
4850 case Intrinsic::eh_sjlj_longjmp: {
4851 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4852 getRoot(), getValue(I.getArgOperand(0))));
4856 case Intrinsic::x86_mmx_pslli_w:
4857 case Intrinsic::x86_mmx_pslli_d:
4858 case Intrinsic::x86_mmx_pslli_q:
4859 case Intrinsic::x86_mmx_psrli_w:
4860 case Intrinsic::x86_mmx_psrli_d:
4861 case Intrinsic::x86_mmx_psrli_q:
4862 case Intrinsic::x86_mmx_psrai_w:
4863 case Intrinsic::x86_mmx_psrai_d: {
4864 SDValue ShAmt = getValue(I.getArgOperand(1));
4865 if (isa<ConstantSDNode>(ShAmt)) {
4866 visitTargetIntrinsic(I, Intrinsic);
4869 unsigned NewIntrinsic = 0;
4870 EVT ShAmtVT = MVT::v2i32;
4871 switch (Intrinsic) {
4872 case Intrinsic::x86_mmx_pslli_w:
4873 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4875 case Intrinsic::x86_mmx_pslli_d:
4876 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4878 case Intrinsic::x86_mmx_pslli_q:
4879 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4881 case Intrinsic::x86_mmx_psrli_w:
4882 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4884 case Intrinsic::x86_mmx_psrli_d:
4885 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4887 case Intrinsic::x86_mmx_psrli_q:
4888 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4890 case Intrinsic::x86_mmx_psrai_w:
4891 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4893 case Intrinsic::x86_mmx_psrai_d:
4894 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4896 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4899 // The vector shift intrinsics with scalars uses 32b shift amounts but
4900 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4902 // We must do this early because v2i32 is not a legal type.
4905 ShOps[1] = DAG.getConstant(0, MVT::i32);
4906 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
4907 EVT DestVT = TLI->getValueType(I.getType());
4908 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4909 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4910 DAG.getConstant(NewIntrinsic, MVT::i32),
4911 getValue(I.getArgOperand(0)), ShAmt);
4915 case Intrinsic::x86_avx_vinsertf128_pd_256:
4916 case Intrinsic::x86_avx_vinsertf128_ps_256:
4917 case Intrinsic::x86_avx_vinsertf128_si_256:
4918 case Intrinsic::x86_avx2_vinserti128: {
4919 EVT DestVT = TLI->getValueType(I.getType());
4920 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
4921 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4922 ElVT.getVectorNumElements();
4923 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
4924 getValue(I.getArgOperand(0)),
4925 getValue(I.getArgOperand(1)),
4926 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
4930 case Intrinsic::x86_avx_vextractf128_pd_256:
4931 case Intrinsic::x86_avx_vextractf128_ps_256:
4932 case Intrinsic::x86_avx_vextractf128_si_256:
4933 case Intrinsic::x86_avx2_vextracti128: {
4934 EVT DestVT = TLI->getValueType(I.getType());
4935 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4936 DestVT.getVectorNumElements();
4937 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
4938 getValue(I.getArgOperand(0)),
4939 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
4943 case Intrinsic::convertff:
4944 case Intrinsic::convertfsi:
4945 case Intrinsic::convertfui:
4946 case Intrinsic::convertsif:
4947 case Intrinsic::convertuif:
4948 case Intrinsic::convertss:
4949 case Intrinsic::convertsu:
4950 case Intrinsic::convertus:
4951 case Intrinsic::convertuu: {
4952 ISD::CvtCode Code = ISD::CVT_INVALID;
4953 switch (Intrinsic) {
4954 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4955 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4956 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4957 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4958 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4959 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4960 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4961 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4962 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4963 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4965 EVT DestVT = TLI->getValueType(I.getType());
4966 const Value *Op1 = I.getArgOperand(0);
4967 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4968 DAG.getValueType(DestVT),
4969 DAG.getValueType(getValue(Op1).getValueType()),
4970 getValue(I.getArgOperand(1)),
4971 getValue(I.getArgOperand(2)),
4976 case Intrinsic::powi:
4977 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4978 getValue(I.getArgOperand(1)), DAG));
4980 case Intrinsic::log:
4981 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4983 case Intrinsic::log2:
4984 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4986 case Intrinsic::log10:
4987 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4989 case Intrinsic::exp:
4990 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4992 case Intrinsic::exp2:
4993 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4995 case Intrinsic::pow:
4996 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4997 getValue(I.getArgOperand(1)), DAG, *TLI));
4999 case Intrinsic::sqrt:
5000 case Intrinsic::fabs:
5001 case Intrinsic::sin:
5002 case Intrinsic::cos:
5003 case Intrinsic::floor:
5004 case Intrinsic::ceil:
5005 case Intrinsic::trunc:
5006 case Intrinsic::rint:
5007 case Intrinsic::nearbyint:
5008 case Intrinsic::round: {
5010 switch (Intrinsic) {
5011 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5012 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5013 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5014 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5015 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5016 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5017 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5018 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5019 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5020 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5021 case Intrinsic::round: Opcode = ISD::FROUND; break;
5024 setValue(&I, DAG.getNode(Opcode, sdl,
5025 getValue(I.getArgOperand(0)).getValueType(),
5026 getValue(I.getArgOperand(0))));
5029 case Intrinsic::copysign:
5030 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5031 getValue(I.getArgOperand(0)).getValueType(),
5032 getValue(I.getArgOperand(0)),
5033 getValue(I.getArgOperand(1))));
5035 case Intrinsic::fma:
5036 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5037 getValue(I.getArgOperand(0)).getValueType(),
5038 getValue(I.getArgOperand(0)),
5039 getValue(I.getArgOperand(1)),
5040 getValue(I.getArgOperand(2))));
5042 case Intrinsic::fmuladd: {
5043 EVT VT = TLI->getValueType(I.getType());
5044 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5045 TLI->isFMAFasterThanFMulAndFAdd(VT)) {
5046 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5047 getValue(I.getArgOperand(0)).getValueType(),
5048 getValue(I.getArgOperand(0)),
5049 getValue(I.getArgOperand(1)),
5050 getValue(I.getArgOperand(2))));
5052 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5053 getValue(I.getArgOperand(0)).getValueType(),
5054 getValue(I.getArgOperand(0)),
5055 getValue(I.getArgOperand(1)));
5056 SDValue Add = DAG.getNode(ISD::FADD, sdl,
5057 getValue(I.getArgOperand(0)).getValueType(),
5059 getValue(I.getArgOperand(2)));
5064 case Intrinsic::convert_to_fp16:
5065 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
5066 MVT::i16, getValue(I.getArgOperand(0))));
5068 case Intrinsic::convert_from_fp16:
5069 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
5070 MVT::f32, getValue(I.getArgOperand(0))));
5072 case Intrinsic::pcmarker: {
5073 SDValue Tmp = getValue(I.getArgOperand(0));
5074 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5077 case Intrinsic::readcyclecounter: {
5078 SDValue Op = getRoot();
5079 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5080 DAG.getVTList(MVT::i64, MVT::Other),
5083 DAG.setRoot(Res.getValue(1));
5086 case Intrinsic::bswap:
5087 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5088 getValue(I.getArgOperand(0)).getValueType(),
5089 getValue(I.getArgOperand(0))));
5091 case Intrinsic::cttz: {
5092 SDValue Arg = getValue(I.getArgOperand(0));
5093 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5094 EVT Ty = Arg.getValueType();
5095 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5099 case Intrinsic::ctlz: {
5100 SDValue Arg = getValue(I.getArgOperand(0));
5101 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5102 EVT Ty = Arg.getValueType();
5103 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5107 case Intrinsic::ctpop: {
5108 SDValue Arg = getValue(I.getArgOperand(0));
5109 EVT Ty = Arg.getValueType();
5110 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5113 case Intrinsic::stacksave: {
5114 SDValue Op = getRoot();
5115 Res = DAG.getNode(ISD::STACKSAVE, sdl,
5116 DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
5118 DAG.setRoot(Res.getValue(1));
5121 case Intrinsic::stackrestore: {
5122 Res = getValue(I.getArgOperand(0));
5123 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5126 case Intrinsic::stackprotector: {
5127 // Emit code into the DAG to store the stack guard onto the stack.
5128 MachineFunction &MF = DAG.getMachineFunction();
5129 MachineFrameInfo *MFI = MF.getFrameInfo();
5130 EVT PtrTy = TLI->getPointerTy();
5132 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5133 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5135 int FI = FuncInfo.StaticAllocaMap[Slot];
5136 MFI->setStackProtectorIndex(FI);
5138 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5140 // Store the stack protector onto the stack.
5141 Res = DAG.getStore(getRoot(), sdl, Src, FIN,
5142 MachinePointerInfo::getFixedStack(FI),
5148 case Intrinsic::objectsize: {
5149 // If we don't know by now, we're never going to know.
5150 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5152 assert(CI && "Non-constant type in __builtin_object_size?");
5154 SDValue Arg = getValue(I.getCalledValue());
5155 EVT Ty = Arg.getValueType();
5158 Res = DAG.getConstant(-1ULL, Ty);
5160 Res = DAG.getConstant(0, Ty);
5165 case Intrinsic::annotation:
5166 case Intrinsic::ptr_annotation:
5167 // Drop the intrinsic, but forward the value
5168 setValue(&I, getValue(I.getOperand(0)));
5170 case Intrinsic::var_annotation:
5171 // Discard annotate attributes
5174 case Intrinsic::init_trampoline: {
5175 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5179 Ops[1] = getValue(I.getArgOperand(0));
5180 Ops[2] = getValue(I.getArgOperand(1));
5181 Ops[3] = getValue(I.getArgOperand(2));
5182 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5183 Ops[5] = DAG.getSrcValue(F);
5185 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
5190 case Intrinsic::adjust_trampoline: {
5191 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5192 TLI->getPointerTy(),
5193 getValue(I.getArgOperand(0))));
5196 case Intrinsic::gcroot:
5198 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5199 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5201 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5202 GFI->addStackRoot(FI->getIndex(), TypeMap);
5205 case Intrinsic::gcread:
5206 case Intrinsic::gcwrite:
5207 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5208 case Intrinsic::flt_rounds:
5209 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5212 case Intrinsic::expect: {
5213 // Just replace __builtin_expect(exp, c) with EXP.
5214 setValue(&I, getValue(I.getArgOperand(0)));
5218 case Intrinsic::debugtrap:
5219 case Intrinsic::trap: {
5220 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5221 if (TrapFuncName.empty()) {
5222 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5223 ISD::TRAP : ISD::DEBUGTRAP;
5224 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5227 TargetLowering::ArgListTy Args;
5229 CallLoweringInfo CLI(getRoot(), I.getType(),
5230 false, false, false, false, 0, CallingConv::C,
5231 /*isTailCall=*/false,
5232 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
5233 DAG.getExternalSymbol(TrapFuncName.data(),
5234 TLI->getPointerTy()),
5236 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
5237 DAG.setRoot(Result.second);
5241 case Intrinsic::uadd_with_overflow:
5242 case Intrinsic::sadd_with_overflow:
5243 case Intrinsic::usub_with_overflow:
5244 case Intrinsic::ssub_with_overflow:
5245 case Intrinsic::umul_with_overflow:
5246 case Intrinsic::smul_with_overflow: {
5248 switch (Intrinsic) {
5249 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5250 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5251 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5252 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5253 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5254 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5255 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5257 SDValue Op1 = getValue(I.getArgOperand(0));
5258 SDValue Op2 = getValue(I.getArgOperand(1));
5260 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5261 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5264 case Intrinsic::prefetch: {
5266 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5268 Ops[1] = getValue(I.getArgOperand(0));
5269 Ops[2] = getValue(I.getArgOperand(1));
5270 Ops[3] = getValue(I.getArgOperand(2));
5271 Ops[4] = getValue(I.getArgOperand(3));
5272 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5273 DAG.getVTList(MVT::Other),
5275 EVT::getIntegerVT(*Context, 8),
5276 MachinePointerInfo(I.getArgOperand(0)),
5278 false, /* volatile */
5280 rw==1)); /* write */
5283 case Intrinsic::lifetime_start:
5284 case Intrinsic::lifetime_end: {
5285 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5286 // Stack coloring is not enabled in O0, discard region information.
5287 if (TM.getOptLevel() == CodeGenOpt::None)
5290 SmallVector<Value *, 4> Allocas;
5291 GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD);
5293 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5294 E = Allocas.end(); Object != E; ++Object) {
5295 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5297 // Could not find an Alloca.
5298 if (!LifetimeObject)
5301 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5305 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
5306 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5308 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
5313 case Intrinsic::invariant_start:
5314 // Discard region information.
5315 setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
5317 case Intrinsic::invariant_end:
5318 // Discard region information.
5320 case Intrinsic::stackprotectorcheck: {
5321 // Do not actually emit anything for this basic block. Instead we initialize
5322 // the stack protector descriptor and export the guard variable so we can
5323 // access it in FinishBasicBlock.
5324 const BasicBlock *BB = I.getParent();
5325 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5326 ExportFromCurrentBlock(SPDescriptor.getGuard());
5328 // Flush our exports since we are going to process a terminator.
5329 (void)getControlRoot();
5332 case Intrinsic::donothing:
5335 case Intrinsic::experimental_stackmap: {
5339 case Intrinsic::experimental_patchpoint_void:
5340 case Intrinsic::experimental_patchpoint_i64: {
5347 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5349 MachineBasicBlock *LandingPad) {
5350 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5351 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5352 Type *RetTy = FTy->getReturnType();
5353 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5354 MCSymbol *BeginLabel = 0;
5356 TargetLowering::ArgListTy Args;
5357 TargetLowering::ArgListEntry Entry;
5358 Args.reserve(CS.arg_size());
5360 // Check whether the function can return without sret-demotion.
5361 SmallVector<ISD::OutputArg, 4> Outs;
5362 const TargetLowering *TLI = TM.getTargetLowering();
5363 GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
5365 bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
5366 DAG.getMachineFunction(),
5367 FTy->isVarArg(), Outs,
5370 SDValue DemoteStackSlot;
5371 int DemoteStackIdx = -100;
5373 if (!CanLowerReturn) {
5374 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
5375 FTy->getReturnType());
5376 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(
5377 FTy->getReturnType());
5378 MachineFunction &MF = DAG.getMachineFunction();
5379 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5380 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
5382 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
5383 Entry.Node = DemoteStackSlot;
5384 Entry.Ty = StackSlotPtrType;
5385 Entry.isSExt = false;
5386 Entry.isZExt = false;
5387 Entry.isInReg = false;
5388 Entry.isSRet = true;
5389 Entry.isNest = false;
5390 Entry.isByVal = false;
5391 Entry.isReturned = false;
5392 Entry.Alignment = Align;
5393 Args.push_back(Entry);
5394 RetTy = Type::getVoidTy(FTy->getContext());
5397 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5399 const Value *V = *i;
5402 if (V->getType()->isEmptyTy())
5405 SDValue ArgNode = getValue(V);
5406 Entry.Node = ArgNode; Entry.Ty = V->getType();
5408 // Skip the first return-type Attribute to get to params.
5409 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5410 Args.push_back(Entry);
5414 // Insert a label before the invoke call to mark the try range. This can be
5415 // used to detect deletion of the invoke via the MachineModuleInfo.
5416 BeginLabel = MMI.getContext().CreateTempSymbol();
5418 // For SjLj, keep track of which landing pads go with which invokes
5419 // so as to maintain the ordering of pads in the LSDA.
5420 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5421 if (CallSiteIndex) {
5422 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5423 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5425 // Now that the call site is handled, stop tracking it.
5426 MMI.setCurrentCallSite(0);
5429 // Both PendingLoads and PendingExports must be flushed here;
5430 // this call might not return.
5432 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5435 // Check if target-independent constraints permit a tail call here.
5436 // Target-dependent constraints are checked within TLI->LowerCallTo.
5437 if (isTailCall && !isInTailCallPosition(CS, *TLI))
5441 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
5443 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
5444 assert((isTailCall || Result.second.getNode()) &&
5445 "Non-null chain expected with non-tail call!");
5446 assert((Result.second.getNode() || !Result.first.getNode()) &&
5447 "Null value expected with tail call!");
5448 if (Result.first.getNode()) {
5449 setValue(CS.getInstruction(), Result.first);
5450 } else if (!CanLowerReturn && Result.second.getNode()) {
5451 // The instruction result is the result of loading from the
5452 // hidden sret parameter.
5453 SmallVector<EVT, 1> PVTs;
5454 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5456 ComputeValueVTs(*TLI, PtrRetTy, PVTs);
5457 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5458 EVT PtrVT = PVTs[0];
5460 SmallVector<EVT, 4> RetTys;
5461 SmallVector<uint64_t, 4> Offsets;
5462 RetTy = FTy->getReturnType();
5463 ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
5465 unsigned NumValues = RetTys.size();
5466 SmallVector<SDValue, 4> Values(NumValues);
5467 SmallVector<SDValue, 4> Chains(NumValues);
5469 for (unsigned i = 0; i < NumValues; ++i) {
5470 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
5472 DAG.getConstant(Offsets[i], PtrVT));
5473 SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
5474 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5475 false, false, false, 1);
5477 Chains[i] = L.getValue(1);
5480 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
5481 MVT::Other, &Chains[0], NumValues);
5482 PendingLoads.push_back(Chain);
5484 setValue(CS.getInstruction(),
5485 DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
5486 DAG.getVTList(&RetTys[0], RetTys.size()),
5487 &Values[0], Values.size()));
5490 if (!Result.second.getNode()) {
5491 // As a special case, a null chain means that a tail call has been emitted
5492 // and the DAG root is already updated.
5495 // Since there's no actual continuation from this block, nothing can be
5496 // relying on us setting vregs for them.
5497 PendingExports.clear();
5499 DAG.setRoot(Result.second);
5503 // Insert a label at the end of the invoke call to mark the try range. This
5504 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5505 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5506 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5508 // Inform MachineModuleInfo of range.
5509 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5513 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5514 /// value is equal or not-equal to zero.
5515 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5516 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5518 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5519 if (IC->isEquality())
5520 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5521 if (C->isNullValue())
5523 // Unknown instruction.
5529 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5531 SelectionDAGBuilder &Builder) {
5533 // Check to see if this load can be trivially constant folded, e.g. if the
5534 // input is from a string literal.
5535 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5536 // Cast pointer to the type we really want to load.
5537 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5538 PointerType::getUnqual(LoadTy));
5540 if (const Constant *LoadCst =
5541 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5543 return Builder.getValue(LoadCst);
5546 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5547 // still constant memory, the input chain can be the entry node.
5549 bool ConstantMemory = false;
5551 // Do not serialize (non-volatile) loads of constant memory with anything.
5552 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5553 Root = Builder.DAG.getEntryNode();
5554 ConstantMemory = true;
5556 // Do not serialize non-volatile loads against each other.
5557 Root = Builder.DAG.getRoot();
5560 SDValue Ptr = Builder.getValue(PtrVal);
5561 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5562 Ptr, MachinePointerInfo(PtrVal),
5564 false /*nontemporal*/,
5565 false /*isinvariant*/, 1 /* align=1 */);
5567 if (!ConstantMemory)
5568 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5572 /// processIntegerCallValue - Record the value for an instruction that
5573 /// produces an integer result, converting the type where necessary.
5574 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5577 EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
5579 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5581 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5582 setValue(&I, Value);
5585 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5586 /// If so, return true and lower it, otherwise return false and it will be
5587 /// lowered like a normal call.
5588 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5589 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5590 if (I.getNumArgOperands() != 3)
5593 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5594 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5595 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5596 !I.getType()->isIntegerTy())
5599 const Value *Size = I.getArgOperand(2);
5600 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5601 if (CSize && CSize->getZExtValue() == 0) {
5602 EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
5603 setValue(&I, DAG.getConstant(0, CallVT));
5607 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5608 std::pair<SDValue, SDValue> Res =
5609 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5610 getValue(LHS), getValue(RHS), getValue(Size),
5611 MachinePointerInfo(LHS),
5612 MachinePointerInfo(RHS));
5613 if (Res.first.getNode()) {
5614 processIntegerCallValue(I, Res.first, true);
5615 PendingLoads.push_back(Res.second);
5619 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5620 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5621 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5622 bool ActuallyDoIt = true;
5625 switch (CSize->getZExtValue()) {
5627 LoadVT = MVT::Other;
5629 ActuallyDoIt = false;
5633 LoadTy = Type::getInt16Ty(CSize->getContext());
5637 LoadTy = Type::getInt32Ty(CSize->getContext());
5641 LoadTy = Type::getInt64Ty(CSize->getContext());
5645 LoadVT = MVT::v4i32;
5646 LoadTy = Type::getInt32Ty(CSize->getContext());
5647 LoadTy = VectorType::get(LoadTy, 4);
5652 // This turns into unaligned loads. We only do this if the target natively
5653 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5654 // we'll only produce a small number of byte loads.
5656 // Require that we can find a legal MVT, and only do this if the target
5657 // supports unaligned loads of that type. Expanding into byte loads would
5659 const TargetLowering *TLI = TM.getTargetLowering();
5660 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5661 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5662 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5663 if (!TLI->isTypeLegal(LoadVT) ||!TLI->allowsUnalignedMemoryAccesses(LoadVT))
5664 ActuallyDoIt = false;
5668 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5669 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5671 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5673 processIntegerCallValue(I, Res, false);
5682 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5683 /// form. If so, return true and lower it, otherwise return false and it
5684 /// will be lowered like a normal call.
5685 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5686 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5687 if (I.getNumArgOperands() != 3)
5690 const Value *Src = I.getArgOperand(0);
5691 const Value *Char = I.getArgOperand(1);
5692 const Value *Length = I.getArgOperand(2);
5693 if (!Src->getType()->isPointerTy() ||
5694 !Char->getType()->isIntegerTy() ||
5695 !Length->getType()->isIntegerTy() ||
5696 !I.getType()->isPointerTy())
5699 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5700 std::pair<SDValue, SDValue> Res =
5701 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5702 getValue(Src), getValue(Char), getValue(Length),
5703 MachinePointerInfo(Src));
5704 if (Res.first.getNode()) {
5705 setValue(&I, Res.first);
5706 PendingLoads.push_back(Res.second);
5713 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5714 /// optimized form. If so, return true and lower it, otherwise return false
5715 /// and it will be lowered like a normal call.
5716 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5717 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5718 if (I.getNumArgOperands() != 2)
5721 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5722 if (!Arg0->getType()->isPointerTy() ||
5723 !Arg1->getType()->isPointerTy() ||
5724 !I.getType()->isPointerTy())
5727 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5728 std::pair<SDValue, SDValue> Res =
5729 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5730 getValue(Arg0), getValue(Arg1),
5731 MachinePointerInfo(Arg0),
5732 MachinePointerInfo(Arg1), isStpcpy);
5733 if (Res.first.getNode()) {
5734 setValue(&I, Res.first);
5735 DAG.setRoot(Res.second);
5742 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5743 /// If so, return true and lower it, otherwise return false and it will be
5744 /// lowered like a normal call.
5745 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5746 // Verify that the prototype makes sense. int strcmp(void*,void*)
5747 if (I.getNumArgOperands() != 2)
5750 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5751 if (!Arg0->getType()->isPointerTy() ||
5752 !Arg1->getType()->isPointerTy() ||
5753 !I.getType()->isIntegerTy())
5756 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5757 std::pair<SDValue, SDValue> Res =
5758 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5759 getValue(Arg0), getValue(Arg1),
5760 MachinePointerInfo(Arg0),
5761 MachinePointerInfo(Arg1));
5762 if (Res.first.getNode()) {
5763 processIntegerCallValue(I, Res.first, true);
5764 PendingLoads.push_back(Res.second);
5771 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5772 /// form. If so, return true and lower it, otherwise return false and it
5773 /// will be lowered like a normal call.
5774 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5775 // Verify that the prototype makes sense. size_t strlen(char *)
5776 if (I.getNumArgOperands() != 1)
5779 const Value *Arg0 = I.getArgOperand(0);
5780 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5783 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5784 std::pair<SDValue, SDValue> Res =
5785 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5786 getValue(Arg0), MachinePointerInfo(Arg0));
5787 if (Res.first.getNode()) {
5788 processIntegerCallValue(I, Res.first, false);
5789 PendingLoads.push_back(Res.second);
5796 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5797 /// form. If so, return true and lower it, otherwise return false and it
5798 /// will be lowered like a normal call.
5799 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5800 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5801 if (I.getNumArgOperands() != 2)
5804 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5805 if (!Arg0->getType()->isPointerTy() ||
5806 !Arg1->getType()->isIntegerTy() ||
5807 !I.getType()->isIntegerTy())
5810 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5811 std::pair<SDValue, SDValue> Res =
5812 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5813 getValue(Arg0), getValue(Arg1),
5814 MachinePointerInfo(Arg0));
5815 if (Res.first.getNode()) {
5816 processIntegerCallValue(I, Res.first, false);
5817 PendingLoads.push_back(Res.second);
5824 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5825 /// operation (as expected), translate it to an SDNode with the specified opcode
5826 /// and return true.
5827 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5829 // Sanity check that it really is a unary floating-point call.
5830 if (I.getNumArgOperands() != 1 ||
5831 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5832 I.getType() != I.getArgOperand(0)->getType() ||
5833 !I.onlyReadsMemory())
5836 SDValue Tmp = getValue(I.getArgOperand(0));
5837 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5841 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5842 // Handle inline assembly differently.
5843 if (isa<InlineAsm>(I.getCalledValue())) {
5848 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5849 ComputeUsesVAFloatArgument(I, &MMI);
5851 const char *RenameFn = 0;
5852 if (Function *F = I.getCalledFunction()) {
5853 if (F->isDeclaration()) {
5854 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5855 if (unsigned IID = II->getIntrinsicID(F)) {
5856 RenameFn = visitIntrinsicCall(I, IID);
5861 if (unsigned IID = F->getIntrinsicID()) {
5862 RenameFn = visitIntrinsicCall(I, IID);
5868 // Check for well-known libc/libm calls. If the function is internal, it
5869 // can't be a library call.
5871 if (!F->hasLocalLinkage() && F->hasName() &&
5872 LibInfo->getLibFunc(F->getName(), Func) &&
5873 LibInfo->hasOptimizedCodeGen(Func)) {
5876 case LibFunc::copysign:
5877 case LibFunc::copysignf:
5878 case LibFunc::copysignl:
5879 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5880 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5881 I.getType() == I.getArgOperand(0)->getType() &&
5882 I.getType() == I.getArgOperand(1)->getType() &&
5883 I.onlyReadsMemory()) {
5884 SDValue LHS = getValue(I.getArgOperand(0));
5885 SDValue RHS = getValue(I.getArgOperand(1));
5886 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5887 LHS.getValueType(), LHS, RHS));
5892 case LibFunc::fabsf:
5893 case LibFunc::fabsl:
5894 if (visitUnaryFloatCall(I, ISD::FABS))
5900 if (visitUnaryFloatCall(I, ISD::FSIN))
5906 if (visitUnaryFloatCall(I, ISD::FCOS))
5910 case LibFunc::sqrtf:
5911 case LibFunc::sqrtl:
5912 case LibFunc::sqrt_finite:
5913 case LibFunc::sqrtf_finite:
5914 case LibFunc::sqrtl_finite:
5915 if (visitUnaryFloatCall(I, ISD::FSQRT))
5918 case LibFunc::floor:
5919 case LibFunc::floorf:
5920 case LibFunc::floorl:
5921 if (visitUnaryFloatCall(I, ISD::FFLOOR))
5924 case LibFunc::nearbyint:
5925 case LibFunc::nearbyintf:
5926 case LibFunc::nearbyintl:
5927 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
5931 case LibFunc::ceilf:
5932 case LibFunc::ceill:
5933 if (visitUnaryFloatCall(I, ISD::FCEIL))
5937 case LibFunc::rintf:
5938 case LibFunc::rintl:
5939 if (visitUnaryFloatCall(I, ISD::FRINT))
5942 case LibFunc::round:
5943 case LibFunc::roundf:
5944 case LibFunc::roundl:
5945 if (visitUnaryFloatCall(I, ISD::FROUND))
5948 case LibFunc::trunc:
5949 case LibFunc::truncf:
5950 case LibFunc::truncl:
5951 if (visitUnaryFloatCall(I, ISD::FTRUNC))
5955 case LibFunc::log2f:
5956 case LibFunc::log2l:
5957 if (visitUnaryFloatCall(I, ISD::FLOG2))
5961 case LibFunc::exp2f:
5962 case LibFunc::exp2l:
5963 if (visitUnaryFloatCall(I, ISD::FEXP2))
5966 case LibFunc::memcmp:
5967 if (visitMemCmpCall(I))
5970 case LibFunc::memchr:
5971 if (visitMemChrCall(I))
5974 case LibFunc::strcpy:
5975 if (visitStrCpyCall(I, false))
5978 case LibFunc::stpcpy:
5979 if (visitStrCpyCall(I, true))
5982 case LibFunc::strcmp:
5983 if (visitStrCmpCall(I))
5986 case LibFunc::strlen:
5987 if (visitStrLenCall(I))
5990 case LibFunc::strnlen:
5991 if (visitStrNLenCall(I))
6000 Callee = getValue(I.getCalledValue());
6002 Callee = DAG.getExternalSymbol(RenameFn,
6003 TM.getTargetLowering()->getPointerTy());
6005 // Check if we can potentially perform a tail call. More detailed checking is
6006 // be done within LowerCallTo, after more information about the call is known.
6007 LowerCallTo(&I, Callee, I.isTailCall());
6012 /// AsmOperandInfo - This contains information for each constraint that we are
6014 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6016 /// CallOperand - If this is the result output operand or a clobber
6017 /// this is null, otherwise it is the incoming operand to the CallInst.
6018 /// This gets modified as the asm is processed.
6019 SDValue CallOperand;
6021 /// AssignedRegs - If this is a register or register class operand, this
6022 /// contains the set of register corresponding to the operand.
6023 RegsForValue AssignedRegs;
6025 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6026 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
6029 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6030 /// corresponds to. If there is no Value* for this operand, it returns
6032 EVT getCallOperandValEVT(LLVMContext &Context,
6033 const TargetLowering &TLI,
6034 const DataLayout *TD) const {
6035 if (CallOperandVal == 0) return MVT::Other;
6037 if (isa<BasicBlock>(CallOperandVal))
6038 return TLI.getPointerTy();
6040 llvm::Type *OpTy = CallOperandVal->getType();
6042 // FIXME: code duplicated from TargetLowering::ParseConstraints().
6043 // If this is an indirect operand, the operand is a pointer to the
6046 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6048 report_fatal_error("Indirect operand for inline asm not a pointer!");
6049 OpTy = PtrTy->getElementType();
6052 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6053 if (StructType *STy = dyn_cast<StructType>(OpTy))
6054 if (STy->getNumElements() == 1)
6055 OpTy = STy->getElementType(0);
6057 // If OpTy is not a single value, it may be a struct/union that we
6058 // can tile with integers.
6059 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6060 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
6069 OpTy = IntegerType::get(Context, BitSize);
6074 return TLI.getValueType(OpTy, true);
6078 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6080 } // end anonymous namespace
6082 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6083 /// specified operand. We prefer to assign virtual registers, to allow the
6084 /// register allocator to handle the assignment process. However, if the asm
6085 /// uses features that we can't model on machineinstrs, we have SDISel do the
6086 /// allocation. This produces generally horrible, but correct, code.
6088 /// OpInfo describes the operand.
6090 static void GetRegistersForValue(SelectionDAG &DAG,
6091 const TargetLowering &TLI,
6093 SDISelAsmOperandInfo &OpInfo) {
6094 LLVMContext &Context = *DAG.getContext();
6096 MachineFunction &MF = DAG.getMachineFunction();
6097 SmallVector<unsigned, 4> Regs;
6099 // If this is a constraint for a single physreg, or a constraint for a
6100 // register class, find it.
6101 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
6102 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6103 OpInfo.ConstraintVT);
6105 unsigned NumRegs = 1;
6106 if (OpInfo.ConstraintVT != MVT::Other) {
6107 // If this is a FP input in an integer register (or visa versa) insert a bit
6108 // cast of the input value. More generally, handle any case where the input
6109 // value disagrees with the register class we plan to stick this in.
6110 if (OpInfo.Type == InlineAsm::isInput &&
6111 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6112 // Try to convert to the first EVT that the reg class contains. If the
6113 // types are identical size, use a bitcast to convert (e.g. two differing
6115 MVT RegVT = *PhysReg.second->vt_begin();
6116 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
6117 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6118 RegVT, OpInfo.CallOperand);
6119 OpInfo.ConstraintVT = RegVT;
6120 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6121 // If the input is a FP value and we want it in FP registers, do a
6122 // bitcast to the corresponding integer type. This turns an f64 value
6123 // into i64, which can be passed with two i32 values on a 32-bit
6125 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6126 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6127 RegVT, OpInfo.CallOperand);
6128 OpInfo.ConstraintVT = RegVT;
6132 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6136 EVT ValueVT = OpInfo.ConstraintVT;
6138 // If this is a constraint for a specific physical register, like {r17},
6140 if (unsigned AssignedReg = PhysReg.first) {
6141 const TargetRegisterClass *RC = PhysReg.second;
6142 if (OpInfo.ConstraintVT == MVT::Other)
6143 ValueVT = *RC->vt_begin();
6145 // Get the actual register value type. This is important, because the user
6146 // may have asked for (e.g.) the AX register in i32 type. We need to
6147 // remember that AX is actually i16 to get the right extension.
6148 RegVT = *RC->vt_begin();
6150 // This is a explicit reference to a physical register.
6151 Regs.push_back(AssignedReg);
6153 // If this is an expanded reference, add the rest of the regs to Regs.
6155 TargetRegisterClass::iterator I = RC->begin();
6156 for (; *I != AssignedReg; ++I)
6157 assert(I != RC->end() && "Didn't find reg!");
6159 // Already added the first reg.
6161 for (; NumRegs; --NumRegs, ++I) {
6162 assert(I != RC->end() && "Ran out of registers to allocate!");
6167 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6171 // Otherwise, if this was a reference to an LLVM register class, create vregs
6172 // for this reference.
6173 if (const TargetRegisterClass *RC = PhysReg.second) {
6174 RegVT = *RC->vt_begin();
6175 if (OpInfo.ConstraintVT == MVT::Other)
6178 // Create the appropriate number of virtual registers.
6179 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6180 for (; NumRegs; --NumRegs)
6181 Regs.push_back(RegInfo.createVirtualRegister(RC));
6183 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6187 // Otherwise, we couldn't allocate enough registers for this.
6190 /// visitInlineAsm - Handle a call to an InlineAsm object.
6192 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6193 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6195 /// ConstraintOperands - Information about all of the constraints.
6196 SDISelAsmOperandInfoVector ConstraintOperands;
6198 const TargetLowering *TLI = TM.getTargetLowering();
6199 TargetLowering::AsmOperandInfoVector
6200 TargetConstraints = TLI->ParseConstraints(CS);
6202 bool hasMemory = false;
6204 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6205 unsigned ResNo = 0; // ResNo - The result number of the next output.
6206 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6207 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6208 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6210 MVT OpVT = MVT::Other;
6212 // Compute the value type for each operand.
6213 switch (OpInfo.Type) {
6214 case InlineAsm::isOutput:
6215 // Indirect outputs just consume an argument.
6216 if (OpInfo.isIndirect) {
6217 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6221 // The return value of the call is this value. As such, there is no
6222 // corresponding argument.
6223 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6224 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6225 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
6227 assert(ResNo == 0 && "Asm only has one result!");
6228 OpVT = TLI->getSimpleValueType(CS.getType());
6232 case InlineAsm::isInput:
6233 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6235 case InlineAsm::isClobber:
6240 // If this is an input or an indirect output, process the call argument.
6241 // BasicBlocks are labels, currently appearing only in asm's.
6242 if (OpInfo.CallOperandVal) {
6243 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6244 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6246 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6249 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, TD).
6253 OpInfo.ConstraintVT = OpVT;
6255 // Indirect operand accesses access memory.
6256 if (OpInfo.isIndirect)
6259 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6260 TargetLowering::ConstraintType
6261 CType = TLI->getConstraintType(OpInfo.Codes[j]);
6262 if (CType == TargetLowering::C_Memory) {
6270 SDValue Chain, Flag;
6272 // We won't need to flush pending loads if this asm doesn't touch
6273 // memory and is nonvolatile.
6274 if (hasMemory || IA->hasSideEffects())
6277 Chain = DAG.getRoot();
6279 // Second pass over the constraints: compute which constraint option to use
6280 // and assign registers to constraints that want a specific physreg.
6281 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6282 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6284 // If this is an output operand with a matching input operand, look up the
6285 // matching input. If their types mismatch, e.g. one is an integer, the
6286 // other is floating point, or their sizes are different, flag it as an
6288 if (OpInfo.hasMatchingInput()) {
6289 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6291 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6292 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6293 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6294 OpInfo.ConstraintVT);
6295 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6296 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
6297 Input.ConstraintVT);
6298 if ((OpInfo.ConstraintVT.isInteger() !=
6299 Input.ConstraintVT.isInteger()) ||
6300 (MatchRC.second != InputRC.second)) {
6301 report_fatal_error("Unsupported asm: input constraint"
6302 " with a matching output constraint of"
6303 " incompatible type!");
6305 Input.ConstraintVT = OpInfo.ConstraintVT;
6309 // Compute the constraint code and ConstraintType to use.
6310 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6312 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6313 OpInfo.Type == InlineAsm::isClobber)
6316 // If this is a memory input, and if the operand is not indirect, do what we
6317 // need to to provide an address for the memory input.
6318 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6319 !OpInfo.isIndirect) {
6320 assert((OpInfo.isMultipleAlternative ||
6321 (OpInfo.Type == InlineAsm::isInput)) &&
6322 "Can only indirectify direct input operands!");
6324 // Memory operands really want the address of the value. If we don't have
6325 // an indirect input, put it in the constpool if we can, otherwise spill
6326 // it to a stack slot.
6327 // TODO: This isn't quite right. We need to handle these according to
6328 // the addressing mode that the constraint wants. Also, this may take
6329 // an additional register for the computation and we don't want that
6332 // If the operand is a float, integer, or vector constant, spill to a
6333 // constant pool entry to get its address.
6334 const Value *OpVal = OpInfo.CallOperandVal;
6335 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6336 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6337 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6338 TLI->getPointerTy());
6340 // Otherwise, create a stack slot and emit a store to it before the
6342 Type *Ty = OpVal->getType();
6343 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
6344 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
6345 MachineFunction &MF = DAG.getMachineFunction();
6346 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6347 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
6348 Chain = DAG.getStore(Chain, getCurSDLoc(),
6349 OpInfo.CallOperand, StackSlot,
6350 MachinePointerInfo::getFixedStack(SSFI),
6352 OpInfo.CallOperand = StackSlot;
6355 // There is no longer a Value* corresponding to this operand.
6356 OpInfo.CallOperandVal = 0;
6358 // It is now an indirect operand.
6359 OpInfo.isIndirect = true;
6362 // If this constraint is for a specific register, allocate it before
6364 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6365 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6368 // Second pass - Loop over all of the operands, assigning virtual or physregs
6369 // to register class operands.
6370 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6371 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6373 // C_Register operands have already been allocated, Other/Memory don't need
6375 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6376 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6379 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6380 std::vector<SDValue> AsmNodeOperands;
6381 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6382 AsmNodeOperands.push_back(
6383 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6384 TLI->getPointerTy()));
6386 // If we have a !srcloc metadata node associated with it, we want to attach
6387 // this to the ultimately generated inline asm machineinstr. To do this, we
6388 // pass in the third operand as this (potentially null) inline asm MDNode.
6389 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6390 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6392 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6393 // bits as operand 3.
6394 unsigned ExtraInfo = 0;
6395 if (IA->hasSideEffects())
6396 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6397 if (IA->isAlignStack())
6398 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6399 // Set the asm dialect.
6400 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6402 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6403 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6404 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6406 // Compute the constraint code and ConstraintType to use.
6407 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6409 // Ideally, we would only check against memory constraints. However, the
6410 // meaning of an other constraint can be target-specific and we can't easily
6411 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6412 // for other constriants as well.
6413 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6414 OpInfo.ConstraintType == TargetLowering::C_Other) {
6415 if (OpInfo.Type == InlineAsm::isInput)
6416 ExtraInfo |= InlineAsm::Extra_MayLoad;
6417 else if (OpInfo.Type == InlineAsm::isOutput)
6418 ExtraInfo |= InlineAsm::Extra_MayStore;
6419 else if (OpInfo.Type == InlineAsm::isClobber)
6420 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6424 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6425 TLI->getPointerTy()));
6427 // Loop over all of the inputs, copying the operand values into the
6428 // appropriate registers and processing the output regs.
6429 RegsForValue RetValRegs;
6431 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6432 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6434 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6435 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6437 switch (OpInfo.Type) {
6438 case InlineAsm::isOutput: {
6439 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6440 OpInfo.ConstraintType != TargetLowering::C_Register) {
6441 // Memory output, or 'other' output (e.g. 'X' constraint).
6442 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6444 // Add information to the INLINEASM node to know about this output.
6445 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6446 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6447 TLI->getPointerTy()));
6448 AsmNodeOperands.push_back(OpInfo.CallOperand);
6452 // Otherwise, this is a register or register class output.
6454 // Copy the output from the appropriate register. Find a register that
6456 if (OpInfo.AssignedRegs.Regs.empty()) {
6457 LLVMContext &Ctx = *DAG.getContext();
6458 Ctx.emitError(CS.getInstruction(),
6459 "couldn't allocate output register for constraint '" +
6460 Twine(OpInfo.ConstraintCode) + "'");
6464 // If this is an indirect operand, store through the pointer after the
6466 if (OpInfo.isIndirect) {
6467 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6468 OpInfo.CallOperandVal));
6470 // This is the result value of the call.
6471 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6472 // Concatenate this output onto the outputs list.
6473 RetValRegs.append(OpInfo.AssignedRegs);
6476 // Add information to the INLINEASM node to know that this register is
6479 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6480 ? InlineAsm::Kind_RegDefEarlyClobber
6481 : InlineAsm::Kind_RegDef,
6482 false, 0, DAG, AsmNodeOperands);
6485 case InlineAsm::isInput: {
6486 SDValue InOperandVal = OpInfo.CallOperand;
6488 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6489 // If this is required to match an output register we have already set,
6490 // just use its register.
6491 unsigned OperandNo = OpInfo.getMatchedOperand();
6493 // Scan until we find the definition we already emitted of this operand.
6494 // When we find it, create a RegsForValue operand.
6495 unsigned CurOp = InlineAsm::Op_FirstOperand;
6496 for (; OperandNo; --OperandNo) {
6497 // Advance to the next operand.
6499 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6500 assert((InlineAsm::isRegDefKind(OpFlag) ||
6501 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6502 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6503 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6507 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6508 if (InlineAsm::isRegDefKind(OpFlag) ||
6509 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6510 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6511 if (OpInfo.isIndirect) {
6512 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6513 LLVMContext &Ctx = *DAG.getContext();
6514 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6515 " don't know how to handle tied "
6516 "indirect register inputs");
6520 RegsForValue MatchedRegs;
6521 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6522 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6523 MatchedRegs.RegVTs.push_back(RegVT);
6524 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6525 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6527 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
6528 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6530 LLVMContext &Ctx = *DAG.getContext();
6531 Ctx.emitError(CS.getInstruction(),
6532 "inline asm error: This value"
6533 " type register class is not natively supported!");
6537 // Use the produced MatchedRegs object to
6538 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6539 Chain, &Flag, CS.getInstruction());
6540 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6541 true, OpInfo.getMatchedOperand(),
6542 DAG, AsmNodeOperands);
6546 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6547 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6548 "Unexpected number of operands");
6549 // Add information to the INLINEASM node to know about this input.
6550 // See InlineAsm.h isUseOperandTiedToDef.
6551 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6552 OpInfo.getMatchedOperand());
6553 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6554 TLI->getPointerTy()));
6555 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6559 // Treat indirect 'X' constraint as memory.
6560 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6562 OpInfo.ConstraintType = TargetLowering::C_Memory;
6564 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6565 std::vector<SDValue> Ops;
6566 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6569 LLVMContext &Ctx = *DAG.getContext();
6570 Ctx.emitError(CS.getInstruction(),
6571 "invalid operand for inline asm constraint '" +
6572 Twine(OpInfo.ConstraintCode) + "'");
6576 // Add information to the INLINEASM node to know about this input.
6577 unsigned ResOpType =
6578 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6579 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6580 TLI->getPointerTy()));
6581 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6585 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6586 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6587 assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
6588 "Memory operands expect pointer values");
6590 // Add information to the INLINEASM node to know about this input.
6591 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6592 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6593 TLI->getPointerTy()));
6594 AsmNodeOperands.push_back(InOperandVal);
6598 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6599 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6600 "Unknown constraint type!");
6602 // TODO: Support this.
6603 if (OpInfo.isIndirect) {
6604 LLVMContext &Ctx = *DAG.getContext();
6605 Ctx.emitError(CS.getInstruction(),
6606 "Don't know how to handle indirect register inputs yet "
6607 "for constraint '" +
6608 Twine(OpInfo.ConstraintCode) + "'");
6612 // Copy the input into the appropriate registers.
6613 if (OpInfo.AssignedRegs.Regs.empty()) {
6614 LLVMContext &Ctx = *DAG.getContext();
6615 Ctx.emitError(CS.getInstruction(),
6616 "couldn't allocate input reg for constraint '" +
6617 Twine(OpInfo.ConstraintCode) + "'");
6621 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6622 Chain, &Flag, CS.getInstruction());
6624 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6625 DAG, AsmNodeOperands);
6628 case InlineAsm::isClobber: {
6629 // Add the clobbered value to the operand list, so that the register
6630 // allocator is aware that the physreg got clobbered.
6631 if (!OpInfo.AssignedRegs.Regs.empty())
6632 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6640 // Finish up input operands. Set the input chain and add the flag last.
6641 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6642 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6644 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6645 DAG.getVTList(MVT::Other, MVT::Glue),
6646 &AsmNodeOperands[0], AsmNodeOperands.size());
6647 Flag = Chain.getValue(1);
6649 // If this asm returns a register value, copy the result from that register
6650 // and set it as the value of the call.
6651 if (!RetValRegs.Regs.empty()) {
6652 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6653 Chain, &Flag, CS.getInstruction());
6655 // FIXME: Why don't we do this for inline asms with MRVs?
6656 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6657 EVT ResultType = TLI->getValueType(CS.getType());
6659 // If any of the results of the inline asm is a vector, it may have the
6660 // wrong width/num elts. This can happen for register classes that can
6661 // contain multiple different value types. The preg or vreg allocated may
6662 // not have the same VT as was expected. Convert it to the right type
6663 // with bit_convert.
6664 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6665 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6668 } else if (ResultType != Val.getValueType() &&
6669 ResultType.isInteger() && Val.getValueType().isInteger()) {
6670 // If a result value was tied to an input value, the computed result may
6671 // have a wider width than the expected result. Extract the relevant
6673 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6676 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6679 setValue(CS.getInstruction(), Val);
6680 // Don't need to use this as a chain in this case.
6681 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6685 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6687 // Process indirect outputs, first output all of the flagged copies out of
6689 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6690 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6691 const Value *Ptr = IndirectStoresToEmit[i].second;
6692 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6694 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6697 // Emit the non-flagged stores from the physregs.
6698 SmallVector<SDValue, 8> OutChains;
6699 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6700 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6701 StoresToEmit[i].first,
6702 getValue(StoresToEmit[i].second),
6703 MachinePointerInfo(StoresToEmit[i].second),
6705 OutChains.push_back(Val);
6708 if (!OutChains.empty())
6709 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
6710 &OutChains[0], OutChains.size());
6715 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6716 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6717 MVT::Other, getRoot(),
6718 getValue(I.getArgOperand(0)),
6719 DAG.getSrcValue(I.getArgOperand(0))));
6722 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6723 const TargetLowering *TLI = TM.getTargetLowering();
6724 const DataLayout &TD = *TLI->getDataLayout();
6725 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
6726 getRoot(), getValue(I.getOperand(0)),
6727 DAG.getSrcValue(I.getOperand(0)),
6728 TD.getABITypeAlignment(I.getType()));
6730 DAG.setRoot(V.getValue(1));
6733 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6734 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6735 MVT::Other, getRoot(),
6736 getValue(I.getArgOperand(0)),
6737 DAG.getSrcValue(I.getArgOperand(0))));
6740 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6741 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6742 MVT::Other, getRoot(),
6743 getValue(I.getArgOperand(0)),
6744 getValue(I.getArgOperand(1)),
6745 DAG.getSrcValue(I.getArgOperand(0)),
6746 DAG.getSrcValue(I.getArgOperand(1))));
6749 /// \brief Lower an argument list according to the target calling convention.
6751 /// \return A tuple of <return-value, token-chain>
6753 /// This is a helper for lowering intrinsics that follow a target calling
6754 /// convention or require stack pointer adjustment. Only a subset of the
6755 /// intrinsic's operands need to participate in the calling convention.
6756 std::pair<SDValue, SDValue>
6757 SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
6758 unsigned NumArgs, SDValue Callee,
6760 TargetLowering::ArgListTy Args;
6761 Args.reserve(NumArgs);
6763 // Populate the argument list.
6764 // Attributes for args start at offset 1, after the return attribute.
6765 ImmutableCallSite CS(&CI);
6766 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6767 ArgI != ArgE; ++ArgI) {
6768 const Value *V = CI.getOperand(ArgI);
6770 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6772 TargetLowering::ArgListEntry Entry;
6773 Entry.Node = getValue(V);
6774 Entry.Ty = V->getType();
6775 Entry.setAttributes(&CS, AttrI);
6776 Args.push_back(Entry);
6779 Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
6780 TargetLowering::CallLoweringInfo CLI(getRoot(), retTy, /*retSExt*/ false,
6781 /*retZExt*/ false, /*isVarArg*/ false, /*isInReg*/ false, NumArgs,
6782 CI.getCallingConv(), /*isTailCall*/ false, /*doesNotReturn*/ false,
6783 /*isReturnValueUsed*/ CI.use_empty(), Callee, Args, DAG, getCurSDLoc());
6785 const TargetLowering *TLI = TM.getTargetLowering();
6786 return TLI->LowerCallTo(CLI);
6789 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6790 /// or patchpoint target node's operand list.
6792 /// Constants are converted to TargetConstants purely as an optimization to
6793 /// avoid constant materialization and register allocation.
6795 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6796 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6797 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6798 /// address materialization and register allocation, but may also be required
6799 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6800 /// alloca in the entry block, then the runtime may assume that the alloca's
6801 /// StackMap location can be read immediately after compilation and that the
6802 /// location is valid at any point during execution (this is similar to the
6803 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6804 /// only available in a register, then the runtime would need to trap when
6805 /// execution reaches the StackMap in order to read the alloca's location.
6806 static void addStackMapLiveVars(const CallInst &CI, unsigned StartIdx,
6807 SmallVectorImpl<SDValue> &Ops,
6808 SelectionDAGBuilder &Builder) {
6809 for (unsigned i = StartIdx, e = CI.getNumArgOperands(); i != e; ++i) {
6810 SDValue OpVal = Builder.getValue(CI.getArgOperand(i));
6811 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6813 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6815 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
6816 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6817 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6819 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
6821 Ops.push_back(OpVal);
6825 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6826 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6827 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6828 // [live variables...])
6830 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6832 SDValue Callee = getValue(CI.getCalledValue());
6834 // Lower into a call sequence with no args and no return value.
6835 std::pair<SDValue, SDValue> Result = LowerCallOperands(CI, 0, 0, Callee);
6836 // Set the root to the target-lowered call chain.
6837 SDValue Chain = Result.second;
6840 /// Get a call instruction from the call sequence chain.
6841 /// Tail calls are not allowed.
6842 SDNode *CallEnd = Chain.getNode();
6843 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6844 "Expected a callseq node.");
6845 SDNode *Call = CallEnd->getOperand(0).getNode();
6846 bool hasGlue = Call->getGluedNode();
6848 // Replace the target specific call node with the stackmap intrinsic.
6849 SmallVector<SDValue, 8> Ops;
6851 // Add the <id> and <numShadowBytes> constants.
6852 for (unsigned i = 0; i < 2; ++i) {
6853 SDValue tmp = getValue(CI.getOperand(i));
6854 Ops.push_back(DAG.getTargetConstant(
6855 cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
6857 // Push live variables for the stack map.
6858 addStackMapLiveVars(CI, 2, Ops, *this);
6860 // Push the chain (this is originally the first operand of the call, but
6861 // becomes now the last or second to last operand).
6862 Ops.push_back(*(Call->op_begin()));
6864 // Push the glue flag (last operand).
6866 Ops.push_back(*(Call->op_end()-1));
6868 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6870 // Replace the target specific call node with a STACKMAP node.
6871 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::STACKMAP, getCurSDLoc(),
6874 // StackMap generates no value, so nothing goes in the NodeMap.
6876 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6878 DAG.ReplaceAllUsesWith(Call, MN);
6880 DAG.DeleteNode(Call);
6883 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6884 void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
6885 // void|i64 @llvm.experimental.patchpoint.void|i64(i32 <id>,
6890 // [live variables...])
6892 CallingConv::ID CC = CI.getCallingConv();
6893 bool isAnyRegCC = CC == CallingConv::AnyReg;
6894 bool hasDef = !CI.getType()->isVoidTy();
6895 SDValue Callee = getValue(CI.getOperand(2)); // <target>
6897 // Get the real number of arguments participating in the call <numArgs>
6898 SDValue NArgVal = getValue(CI.getArgOperand(PatchPointOpers::NArgPos));
6899 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
6901 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6902 // Intrinsics include all meta-operands up to but not including CC.
6903 unsigned NumMetaOpers = PatchPointOpers::CCPos;
6904 assert(CI.getNumArgOperands() >= NumMetaOpers + NumArgs &&
6905 "Not enough arguments provided to the patchpoint intrinsic");
6907 // For AnyRegCC the arguments are lowered later on manually.
6908 unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
6909 std::pair<SDValue, SDValue> Result =
6910 LowerCallOperands(CI, NumMetaOpers, NumCallArgs, Callee, isAnyRegCC);
6912 // Set the root to the target-lowered call chain.
6913 SDValue Chain = Result.second;
6916 SDNode *CallEnd = Chain.getNode();
6917 if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6918 CallEnd = CallEnd->getOperand(0).getNode();
6920 /// Get a call instruction from the call sequence chain.
6921 /// Tail calls are not allowed.
6922 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6923 "Expected a callseq node.");
6924 SDNode *Call = CallEnd->getOperand(0).getNode();
6925 bool hasGlue = Call->getGluedNode();
6927 // Replace the target specific call node with the patchable intrinsic.
6928 SmallVector<SDValue, 8> Ops;
6930 // Add the <id> and <numBytes> constants.
6931 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6932 Ops.push_back(DAG.getTargetConstant(
6933 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i32));
6934 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6935 Ops.push_back(DAG.getTargetConstant(
6936 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
6938 // Assume that the Callee is a constant address.
6939 // FIXME: handle function symbols in the future.
6941 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
6942 /*isTarget=*/true));
6944 // Adjust <numArgs> to account for any arguments that have been passed on the
6946 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
6947 unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
6948 NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
6949 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
6951 // Add the calling convention
6952 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
6954 // Add the arguments we omitted previously. The register allocator should
6955 // place these in any free register.
6957 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
6958 Ops.push_back(getValue(CI.getArgOperand(i)));
6960 // Push the arguments from the call instruction up to the register mask.
6961 SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
6962 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
6965 // Push live variables for the stack map.
6966 addStackMapLiveVars(CI, NumMetaOpers + NumArgs, Ops, *this);
6968 // Push the register mask info.
6970 Ops.push_back(*(Call->op_end()-2));
6972 Ops.push_back(*(Call->op_end()-1));
6974 // Push the chain (this is originally the first operand of the call, but
6975 // becomes now the last or second to last operand).
6976 Ops.push_back(*(Call->op_begin()));
6978 // Push the glue flag (last operand).
6980 Ops.push_back(*(Call->op_end()-1));
6983 if (isAnyRegCC && hasDef) {
6984 // Create the return types based on the intrinsic definition
6985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6986 SmallVector<EVT, 3> ValueVTs;
6987 ComputeValueVTs(TLI, CI.getType(), ValueVTs);
6988 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
6990 // There is always a chain and a glue type at the end
6991 ValueVTs.push_back(MVT::Other);
6992 ValueVTs.push_back(MVT::Glue);
6993 NodeTys = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
6995 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6997 // Replace the target specific call node with a PATCHPOINT node.
6998 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
6999 getCurSDLoc(), NodeTys, Ops);
7001 // Update the NodeMap.
7004 setValue(&CI, SDValue(MN, 0));
7006 setValue(&CI, Result.first);
7009 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7010 // call sequence. Furthermore the location of the chain and glue can change
7011 // when the AnyReg calling convention is used and the intrinsic returns a
7013 if (isAnyRegCC && hasDef) {
7014 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7015 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7016 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7018 DAG.ReplaceAllUsesWith(Call, MN);
7019 DAG.DeleteNode(Call);
7022 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7023 /// implementation, which just calls LowerCall.
7024 /// FIXME: When all targets are
7025 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7026 std::pair<SDValue, SDValue>
7027 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7028 // Handle the incoming return values from the call.
7030 SmallVector<EVT, 4> RetTys;
7031 ComputeValueVTs(*this, CLI.RetTy, RetTys);
7032 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7034 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7035 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7036 for (unsigned i = 0; i != NumRegs; ++i) {
7037 ISD::InputArg MyFlags;
7038 MyFlags.VT = RegisterVT;
7040 MyFlags.Used = CLI.IsReturnValueUsed;
7042 MyFlags.Flags.setSExt();
7044 MyFlags.Flags.setZExt();
7046 MyFlags.Flags.setInReg();
7047 CLI.Ins.push_back(MyFlags);
7051 // Handle all of the outgoing arguments.
7053 CLI.OutVals.clear();
7054 ArgListTy &Args = CLI.Args;
7055 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7056 SmallVector<EVT, 4> ValueVTs;
7057 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7058 for (unsigned Value = 0, NumValues = ValueVTs.size();
7059 Value != NumValues; ++Value) {
7060 EVT VT = ValueVTs[Value];
7061 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7062 SDValue Op = SDValue(Args[i].Node.getNode(),
7063 Args[i].Node.getResNo() + Value);
7064 ISD::ArgFlagsTy Flags;
7065 unsigned OriginalAlignment =
7066 getDataLayout()->getABITypeAlignment(ArgTy);
7072 if (Args[i].isInReg)
7076 if (Args[i].isByVal) {
7078 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7079 Type *ElementTy = Ty->getElementType();
7080 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
7081 // For ByVal, alignment should come from FE. BE will guess if this
7082 // info is not there but there are cases it cannot get right.
7083 unsigned FrameAlign;
7084 if (Args[i].Alignment)
7085 FrameAlign = Args[i].Alignment;
7087 FrameAlign = getByValTypeAlignment(ElementTy);
7088 Flags.setByValAlign(FrameAlign);
7092 Flags.setOrigAlign(OriginalAlignment);
7094 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7095 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7096 SmallVector<SDValue, 4> Parts(NumParts);
7097 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7100 ExtendKind = ISD::SIGN_EXTEND;
7101 else if (Args[i].isZExt)
7102 ExtendKind = ISD::ZERO_EXTEND;
7104 // Conservatively only handle 'returned' on non-vectors for now
7105 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7106 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7107 "unexpected use of 'returned'");
7108 // Before passing 'returned' to the target lowering code, ensure that
7109 // either the register MVT and the actual EVT are the same size or that
7110 // the return value and argument are extended in the same way; in these
7111 // cases it's safe to pass the argument register value unchanged as the
7112 // return register value (although it's at the target's option whether
7114 // TODO: allow code generation to take advantage of partially preserved
7115 // registers rather than clobbering the entire register when the
7116 // parameter extension method is not compatible with the return
7118 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7119 (ExtendKind != ISD::ANY_EXTEND &&
7120 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7121 Flags.setReturned();
7124 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
7125 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
7127 for (unsigned j = 0; j != NumParts; ++j) {
7128 // if it isn't first piece, alignment must be 1
7129 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7130 i < CLI.NumFixedArgs,
7131 i, j*Parts[j].getValueType().getStoreSize());
7132 if (NumParts > 1 && j == 0)
7133 MyFlags.Flags.setSplit();
7135 MyFlags.Flags.setOrigAlign(1);
7137 CLI.Outs.push_back(MyFlags);
7138 CLI.OutVals.push_back(Parts[j]);
7143 SmallVector<SDValue, 4> InVals;
7144 CLI.Chain = LowerCall(CLI, InVals);
7146 // Verify that the target's LowerCall behaved as expected.
7147 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7148 "LowerCall didn't return a valid chain!");
7149 assert((!CLI.IsTailCall || InVals.empty()) &&
7150 "LowerCall emitted a return value for a tail call!");
7151 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7152 "LowerCall didn't emit the correct number of values!");
7154 // For a tail call, the return value is merely live-out and there aren't
7155 // any nodes in the DAG representing it. Return a special value to
7156 // indicate that a tail call has been emitted and no more Instructions
7157 // should be processed in the current block.
7158 if (CLI.IsTailCall) {
7159 CLI.DAG.setRoot(CLI.Chain);
7160 return std::make_pair(SDValue(), SDValue());
7163 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7164 assert(InVals[i].getNode() &&
7165 "LowerCall emitted a null value!");
7166 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7167 "LowerCall emitted a value with the wrong type!");
7170 // Collect the legal value parts into potentially illegal values
7171 // that correspond to the original function's return values.
7172 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7174 AssertOp = ISD::AssertSext;
7175 else if (CLI.RetZExt)
7176 AssertOp = ISD::AssertZext;
7177 SmallVector<SDValue, 4> ReturnValues;
7178 unsigned CurReg = 0;
7179 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7181 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7182 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7184 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7185 NumRegs, RegisterVT, VT, NULL,
7190 // For a function returning void, there is no return value. We can't create
7191 // such a node, so we just return a null return value in that case. In
7192 // that case, nothing will actually look at the value.
7193 if (ReturnValues.empty())
7194 return std::make_pair(SDValue(), CLI.Chain);
7196 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7197 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
7198 &ReturnValues[0], ReturnValues.size());
7199 return std::make_pair(Res, CLI.Chain);
7202 void TargetLowering::LowerOperationWrapper(SDNode *N,
7203 SmallVectorImpl<SDValue> &Results,
7204 SelectionDAG &DAG) const {
7205 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7207 Results.push_back(Res);
7210 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7211 llvm_unreachable("LowerOperation not implemented for this target!");
7215 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7216 SDValue Op = getNonRegisterValue(V);
7217 assert((Op.getOpcode() != ISD::CopyFromReg ||
7218 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7219 "Copy from a reg to the same reg!");
7220 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7222 const TargetLowering *TLI = TM.getTargetLowering();
7223 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
7224 SDValue Chain = DAG.getEntryNode();
7225 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V);
7226 PendingExports.push_back(Chain);
7229 #include "llvm/CodeGen/SelectionDAGISel.h"
7231 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7232 /// entry block, return true. This includes arguments used by switches, since
7233 /// the switch may expand into multiple basic blocks.
7234 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7235 // With FastISel active, we may be splitting blocks, so force creation
7236 // of virtual registers for all non-dead arguments.
7238 return A->use_empty();
7240 const BasicBlock *Entry = A->getParent()->begin();
7241 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
7243 const User *U = *UI;
7244 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7245 return false; // Use not in entry block.
7250 void SelectionDAGISel::LowerArguments(const Function &F) {
7251 SelectionDAG &DAG = SDB->DAG;
7252 SDLoc dl = SDB->getCurSDLoc();
7253 const TargetLowering *TLI = getTargetLowering();
7254 const DataLayout *TD = TLI->getDataLayout();
7255 SmallVector<ISD::InputArg, 16> Ins;
7257 if (!FuncInfo->CanLowerReturn) {
7258 // Put in an sret pointer parameter before all the other parameters.
7259 SmallVector<EVT, 1> ValueVTs;
7260 ComputeValueVTs(*getTargetLowering(),
7261 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7263 // NOTE: Assuming that a pointer will never break down to more than one VT
7265 ISD::ArgFlagsTy Flags;
7267 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7268 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
7269 Ins.push_back(RetArg);
7272 // Set up the incoming argument description vector.
7274 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7275 I != E; ++I, ++Idx) {
7276 SmallVector<EVT, 4> ValueVTs;
7277 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7278 bool isArgValueUsed = !I->use_empty();
7279 unsigned PartBase = 0;
7280 for (unsigned Value = 0, NumValues = ValueVTs.size();
7281 Value != NumValues; ++Value) {
7282 EVT VT = ValueVTs[Value];
7283 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7284 ISD::ArgFlagsTy Flags;
7285 unsigned OriginalAlignment =
7286 TD->getABITypeAlignment(ArgTy);
7288 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7290 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7292 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7294 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7296 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) {
7298 PointerType *Ty = cast<PointerType>(I->getType());
7299 Type *ElementTy = Ty->getElementType();
7300 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
7301 // For ByVal, alignment should be passed from FE. BE will guess if
7302 // this info is not there but there are cases it cannot get right.
7303 unsigned FrameAlign;
7304 if (F.getParamAlignment(Idx))
7305 FrameAlign = F.getParamAlignment(Idx);
7307 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7308 Flags.setByValAlign(FrameAlign);
7310 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7312 Flags.setOrigAlign(OriginalAlignment);
7314 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7315 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7316 for (unsigned i = 0; i != NumRegs; ++i) {
7317 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7318 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7319 if (NumRegs > 1 && i == 0)
7320 MyFlags.Flags.setSplit();
7321 // if it isn't first piece, alignment must be 1
7323 MyFlags.Flags.setOrigAlign(1);
7324 Ins.push_back(MyFlags);
7326 PartBase += VT.getStoreSize();
7330 // Call the target to set up the argument values.
7331 SmallVector<SDValue, 8> InVals;
7332 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
7336 // Verify that the target's LowerFormalArguments behaved as expected.
7337 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7338 "LowerFormalArguments didn't return a valid chain!");
7339 assert(InVals.size() == Ins.size() &&
7340 "LowerFormalArguments didn't emit the correct number of values!");
7342 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7343 assert(InVals[i].getNode() &&
7344 "LowerFormalArguments emitted a null value!");
7345 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7346 "LowerFormalArguments emitted a value with the wrong type!");
7350 // Update the DAG with the new chain value resulting from argument lowering.
7351 DAG.setRoot(NewRoot);
7353 // Set up the argument values.
7356 if (!FuncInfo->CanLowerReturn) {
7357 // Create a virtual register for the sret pointer, and put in a copy
7358 // from the sret argument into it.
7359 SmallVector<EVT, 1> ValueVTs;
7360 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7361 MVT VT = ValueVTs[0].getSimpleVT();
7362 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7363 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7364 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7365 RegVT, VT, NULL, AssertOp);
7367 MachineFunction& MF = SDB->DAG.getMachineFunction();
7368 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7369 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7370 FuncInfo->DemoteRegister = SRetReg;
7371 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
7373 DAG.setRoot(NewRoot);
7375 // i indexes lowered arguments. Bump it past the hidden sret argument.
7376 // Idx indexes LLVM arguments. Don't touch it.
7380 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7382 SmallVector<SDValue, 4> ArgValues;
7383 SmallVector<EVT, 4> ValueVTs;
7384 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7385 unsigned NumValues = ValueVTs.size();
7387 // If this argument is unused then remember its value. It is used to generate
7388 // debugging information.
7389 if (I->use_empty() && NumValues) {
7390 SDB->setUnusedArgValue(I, InVals[i]);
7392 // Also remember any frame index for use in FastISel.
7393 if (FrameIndexSDNode *FI =
7394 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7395 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7398 for (unsigned Val = 0; Val != NumValues; ++Val) {
7399 EVT VT = ValueVTs[Val];
7400 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7401 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7403 if (!I->use_empty()) {
7404 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7405 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7406 AssertOp = ISD::AssertSext;
7407 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7408 AssertOp = ISD::AssertZext;
7410 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7411 NumParts, PartVT, VT,
7418 // We don't need to do anything else for unused arguments.
7419 if (ArgValues.empty())
7422 // Note down frame index.
7423 if (FrameIndexSDNode *FI =
7424 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7425 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7427 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
7428 SDB->getCurSDLoc());
7430 SDB->setValue(I, Res);
7431 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7432 if (LoadSDNode *LNode =
7433 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7434 if (FrameIndexSDNode *FI =
7435 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7436 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7439 // If this argument is live outside of the entry block, insert a copy from
7440 // wherever we got it to the vreg that other BB's will reference it as.
7441 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7442 // If we can, though, try to skip creating an unnecessary vreg.
7443 // FIXME: This isn't very clean... it would be nice to make this more
7444 // general. It's also subtly incompatible with the hacks FastISel
7446 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7447 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7448 FuncInfo->ValueMap[I] = Reg;
7452 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7453 FuncInfo->InitializeRegForValue(I);
7454 SDB->CopyToExportRegsIfNeeded(I);
7458 assert(i == InVals.size() && "Argument register count mismatch!");
7460 // Finally, if the target has anything special to do, allow it to do so.
7461 // FIXME: this should insert code into the DAG!
7462 EmitFunctionEntryCode();
7465 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7466 /// ensure constants are generated when needed. Remember the virtual registers
7467 /// that need to be added to the Machine PHI nodes as input. We cannot just
7468 /// directly add them, because expansion might result in multiple MBB's for one
7469 /// BB. As such, the start of the BB might correspond to a different MBB than
7473 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7474 const TerminatorInst *TI = LLVMBB->getTerminator();
7476 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7478 // Check successor nodes' PHI nodes that expect a constant to be available
7480 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7481 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7482 if (!isa<PHINode>(SuccBB->begin())) continue;
7483 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7485 // If this terminator has multiple identical successors (common for
7486 // switches), only handle each succ once.
7487 if (!SuccsHandled.insert(SuccMBB)) continue;
7489 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7491 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7492 // nodes and Machine PHI nodes, but the incoming operands have not been
7494 for (BasicBlock::const_iterator I = SuccBB->begin();
7495 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7496 // Ignore dead phi's.
7497 if (PN->use_empty()) continue;
7500 if (PN->getType()->isEmptyTy())
7504 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7506 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7507 unsigned &RegOut = ConstantsOut[C];
7509 RegOut = FuncInfo.CreateRegs(C->getType());
7510 CopyValueToVirtualRegister(C, RegOut);
7514 DenseMap<const Value *, unsigned>::iterator I =
7515 FuncInfo.ValueMap.find(PHIOp);
7516 if (I != FuncInfo.ValueMap.end())
7519 assert(isa<AllocaInst>(PHIOp) &&
7520 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7521 "Didn't codegen value into a register!??");
7522 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7523 CopyValueToVirtualRegister(PHIOp, Reg);
7527 // Remember that this register needs to added to the machine PHI node as
7528 // the input for this MBB.
7529 SmallVector<EVT, 4> ValueVTs;
7530 const TargetLowering *TLI = TM.getTargetLowering();
7531 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
7532 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7533 EVT VT = ValueVTs[vti];
7534 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
7535 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7536 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7537 Reg += NumRegisters;
7542 ConstantsOut.clear();
7545 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7548 SelectionDAGBuilder::StackProtectorDescriptor::
7549 AddSuccessorMBB(const BasicBlock *BB,
7550 MachineBasicBlock *ParentMBB,
7551 MachineBasicBlock *SuccMBB) {
7552 // If SuccBB has not been created yet, create it.
7554 MachineFunction *MF = ParentMBB->getParent();
7555 MachineFunction::iterator BBI = ParentMBB;
7556 SuccMBB = MF->CreateMachineBasicBlock(BB);
7557 MF->insert(++BBI, SuccMBB);
7559 // Add it as a successor of ParentMBB.
7560 ParentMBB->addSuccessor(SuccMBB);