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 return DAG.getConstant(0, TLI->getPointerTy());
1070 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1071 return DAG.getConstantFP(*CFP, VT);
1073 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1074 return DAG.getUNDEF(VT);
1076 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1077 visit(CE->getOpcode(), *CE);
1078 SDValue N1 = NodeMap[V];
1079 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1083 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1084 SmallVector<SDValue, 4> Constants;
1085 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1087 SDNode *Val = getValue(*OI).getNode();
1088 // If the operand is an empty aggregate, there are no values.
1090 // Add each leaf value from the operand to the Constants list
1091 // to form a flattened list of all the values.
1092 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1093 Constants.push_back(SDValue(Val, i));
1096 return DAG.getMergeValues(&Constants[0], Constants.size(),
1100 if (const ConstantDataSequential *CDS =
1101 dyn_cast<ConstantDataSequential>(C)) {
1102 SmallVector<SDValue, 4> Ops;
1103 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1104 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1105 // Add each leaf value from the operand to the Constants list
1106 // to form a flattened list of all the values.
1107 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1108 Ops.push_back(SDValue(Val, i));
1111 if (isa<ArrayType>(CDS->getType()))
1112 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
1113 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1114 VT, &Ops[0], Ops.size());
1117 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1118 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1119 "Unknown struct or array constant!");
1121 SmallVector<EVT, 4> ValueVTs;
1122 ComputeValueVTs(*TLI, C->getType(), ValueVTs);
1123 unsigned NumElts = ValueVTs.size();
1125 return SDValue(); // empty struct
1126 SmallVector<SDValue, 4> Constants(NumElts);
1127 for (unsigned i = 0; i != NumElts; ++i) {
1128 EVT EltVT = ValueVTs[i];
1129 if (isa<UndefValue>(C))
1130 Constants[i] = DAG.getUNDEF(EltVT);
1131 else if (EltVT.isFloatingPoint())
1132 Constants[i] = DAG.getConstantFP(0, EltVT);
1134 Constants[i] = DAG.getConstant(0, EltVT);
1137 return DAG.getMergeValues(&Constants[0], NumElts,
1141 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1142 return DAG.getBlockAddress(BA, VT);
1144 VectorType *VecTy = cast<VectorType>(V->getType());
1145 unsigned NumElements = VecTy->getNumElements();
1147 // Now that we know the number and type of the elements, get that number of
1148 // elements into the Ops array based on what kind of constant it is.
1149 SmallVector<SDValue, 16> Ops;
1150 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1151 for (unsigned i = 0; i != NumElements; ++i)
1152 Ops.push_back(getValue(CV->getOperand(i)));
1154 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1155 EVT EltVT = TLI->getValueType(VecTy->getElementType());
1158 if (EltVT.isFloatingPoint())
1159 Op = DAG.getConstantFP(0, EltVT);
1161 Op = DAG.getConstant(0, EltVT);
1162 Ops.assign(NumElements, Op);
1165 // Create a BUILD_VECTOR node.
1166 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1167 VT, &Ops[0], Ops.size());
1170 // If this is a static alloca, generate it as the frameindex instead of
1172 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1173 DenseMap<const AllocaInst*, int>::iterator SI =
1174 FuncInfo.StaticAllocaMap.find(AI);
1175 if (SI != FuncInfo.StaticAllocaMap.end())
1176 return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
1179 // If this is an instruction which fast-isel has deferred, select it now.
1180 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1181 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1182 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
1183 SDValue Chain = DAG.getEntryNode();
1184 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
1187 llvm_unreachable("Can't get register for value!");
1190 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1191 const TargetLowering *TLI = TM.getTargetLowering();
1192 SDValue Chain = getControlRoot();
1193 SmallVector<ISD::OutputArg, 8> Outs;
1194 SmallVector<SDValue, 8> OutVals;
1196 if (!FuncInfo.CanLowerReturn) {
1197 unsigned DemoteReg = FuncInfo.DemoteRegister;
1198 const Function *F = I.getParent()->getParent();
1200 // Emit a store of the return value through the virtual register.
1201 // Leave Outs empty so that LowerReturn won't try to load return
1202 // registers the usual way.
1203 SmallVector<EVT, 1> PtrValueVTs;
1204 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
1207 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1208 SDValue RetOp = getValue(I.getOperand(0));
1210 SmallVector<EVT, 4> ValueVTs;
1211 SmallVector<uint64_t, 4> Offsets;
1212 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1213 unsigned NumValues = ValueVTs.size();
1215 SmallVector<SDValue, 4> Chains(NumValues);
1216 for (unsigned i = 0; i != NumValues; ++i) {
1217 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1218 RetPtr.getValueType(), RetPtr,
1219 DAG.getIntPtrConstant(Offsets[i]));
1221 DAG.getStore(Chain, getCurSDLoc(),
1222 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1223 // FIXME: better loc info would be nice.
1224 Add, MachinePointerInfo(), false, false, 0);
1227 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1228 MVT::Other, &Chains[0], NumValues);
1229 } else if (I.getNumOperands() != 0) {
1230 SmallVector<EVT, 4> ValueVTs;
1231 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
1232 unsigned NumValues = ValueVTs.size();
1234 SDValue RetOp = getValue(I.getOperand(0));
1235 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1236 EVT VT = ValueVTs[j];
1238 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1240 const Function *F = I.getParent()->getParent();
1241 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1243 ExtendKind = ISD::SIGN_EXTEND;
1244 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1246 ExtendKind = ISD::ZERO_EXTEND;
1248 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1249 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
1251 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
1252 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
1253 SmallVector<SDValue, 4> Parts(NumParts);
1254 getCopyToParts(DAG, getCurSDLoc(),
1255 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1256 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1258 // 'inreg' on function refers to return value
1259 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1260 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1264 // Propagate extension type if any
1265 if (ExtendKind == ISD::SIGN_EXTEND)
1267 else if (ExtendKind == ISD::ZERO_EXTEND)
1270 for (unsigned i = 0; i < NumParts; ++i) {
1271 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1272 VT, /*isfixed=*/true, 0, 0));
1273 OutVals.push_back(Parts[i]);
1279 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1280 CallingConv::ID CallConv =
1281 DAG.getMachineFunction().getFunction()->getCallingConv();
1282 Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
1283 Outs, OutVals, getCurSDLoc(),
1286 // Verify that the target's LowerReturn behaved as expected.
1287 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1288 "LowerReturn didn't return a valid chain!");
1290 // Update the DAG with the new chain value resulting from return lowering.
1294 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1295 /// created for it, emit nodes to copy the value into the virtual
1297 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1299 if (V->getType()->isEmptyTy())
1302 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1303 if (VMI != FuncInfo.ValueMap.end()) {
1304 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1305 CopyValueToVirtualRegister(V, VMI->second);
1309 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1310 /// the current basic block, add it to ValueMap now so that we'll get a
1312 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1313 // No need to export constants.
1314 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1316 // Already exported?
1317 if (FuncInfo.isExportedInst(V)) return;
1319 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1320 CopyValueToVirtualRegister(V, Reg);
1323 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1324 const BasicBlock *FromBB) {
1325 // The operands of the setcc have to be in this block. We don't know
1326 // how to export them from some other block.
1327 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1328 // Can export from current BB.
1329 if (VI->getParent() == FromBB)
1332 // Is already exported, noop.
1333 return FuncInfo.isExportedInst(V);
1336 // If this is an argument, we can export it if the BB is the entry block or
1337 // if it is already exported.
1338 if (isa<Argument>(V)) {
1339 if (FromBB == &FromBB->getParent()->getEntryBlock())
1342 // Otherwise, can only export this if it is already exported.
1343 return FuncInfo.isExportedInst(V);
1346 // Otherwise, constants can always be exported.
1350 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1351 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1352 const MachineBasicBlock *Dst) const {
1353 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1356 const BasicBlock *SrcBB = Src->getBasicBlock();
1357 const BasicBlock *DstBB = Dst->getBasicBlock();
1358 return BPI->getEdgeWeight(SrcBB, DstBB);
1361 void SelectionDAGBuilder::
1362 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1363 uint32_t Weight /* = 0 */) {
1365 Weight = getEdgeWeight(Src, Dst);
1366 Src->addSuccessor(Dst, Weight);
1370 static bool InBlock(const Value *V, const BasicBlock *BB) {
1371 if (const Instruction *I = dyn_cast<Instruction>(V))
1372 return I->getParent() == BB;
1376 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1377 /// This function emits a branch and is used at the leaves of an OR or an
1378 /// AND operator tree.
1381 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1382 MachineBasicBlock *TBB,
1383 MachineBasicBlock *FBB,
1384 MachineBasicBlock *CurBB,
1385 MachineBasicBlock *SwitchBB) {
1386 const BasicBlock *BB = CurBB->getBasicBlock();
1388 // If the leaf of the tree is a comparison, merge the condition into
1390 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1391 // The operands of the cmp have to be in this block. We don't know
1392 // how to export them from some other block. If this is the first block
1393 // of the sequence, no exporting is needed.
1394 if (CurBB == SwitchBB ||
1395 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1396 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1397 ISD::CondCode Condition;
1398 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1399 Condition = getICmpCondCode(IC->getPredicate());
1400 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1401 Condition = getFCmpCondCode(FC->getPredicate());
1402 if (TM.Options.NoNaNsFPMath)
1403 Condition = getFCmpCodeWithoutNaN(Condition);
1405 Condition = ISD::SETEQ; // silence warning.
1406 llvm_unreachable("Unknown compare instruction");
1409 CaseBlock CB(Condition, BOp->getOperand(0),
1410 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1411 SwitchCases.push_back(CB);
1416 // Create a CaseBlock record representing this branch.
1417 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1418 NULL, TBB, FBB, CurBB);
1419 SwitchCases.push_back(CB);
1422 /// FindMergedConditions - If Cond is an expression like
1423 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1424 MachineBasicBlock *TBB,
1425 MachineBasicBlock *FBB,
1426 MachineBasicBlock *CurBB,
1427 MachineBasicBlock *SwitchBB,
1429 // If this node is not part of the or/and tree, emit it as a branch.
1430 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1431 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1432 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1433 BOp->getParent() != CurBB->getBasicBlock() ||
1434 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1435 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1436 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1440 // Create TmpBB after CurBB.
1441 MachineFunction::iterator BBI = CurBB;
1442 MachineFunction &MF = DAG.getMachineFunction();
1443 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1444 CurBB->getParent()->insert(++BBI, TmpBB);
1446 if (Opc == Instruction::Or) {
1447 // Codegen X | Y as:
1455 // Emit the LHS condition.
1456 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1458 // Emit the RHS condition into TmpBB.
1459 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1461 assert(Opc == Instruction::And && "Unknown merge op!");
1462 // Codegen X & Y as:
1469 // This requires creation of TmpBB after CurBB.
1471 // Emit the LHS condition.
1472 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1474 // Emit the RHS condition into TmpBB.
1475 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1479 /// If the set of cases should be emitted as a series of branches, return true.
1480 /// If we should emit this as a bunch of and/or'd together conditions, return
1483 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1484 if (Cases.size() != 2) return true;
1486 // If this is two comparisons of the same values or'd or and'd together, they
1487 // will get folded into a single comparison, so don't emit two blocks.
1488 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1489 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1490 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1491 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1495 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1496 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1497 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1498 Cases[0].CC == Cases[1].CC &&
1499 isa<Constant>(Cases[0].CmpRHS) &&
1500 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1501 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1503 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1510 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1511 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1513 // Update machine-CFG edges.
1514 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1516 // Figure out which block is immediately after the current one.
1517 MachineBasicBlock *NextBlock = 0;
1518 MachineFunction::iterator BBI = BrMBB;
1519 if (++BBI != FuncInfo.MF->end())
1522 if (I.isUnconditional()) {
1523 // Update machine-CFG edges.
1524 BrMBB->addSuccessor(Succ0MBB);
1526 // If this is not a fall-through branch, emit the branch.
1527 if (Succ0MBB != NextBlock)
1528 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1529 MVT::Other, getControlRoot(),
1530 DAG.getBasicBlock(Succ0MBB)));
1535 // If this condition is one of the special cases we handle, do special stuff
1537 const Value *CondVal = I.getCondition();
1538 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1540 // If this is a series of conditions that are or'd or and'd together, emit
1541 // this as a sequence of branches instead of setcc's with and/or operations.
1542 // As long as jumps are not expensive, this should improve performance.
1543 // For example, instead of something like:
1556 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1557 if (!TM.getTargetLowering()->isJumpExpensive() &&
1559 (BOp->getOpcode() == Instruction::And ||
1560 BOp->getOpcode() == Instruction::Or)) {
1561 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1563 // If the compares in later blocks need to use values not currently
1564 // exported from this block, export them now. This block should always
1565 // be the first entry.
1566 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1568 // Allow some cases to be rejected.
1569 if (ShouldEmitAsBranches(SwitchCases)) {
1570 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1571 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1572 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1575 // Emit the branch for this block.
1576 visitSwitchCase(SwitchCases[0], BrMBB);
1577 SwitchCases.erase(SwitchCases.begin());
1581 // Okay, we decided not to do this, remove any inserted MBB's and clear
1583 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1584 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1586 SwitchCases.clear();
1590 // Create a CaseBlock record representing this branch.
1591 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1592 NULL, Succ0MBB, Succ1MBB, BrMBB);
1594 // Use visitSwitchCase to actually insert the fast branch sequence for this
1596 visitSwitchCase(CB, BrMBB);
1599 /// visitSwitchCase - Emits the necessary code to represent a single node in
1600 /// the binary search tree resulting from lowering a switch instruction.
1601 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1602 MachineBasicBlock *SwitchBB) {
1604 SDValue CondLHS = getValue(CB.CmpLHS);
1605 SDLoc dl = getCurSDLoc();
1607 // Build the setcc now.
1608 if (CB.CmpMHS == NULL) {
1609 // Fold "(X == true)" to X and "(X == false)" to !X to
1610 // handle common cases produced by branch lowering.
1611 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1612 CB.CC == ISD::SETEQ)
1614 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1615 CB.CC == ISD::SETEQ) {
1616 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1617 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1619 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1621 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1623 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1624 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1626 SDValue CmpOp = getValue(CB.CmpMHS);
1627 EVT VT = CmpOp.getValueType();
1629 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1630 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1633 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1634 VT, CmpOp, DAG.getConstant(Low, VT));
1635 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1636 DAG.getConstant(High-Low, VT), ISD::SETULE);
1640 // Update successor info
1641 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1642 // TrueBB and FalseBB are always different unless the incoming IR is
1643 // degenerate. This only happens when running llc on weird IR.
1644 if (CB.TrueBB != CB.FalseBB)
1645 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1647 // Set NextBlock to be the MBB immediately after the current one, if any.
1648 // This is used to avoid emitting unnecessary branches to the next block.
1649 MachineBasicBlock *NextBlock = 0;
1650 MachineFunction::iterator BBI = SwitchBB;
1651 if (++BBI != FuncInfo.MF->end())
1654 // If the lhs block is the next block, invert the condition so that we can
1655 // fall through to the lhs instead of the rhs block.
1656 if (CB.TrueBB == NextBlock) {
1657 std::swap(CB.TrueBB, CB.FalseBB);
1658 SDValue True = DAG.getConstant(1, Cond.getValueType());
1659 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1662 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1663 MVT::Other, getControlRoot(), Cond,
1664 DAG.getBasicBlock(CB.TrueBB));
1666 // Insert the false branch. Do this even if it's a fall through branch,
1667 // this makes it easier to do DAG optimizations which require inverting
1668 // the branch condition.
1669 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1670 DAG.getBasicBlock(CB.FalseBB));
1672 DAG.setRoot(BrCond);
1675 /// visitJumpTable - Emit JumpTable node in the current MBB
1676 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1677 // Emit the code for the jump table
1678 assert(JT.Reg != -1U && "Should lower JT Header first!");
1679 EVT PTy = TM.getTargetLowering()->getPointerTy();
1680 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1682 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1683 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1684 MVT::Other, Index.getValue(1),
1686 DAG.setRoot(BrJumpTable);
1689 /// visitJumpTableHeader - This function emits necessary code to produce index
1690 /// in the JumpTable from switch case.
1691 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1692 JumpTableHeader &JTH,
1693 MachineBasicBlock *SwitchBB) {
1694 // Subtract the lowest switch case value from the value being switched on and
1695 // conditional branch to default mbb if the result is greater than the
1696 // difference between smallest and largest cases.
1697 SDValue SwitchOp = getValue(JTH.SValue);
1698 EVT VT = SwitchOp.getValueType();
1699 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1700 DAG.getConstant(JTH.First, VT));
1702 // The SDNode we just created, which holds the value being switched on minus
1703 // the smallest case value, needs to be copied to a virtual register so it
1704 // can be used as an index into the jump table in a subsequent basic block.
1705 // This value may be smaller or larger than the target's pointer type, and
1706 // therefore require extension or truncating.
1707 const TargetLowering *TLI = TM.getTargetLowering();
1708 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
1710 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
1711 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1712 JumpTableReg, SwitchOp);
1713 JT.Reg = JumpTableReg;
1715 // Emit the range check for the jump table, and branch to the default block
1716 // for the switch statement if the value being switched on exceeds the largest
1717 // case in the switch.
1718 SDValue CMP = DAG.getSetCC(getCurSDLoc(),
1719 TLI->getSetCCResultType(*DAG.getContext(),
1720 Sub.getValueType()),
1722 DAG.getConstant(JTH.Last - JTH.First,VT),
1725 // Set NextBlock to be the MBB immediately after the current one, if any.
1726 // This is used to avoid emitting unnecessary branches to the next block.
1727 MachineBasicBlock *NextBlock = 0;
1728 MachineFunction::iterator BBI = SwitchBB;
1730 if (++BBI != FuncInfo.MF->end())
1733 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1734 MVT::Other, CopyTo, CMP,
1735 DAG.getBasicBlock(JT.Default));
1737 if (JT.MBB != NextBlock)
1738 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1739 DAG.getBasicBlock(JT.MBB));
1741 DAG.setRoot(BrCond);
1744 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1745 /// tail spliced into a stack protector check success bb.
1747 /// For a high level explanation of how this fits into the stack protector
1748 /// generation see the comment on the declaration of class
1749 /// StackProtectorDescriptor.
1750 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1751 MachineBasicBlock *ParentBB) {
1753 // First create the loads to the guard/stack slot for the comparison.
1754 const TargetLowering *TLI = TM.getTargetLowering();
1755 EVT PtrTy = TLI->getPointerTy();
1757 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1758 int FI = MFI->getStackProtectorIndex();
1760 const Value *IRGuard = SPD.getGuard();
1761 SDValue GuardPtr = getValue(IRGuard);
1762 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1765 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1766 SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1767 GuardPtr, MachinePointerInfo(IRGuard, 0),
1768 true, false, false, Align);
1770 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1772 MachinePointerInfo::getFixedStack(FI),
1773 true, false, false, Align);
1775 // Perform the comparison via a subtract/getsetcc.
1776 EVT VT = Guard.getValueType();
1777 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1779 SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
1780 TLI->getSetCCResultType(*DAG.getContext(),
1781 Sub.getValueType()),
1782 Sub, DAG.getConstant(0, VT),
1785 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1786 // branch to failure MBB.
1787 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1788 MVT::Other, StackSlot.getOperand(0),
1789 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1790 // Otherwise branch to success MBB.
1791 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1793 DAG.getBasicBlock(SPD.getSuccessMBB()));
1798 /// Codegen the failure basic block for a stack protector check.
1800 /// A failure stack protector machine basic block consists simply of a call to
1801 /// __stack_chk_fail().
1803 /// For a high level explanation of how this fits into the stack protector
1804 /// generation see the comment on the declaration of class
1805 /// StackProtectorDescriptor.
1807 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1808 const TargetLowering *TLI = TM.getTargetLowering();
1809 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
1810 MVT::isVoid, 0, 0, false, getCurSDLoc(),
1811 false, false).second;
1815 /// visitBitTestHeader - This function emits necessary code to produce value
1816 /// suitable for "bit tests"
1817 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1818 MachineBasicBlock *SwitchBB) {
1819 // Subtract the minimum value
1820 SDValue SwitchOp = getValue(B.SValue);
1821 EVT VT = SwitchOp.getValueType();
1822 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1823 DAG.getConstant(B.First, VT));
1826 const TargetLowering *TLI = TM.getTargetLowering();
1827 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
1828 TLI->getSetCCResultType(*DAG.getContext(),
1829 Sub.getValueType()),
1830 Sub, DAG.getConstant(B.Range, VT),
1833 // Determine the type of the test operands.
1834 bool UsePtrType = false;
1835 if (!TLI->isTypeLegal(VT))
1838 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1839 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1840 // Switch table case range are encoded into series of masks.
1841 // Just use pointer type, it's guaranteed to fit.
1847 VT = TLI->getPointerTy();
1848 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1851 B.RegVT = VT.getSimpleVT();
1852 B.Reg = FuncInfo.CreateReg(B.RegVT);
1853 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1856 // Set NextBlock to be the MBB immediately after the current one, if any.
1857 // This is used to avoid emitting unnecessary branches to the next block.
1858 MachineBasicBlock *NextBlock = 0;
1859 MachineFunction::iterator BBI = SwitchBB;
1860 if (++BBI != FuncInfo.MF->end())
1863 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1865 addSuccessorWithWeight(SwitchBB, B.Default);
1866 addSuccessorWithWeight(SwitchBB, MBB);
1868 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1869 MVT::Other, CopyTo, RangeCmp,
1870 DAG.getBasicBlock(B.Default));
1872 if (MBB != NextBlock)
1873 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1874 DAG.getBasicBlock(MBB));
1876 DAG.setRoot(BrRange);
1879 /// visitBitTestCase - this function produces one "bit test"
1880 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1881 MachineBasicBlock* NextMBB,
1882 uint32_t BranchWeightToNext,
1885 MachineBasicBlock *SwitchBB) {
1887 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1890 unsigned PopCount = CountPopulation_64(B.Mask);
1891 const TargetLowering *TLI = TM.getTargetLowering();
1892 if (PopCount == 1) {
1893 // Testing for a single bit; just compare the shift count with what it
1894 // would need to be to shift a 1 bit in that position.
1895 Cmp = DAG.getSetCC(getCurSDLoc(),
1896 TLI->getSetCCResultType(*DAG.getContext(), VT),
1898 DAG.getConstant(countTrailingZeros(B.Mask), VT),
1900 } else if (PopCount == BB.Range) {
1901 // There is only one zero bit in the range, test for it directly.
1902 Cmp = DAG.getSetCC(getCurSDLoc(),
1903 TLI->getSetCCResultType(*DAG.getContext(), VT),
1905 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1908 // Make desired shift
1909 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1910 DAG.getConstant(1, VT), ShiftOp);
1912 // Emit bit tests and jumps
1913 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1914 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1915 Cmp = DAG.getSetCC(getCurSDLoc(),
1916 TLI->getSetCCResultType(*DAG.getContext(), VT),
1917 AndOp, DAG.getConstant(0, VT),
1921 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1922 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1923 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1924 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1926 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1927 MVT::Other, getControlRoot(),
1928 Cmp, DAG.getBasicBlock(B.TargetBB));
1930 // Set NextBlock to be the MBB immediately after the current one, if any.
1931 // This is used to avoid emitting unnecessary branches to the next block.
1932 MachineBasicBlock *NextBlock = 0;
1933 MachineFunction::iterator BBI = SwitchBB;
1934 if (++BBI != FuncInfo.MF->end())
1937 if (NextMBB != NextBlock)
1938 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1939 DAG.getBasicBlock(NextMBB));
1944 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1945 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1947 // Retrieve successors.
1948 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1949 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1951 const Value *Callee(I.getCalledValue());
1952 const Function *Fn = dyn_cast<Function>(Callee);
1953 if (isa<InlineAsm>(Callee))
1955 else if (Fn && Fn->isIntrinsic()) {
1956 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
1957 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
1959 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1961 // If the value of the invoke is used outside of its defining block, make it
1962 // available as a virtual register.
1963 CopyToExportRegsIfNeeded(&I);
1965 // Update successor info
1966 addSuccessorWithWeight(InvokeMBB, Return);
1967 addSuccessorWithWeight(InvokeMBB, LandingPad);
1969 // Drop into normal successor.
1970 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1971 MVT::Other, getControlRoot(),
1972 DAG.getBasicBlock(Return)));
1975 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1976 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1979 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1980 assert(FuncInfo.MBB->isLandingPad() &&
1981 "Call to landingpad not in landing pad!");
1983 MachineBasicBlock *MBB = FuncInfo.MBB;
1984 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1985 AddLandingPadInfo(LP, MMI, MBB);
1987 // If there aren't registers to copy the values into (e.g., during SjLj
1988 // exceptions), then don't bother to create these DAG nodes.
1989 const TargetLowering *TLI = TM.getTargetLowering();
1990 if (TLI->getExceptionPointerRegister() == 0 &&
1991 TLI->getExceptionSelectorRegister() == 0)
1994 SmallVector<EVT, 2> ValueVTs;
1995 ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
1996 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
1998 // Get the two live-in registers as SDValues. The physregs have already been
1999 // copied into virtual registers.
2001 Ops[0] = DAG.getZExtOrTrunc(
2002 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2003 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
2004 getCurSDLoc(), ValueVTs[0]);
2005 Ops[1] = DAG.getZExtOrTrunc(
2006 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2007 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
2008 getCurSDLoc(), ValueVTs[1]);
2011 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2012 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
2017 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2018 /// small case ranges).
2019 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2020 CaseRecVector& WorkList,
2022 MachineBasicBlock *Default,
2023 MachineBasicBlock *SwitchBB) {
2024 // Size is the number of Cases represented by this range.
2025 size_t Size = CR.Range.second - CR.Range.first;
2029 // Get the MachineFunction which holds the current MBB. This is used when
2030 // inserting any additional MBBs necessary to represent the switch.
2031 MachineFunction *CurMF = FuncInfo.MF;
2033 // Figure out which block is immediately after the current one.
2034 MachineBasicBlock *NextBlock = 0;
2035 MachineFunction::iterator BBI = CR.CaseBB;
2037 if (++BBI != FuncInfo.MF->end())
2040 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2041 // If any two of the cases has the same destination, and if one value
2042 // is the same as the other, but has one bit unset that the other has set,
2043 // use bit manipulation to do two compares at once. For example:
2044 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2045 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2046 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2047 if (Size == 2 && CR.CaseBB == SwitchBB) {
2048 Case &Small = *CR.Range.first;
2049 Case &Big = *(CR.Range.second-1);
2051 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2052 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2053 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2055 // Check that there is only one bit different.
2056 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2057 (SmallValue | BigValue) == BigValue) {
2058 // Isolate the common bit.
2059 APInt CommonBit = BigValue & ~SmallValue;
2060 assert((SmallValue | CommonBit) == BigValue &&
2061 CommonBit.countPopulation() == 1 && "Not a common bit?");
2063 SDValue CondLHS = getValue(SV);
2064 EVT VT = CondLHS.getValueType();
2065 SDLoc DL = getCurSDLoc();
2067 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2068 DAG.getConstant(CommonBit, VT));
2069 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2070 Or, DAG.getConstant(BigValue, VT),
2073 // Update successor info.
2074 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2075 addSuccessorWithWeight(SwitchBB, Small.BB,
2076 Small.ExtraWeight + Big.ExtraWeight);
2077 addSuccessorWithWeight(SwitchBB, Default,
2078 // The default destination is the first successor in IR.
2079 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2081 // Insert the true branch.
2082 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2083 getControlRoot(), Cond,
2084 DAG.getBasicBlock(Small.BB));
2086 // Insert the false branch.
2087 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2088 DAG.getBasicBlock(Default));
2090 DAG.setRoot(BrCond);
2096 // Order cases by weight so the most likely case will be checked first.
2097 uint32_t UnhandledWeights = 0;
2099 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2100 uint32_t IWeight = I->ExtraWeight;
2101 UnhandledWeights += IWeight;
2102 for (CaseItr J = CR.Range.first; J < I; ++J) {
2103 uint32_t JWeight = J->ExtraWeight;
2104 if (IWeight > JWeight)
2109 // Rearrange the case blocks so that the last one falls through if possible.
2110 Case &BackCase = *(CR.Range.second-1);
2112 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2113 // The last case block won't fall through into 'NextBlock' if we emit the
2114 // branches in this order. See if rearranging a case value would help.
2115 // We start at the bottom as it's the case with the least weight.
2116 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2117 if (I->BB == NextBlock) {
2118 std::swap(*I, BackCase);
2123 // Create a CaseBlock record representing a conditional branch to
2124 // the Case's target mbb if the value being switched on SV is equal
2126 MachineBasicBlock *CurBlock = CR.CaseBB;
2127 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2128 MachineBasicBlock *FallThrough;
2130 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2131 CurMF->insert(BBI, FallThrough);
2133 // Put SV in a virtual register to make it available from the new blocks.
2134 ExportFromCurrentBlock(SV);
2136 // If the last case doesn't match, go to the default block.
2137 FallThrough = Default;
2140 const Value *RHS, *LHS, *MHS;
2142 if (I->High == I->Low) {
2143 // This is just small small case range :) containing exactly 1 case
2145 LHS = SV; RHS = I->High; MHS = NULL;
2148 LHS = I->Low; MHS = SV; RHS = I->High;
2151 // The false weight should be sum of all un-handled cases.
2152 UnhandledWeights -= I->ExtraWeight;
2153 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2155 /* trueweight */ I->ExtraWeight,
2156 /* falseweight */ UnhandledWeights);
2158 // If emitting the first comparison, just call visitSwitchCase to emit the
2159 // code into the current block. Otherwise, push the CaseBlock onto the
2160 // vector to be later processed by SDISel, and insert the node's MBB
2161 // before the next MBB.
2162 if (CurBlock == SwitchBB)
2163 visitSwitchCase(CB, SwitchBB);
2165 SwitchCases.push_back(CB);
2167 CurBlock = FallThrough;
2173 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2174 return TLI.supportJumpTables() &&
2175 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2176 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
2179 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2180 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2181 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2182 return (LastExt - FirstExt + 1ULL);
2185 /// handleJTSwitchCase - Emit jumptable for current switch case range
2186 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2187 CaseRecVector &WorkList,
2189 MachineBasicBlock *Default,
2190 MachineBasicBlock *SwitchBB) {
2191 Case& FrontCase = *CR.Range.first;
2192 Case& BackCase = *(CR.Range.second-1);
2194 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2195 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2197 APInt TSize(First.getBitWidth(), 0);
2198 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2201 const TargetLowering *TLI = TM.getTargetLowering();
2202 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
2205 APInt Range = ComputeRange(First, Last);
2206 // The density is TSize / Range. Require at least 40%.
2207 // It should not be possible for IntTSize to saturate for sane code, but make
2208 // sure we handle Range saturation correctly.
2209 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2210 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2211 if (IntTSize * 10 < IntRange * 4)
2214 DEBUG(dbgs() << "Lowering jump table\n"
2215 << "First entry: " << First << ". Last entry: " << Last << '\n'
2216 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2218 // Get the MachineFunction which holds the current MBB. This is used when
2219 // inserting any additional MBBs necessary to represent the switch.
2220 MachineFunction *CurMF = FuncInfo.MF;
2222 // Figure out which block is immediately after the current one.
2223 MachineFunction::iterator BBI = CR.CaseBB;
2226 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2228 // Create a new basic block to hold the code for loading the address
2229 // of the jump table, and jumping to it. Update successor information;
2230 // we will either branch to the default case for the switch, or the jump
2232 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2233 CurMF->insert(BBI, JumpTableBB);
2235 addSuccessorWithWeight(CR.CaseBB, Default);
2236 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2238 // Build a vector of destination BBs, corresponding to each target
2239 // of the jump table. If the value of the jump table slot corresponds to
2240 // a case statement, push the case's BB onto the vector, otherwise, push
2242 std::vector<MachineBasicBlock*> DestBBs;
2244 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2245 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2246 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2248 if (Low.sle(TEI) && TEI.sle(High)) {
2249 DestBBs.push_back(I->BB);
2253 DestBBs.push_back(Default);
2257 // Calculate weight for each unique destination in CR.
2258 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2260 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2261 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2262 DestWeights.find(I->BB);
2263 if (Itr != DestWeights.end())
2264 Itr->second += I->ExtraWeight;
2266 DestWeights[I->BB] = I->ExtraWeight;
2269 // Update successor info. Add one edge to each unique successor.
2270 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2271 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2272 E = DestBBs.end(); I != E; ++I) {
2273 if (!SuccsHandled[(*I)->getNumber()]) {
2274 SuccsHandled[(*I)->getNumber()] = true;
2275 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2276 DestWeights.find(*I);
2277 addSuccessorWithWeight(JumpTableBB, *I,
2278 Itr != DestWeights.end() ? Itr->second : 0);
2282 // Create a jump table index for this jump table.
2283 unsigned JTEncoding = TLI->getJumpTableEncoding();
2284 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2285 ->createJumpTableIndex(DestBBs);
2287 // Set the jump table information so that we can codegen it as a second
2288 // MachineBasicBlock
2289 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2290 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2291 if (CR.CaseBB == SwitchBB)
2292 visitJumpTableHeader(JT, JTH, SwitchBB);
2294 JTCases.push_back(JumpTableBlock(JTH, JT));
2298 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2300 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2301 CaseRecVector& WorkList,
2303 MachineBasicBlock* Default,
2304 MachineBasicBlock* SwitchBB) {
2305 // Get the MachineFunction which holds the current MBB. This is used when
2306 // inserting any additional MBBs necessary to represent the switch.
2307 MachineFunction *CurMF = FuncInfo.MF;
2309 // Figure out which block is immediately after the current one.
2310 MachineFunction::iterator BBI = CR.CaseBB;
2313 Case& FrontCase = *CR.Range.first;
2314 Case& BackCase = *(CR.Range.second-1);
2315 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2317 // Size is the number of Cases represented by this range.
2318 unsigned Size = CR.Range.second - CR.Range.first;
2320 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2321 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2323 CaseItr Pivot = CR.Range.first + Size/2;
2325 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2326 // (heuristically) allow us to emit JumpTable's later.
2327 APInt TSize(First.getBitWidth(), 0);
2328 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2332 APInt LSize = FrontCase.size();
2333 APInt RSize = TSize-LSize;
2334 DEBUG(dbgs() << "Selecting best pivot: \n"
2335 << "First: " << First << ", Last: " << Last <<'\n'
2336 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2337 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2339 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2340 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2341 APInt Range = ComputeRange(LEnd, RBegin);
2342 assert((Range - 2ULL).isNonNegative() &&
2343 "Invalid case distance");
2344 // Use volatile double here to avoid excess precision issues on some hosts,
2345 // e.g. that use 80-bit X87 registers.
2346 volatile double LDensity =
2347 (double)LSize.roundToDouble() /
2348 (LEnd - First + 1ULL).roundToDouble();
2349 volatile double RDensity =
2350 (double)RSize.roundToDouble() /
2351 (Last - RBegin + 1ULL).roundToDouble();
2352 double Metric = Range.logBase2()*(LDensity+RDensity);
2353 // Should always split in some non-trivial place
2354 DEBUG(dbgs() <<"=>Step\n"
2355 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2356 << "LDensity: " << LDensity
2357 << ", RDensity: " << RDensity << '\n'
2358 << "Metric: " << Metric << '\n');
2359 if (FMetric < Metric) {
2362 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2369 const TargetLowering *TLI = TM.getTargetLowering();
2370 if (areJTsAllowed(*TLI)) {
2371 // If our case is dense we *really* should handle it earlier!
2372 assert((FMetric > 0) && "Should handle dense range earlier!");
2374 Pivot = CR.Range.first + Size/2;
2377 CaseRange LHSR(CR.Range.first, Pivot);
2378 CaseRange RHSR(Pivot, CR.Range.second);
2379 const Constant *C = Pivot->Low;
2380 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2382 // We know that we branch to the LHS if the Value being switched on is
2383 // less than the Pivot value, C. We use this to optimize our binary
2384 // tree a bit, by recognizing that if SV is greater than or equal to the
2385 // LHS's Case Value, and that Case Value is exactly one less than the
2386 // Pivot's Value, then we can branch directly to the LHS's Target,
2387 // rather than creating a leaf node for it.
2388 if ((LHSR.second - LHSR.first) == 1 &&
2389 LHSR.first->High == CR.GE &&
2390 cast<ConstantInt>(C)->getValue() ==
2391 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2392 TrueBB = LHSR.first->BB;
2394 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2395 CurMF->insert(BBI, TrueBB);
2396 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2398 // Put SV in a virtual register to make it available from the new blocks.
2399 ExportFromCurrentBlock(SV);
2402 // Similar to the optimization above, if the Value being switched on is
2403 // known to be less than the Constant CR.LT, and the current Case Value
2404 // is CR.LT - 1, then we can branch directly to the target block for
2405 // the current Case Value, rather than emitting a RHS leaf node for it.
2406 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2407 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2408 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2409 FalseBB = RHSR.first->BB;
2411 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2412 CurMF->insert(BBI, FalseBB);
2413 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2415 // Put SV in a virtual register to make it available from the new blocks.
2416 ExportFromCurrentBlock(SV);
2419 // Create a CaseBlock record representing a conditional branch to
2420 // the LHS node if the value being switched on SV is less than C.
2421 // Otherwise, branch to LHS.
2422 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2424 if (CR.CaseBB == SwitchBB)
2425 visitSwitchCase(CB, SwitchBB);
2427 SwitchCases.push_back(CB);
2432 /// handleBitTestsSwitchCase - if current case range has few destination and
2433 /// range span less, than machine word bitwidth, encode case range into series
2434 /// of masks and emit bit tests with these masks.
2435 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2436 CaseRecVector& WorkList,
2438 MachineBasicBlock* Default,
2439 MachineBasicBlock* SwitchBB) {
2440 const TargetLowering *TLI = TM.getTargetLowering();
2441 EVT PTy = TLI->getPointerTy();
2442 unsigned IntPtrBits = PTy.getSizeInBits();
2444 Case& FrontCase = *CR.Range.first;
2445 Case& BackCase = *(CR.Range.second-1);
2447 // Get the MachineFunction which holds the current MBB. This is used when
2448 // inserting any additional MBBs necessary to represent the switch.
2449 MachineFunction *CurMF = FuncInfo.MF;
2451 // If target does not have legal shift left, do not emit bit tests at all.
2452 if (!TLI->isOperationLegal(ISD::SHL, PTy))
2456 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2458 // Single case counts one, case range - two.
2459 numCmps += (I->Low == I->High ? 1 : 2);
2462 // Count unique destinations
2463 SmallSet<MachineBasicBlock*, 4> Dests;
2464 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2465 Dests.insert(I->BB);
2466 if (Dests.size() > 3)
2467 // Don't bother the code below, if there are too much unique destinations
2470 DEBUG(dbgs() << "Total number of unique destinations: "
2471 << Dests.size() << '\n'
2472 << "Total number of comparisons: " << numCmps << '\n');
2474 // Compute span of values.
2475 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2476 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2477 APInt cmpRange = maxValue - minValue;
2479 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2480 << "Low bound: " << minValue << '\n'
2481 << "High bound: " << maxValue << '\n');
2483 if (cmpRange.uge(IntPtrBits) ||
2484 (!(Dests.size() == 1 && numCmps >= 3) &&
2485 !(Dests.size() == 2 && numCmps >= 5) &&
2486 !(Dests.size() >= 3 && numCmps >= 6)))
2489 DEBUG(dbgs() << "Emitting bit tests\n");
2490 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2492 // Optimize the case where all the case values fit in a
2493 // word without having to subtract minValue. In this case,
2494 // we can optimize away the subtraction.
2495 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2496 cmpRange = maxValue;
2498 lowBound = minValue;
2501 CaseBitsVector CasesBits;
2502 unsigned i, count = 0;
2504 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2505 MachineBasicBlock* Dest = I->BB;
2506 for (i = 0; i < count; ++i)
2507 if (Dest == CasesBits[i].BB)
2511 assert((count < 3) && "Too much destinations to test!");
2512 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2516 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2517 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2519 uint64_t lo = (lowValue - lowBound).getZExtValue();
2520 uint64_t hi = (highValue - lowBound).getZExtValue();
2521 CasesBits[i].ExtraWeight += I->ExtraWeight;
2523 for (uint64_t j = lo; j <= hi; j++) {
2524 CasesBits[i].Mask |= 1ULL << j;
2525 CasesBits[i].Bits++;
2529 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2533 // Figure out which block is immediately after the current one.
2534 MachineFunction::iterator BBI = CR.CaseBB;
2537 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2539 DEBUG(dbgs() << "Cases:\n");
2540 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2541 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2542 << ", Bits: " << CasesBits[i].Bits
2543 << ", BB: " << CasesBits[i].BB << '\n');
2545 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2546 CurMF->insert(BBI, CaseBB);
2547 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2549 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2551 // Put SV in a virtual register to make it available from the new blocks.
2552 ExportFromCurrentBlock(SV);
2555 BitTestBlock BTB(lowBound, cmpRange, SV,
2556 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2557 CR.CaseBB, Default, BTC);
2559 if (CR.CaseBB == SwitchBB)
2560 visitBitTestHeader(BTB, SwitchBB);
2562 BitTestCases.push_back(BTB);
2567 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2568 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2569 const SwitchInst& SI) {
2572 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2573 // Start with "simple" cases
2574 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2576 const BasicBlock *SuccBB = i.getCaseSuccessor();
2577 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2579 uint32_t ExtraWeight =
2580 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2582 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2583 SMBB, ExtraWeight));
2585 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2587 // Merge case into clusters
2588 if (Cases.size() >= 2)
2589 // Must recompute end() each iteration because it may be
2590 // invalidated by erase if we hold on to it
2591 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2592 J != Cases.end(); ) {
2593 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2594 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2595 MachineBasicBlock* nextBB = J->BB;
2596 MachineBasicBlock* currentBB = I->BB;
2598 // If the two neighboring cases go to the same destination, merge them
2599 // into a single case.
2600 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2602 I->ExtraWeight += J->ExtraWeight;
2609 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2610 if (I->Low != I->High)
2611 // A range counts double, since it requires two compares.
2618 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2619 MachineBasicBlock *Last) {
2621 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2622 if (JTCases[i].first.HeaderBB == First)
2623 JTCases[i].first.HeaderBB = Last;
2625 // Update BitTestCases.
2626 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2627 if (BitTestCases[i].Parent == First)
2628 BitTestCases[i].Parent = Last;
2631 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2632 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2634 // Figure out which block is immediately after the current one.
2635 MachineBasicBlock *NextBlock = 0;
2636 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2638 // If there is only the default destination, branch to it if it is not the
2639 // next basic block. Otherwise, just fall through.
2640 if (!SI.getNumCases()) {
2641 // Update machine-CFG edges.
2643 // If this is not a fall-through branch, emit the branch.
2644 SwitchMBB->addSuccessor(Default);
2645 if (Default != NextBlock)
2646 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2647 MVT::Other, getControlRoot(),
2648 DAG.getBasicBlock(Default)));
2653 // If there are any non-default case statements, create a vector of Cases
2654 // representing each one, and sort the vector so that we can efficiently
2655 // create a binary search tree from them.
2657 size_t numCmps = Clusterify(Cases, SI);
2658 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2659 << ". Total compares: " << numCmps << '\n');
2662 // Get the Value to be switched on and default basic blocks, which will be
2663 // inserted into CaseBlock records, representing basic blocks in the binary
2665 const Value *SV = SI.getCondition();
2667 // Push the initial CaseRec onto the worklist
2668 CaseRecVector WorkList;
2669 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2670 CaseRange(Cases.begin(),Cases.end())));
2672 while (!WorkList.empty()) {
2673 // Grab a record representing a case range to process off the worklist
2674 CaseRec CR = WorkList.back();
2675 WorkList.pop_back();
2677 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2680 // If the range has few cases (two or less) emit a series of specific
2682 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2685 // If the switch has more than N blocks, and is at least 40% dense, and the
2686 // target supports indirect branches, then emit a jump table rather than
2687 // lowering the switch to a binary tree of conditional branches.
2688 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2689 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2692 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2693 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2694 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2698 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2699 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2701 // Update machine-CFG edges with unique successors.
2702 SmallSet<BasicBlock*, 32> Done;
2703 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2704 BasicBlock *BB = I.getSuccessor(i);
2705 bool Inserted = Done.insert(BB);
2709 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2710 addSuccessorWithWeight(IndirectBrMBB, Succ);
2713 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2714 MVT::Other, getControlRoot(),
2715 getValue(I.getAddress())));
2718 void SelectionDAGBuilder::visitFSub(const User &I) {
2719 // -0.0 - X --> fneg
2720 Type *Ty = I.getType();
2721 if (isa<Constant>(I.getOperand(0)) &&
2722 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2723 SDValue Op2 = getValue(I.getOperand(1));
2724 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2725 Op2.getValueType(), Op2));
2729 visitBinary(I, ISD::FSUB);
2732 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2733 SDValue Op1 = getValue(I.getOperand(0));
2734 SDValue Op2 = getValue(I.getOperand(1));
2735 setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
2736 Op1.getValueType(), Op1, Op2));
2739 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2740 SDValue Op1 = getValue(I.getOperand(0));
2741 SDValue Op2 = getValue(I.getOperand(1));
2743 EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
2745 // Coerce the shift amount to the right type if we can.
2746 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2747 unsigned ShiftSize = ShiftTy.getSizeInBits();
2748 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2749 SDLoc DL = getCurSDLoc();
2751 // If the operand is smaller than the shift count type, promote it.
2752 if (ShiftSize > Op2Size)
2753 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2755 // If the operand is larger than the shift count type but the shift
2756 // count type has enough bits to represent any shift value, truncate
2757 // it now. This is a common case and it exposes the truncate to
2758 // optimization early.
2759 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2760 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2761 // Otherwise we'll need to temporarily settle for some other convenient
2762 // type. Type legalization will make adjustments once the shiftee is split.
2764 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2767 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
2768 Op1.getValueType(), Op1, Op2));
2771 void SelectionDAGBuilder::visitSDiv(const User &I) {
2772 SDValue Op1 = getValue(I.getOperand(0));
2773 SDValue Op2 = getValue(I.getOperand(1));
2775 // Turn exact SDivs into multiplications.
2776 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2778 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2779 !isa<ConstantSDNode>(Op1) &&
2780 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2781 setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
2782 getCurSDLoc(), DAG));
2784 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2788 void SelectionDAGBuilder::visitICmp(const User &I) {
2789 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2790 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2791 predicate = IC->getPredicate();
2792 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2793 predicate = ICmpInst::Predicate(IC->getPredicate());
2794 SDValue Op1 = getValue(I.getOperand(0));
2795 SDValue Op2 = getValue(I.getOperand(1));
2796 ISD::CondCode Opcode = getICmpCondCode(predicate);
2798 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2799 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2802 void SelectionDAGBuilder::visitFCmp(const User &I) {
2803 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2804 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2805 predicate = FC->getPredicate();
2806 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2807 predicate = FCmpInst::Predicate(FC->getPredicate());
2808 SDValue Op1 = getValue(I.getOperand(0));
2809 SDValue Op2 = getValue(I.getOperand(1));
2810 ISD::CondCode Condition = getFCmpCondCode(predicate);
2811 if (TM.Options.NoNaNsFPMath)
2812 Condition = getFCmpCodeWithoutNaN(Condition);
2813 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2814 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2817 void SelectionDAGBuilder::visitSelect(const User &I) {
2818 SmallVector<EVT, 4> ValueVTs;
2819 ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
2820 unsigned NumValues = ValueVTs.size();
2821 if (NumValues == 0) return;
2823 SmallVector<SDValue, 4> Values(NumValues);
2824 SDValue Cond = getValue(I.getOperand(0));
2825 SDValue TrueVal = getValue(I.getOperand(1));
2826 SDValue FalseVal = getValue(I.getOperand(2));
2827 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2828 ISD::VSELECT : ISD::SELECT;
2830 for (unsigned i = 0; i != NumValues; ++i)
2831 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2832 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2834 SDValue(TrueVal.getNode(),
2835 TrueVal.getResNo() + i),
2836 SDValue(FalseVal.getNode(),
2837 FalseVal.getResNo() + i));
2839 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2840 DAG.getVTList(&ValueVTs[0], NumValues),
2841 &Values[0], NumValues));
2844 void SelectionDAGBuilder::visitTrunc(const User &I) {
2845 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2846 SDValue N = getValue(I.getOperand(0));
2847 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2848 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2851 void SelectionDAGBuilder::visitZExt(const User &I) {
2852 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2853 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2854 SDValue N = getValue(I.getOperand(0));
2855 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2856 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2859 void SelectionDAGBuilder::visitSExt(const User &I) {
2860 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2861 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2862 SDValue N = getValue(I.getOperand(0));
2863 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2864 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2867 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2868 // FPTrunc is never a no-op cast, no need to check
2869 SDValue N = getValue(I.getOperand(0));
2870 const TargetLowering *TLI = TM.getTargetLowering();
2871 EVT DestVT = TLI->getValueType(I.getType());
2872 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
2874 DAG.getTargetConstant(0, TLI->getPointerTy())));
2877 void SelectionDAGBuilder::visitFPExt(const User &I) {
2878 // FPExt is never a no-op cast, no need to check
2879 SDValue N = getValue(I.getOperand(0));
2880 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2881 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2884 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2885 // FPToUI is never a no-op cast, no need to check
2886 SDValue N = getValue(I.getOperand(0));
2887 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2888 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2891 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2892 // FPToSI is never a no-op cast, no need to check
2893 SDValue N = getValue(I.getOperand(0));
2894 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2895 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2898 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2899 // UIToFP is never a no-op cast, no need to check
2900 SDValue N = getValue(I.getOperand(0));
2901 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2902 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2905 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2906 // SIToFP is never a no-op cast, no need to check
2907 SDValue N = getValue(I.getOperand(0));
2908 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2909 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2912 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2913 // What to do depends on the size of the integer and the size of the pointer.
2914 // We can either truncate, zero extend, or no-op, accordingly.
2915 SDValue N = getValue(I.getOperand(0));
2916 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2917 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2920 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2921 // What to do depends on the size of the integer and the size of the pointer.
2922 // We can either truncate, zero extend, or no-op, accordingly.
2923 SDValue N = getValue(I.getOperand(0));
2924 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2925 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2928 void SelectionDAGBuilder::visitBitCast(const User &I) {
2929 SDValue N = getValue(I.getOperand(0));
2930 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2932 // BitCast assures us that source and destination are the same size so this is
2933 // either a BITCAST or a no-op.
2934 if (DestVT != N.getValueType())
2935 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
2936 DestVT, N)); // convert types.
2938 setValue(&I, N); // noop cast.
2941 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2942 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2943 const Value *SV = I.getOperand(0);
2944 SDValue N = getValue(SV);
2945 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2947 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2948 unsigned DestAS = I.getType()->getPointerAddressSpace();
2950 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2951 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2956 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2957 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2958 SDValue InVec = getValue(I.getOperand(0));
2959 SDValue InVal = getValue(I.getOperand(1));
2960 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
2961 getCurSDLoc(), TLI.getVectorIdxTy());
2962 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2963 TM.getTargetLowering()->getValueType(I.getType()),
2964 InVec, InVal, InIdx));
2967 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2969 SDValue InVec = getValue(I.getOperand(0));
2970 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
2971 getCurSDLoc(), TLI.getVectorIdxTy());
2972 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2973 TM.getTargetLowering()->getValueType(I.getType()),
2977 // Utility for visitShuffleVector - Return true if every element in Mask,
2978 // beginning from position Pos and ending in Pos+Size, falls within the
2979 // specified sequential range [L, L+Pos). or is undef.
2980 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2981 unsigned Pos, unsigned Size, int Low) {
2982 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2983 if (Mask[i] >= 0 && Mask[i] != Low)
2988 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2989 SDValue Src1 = getValue(I.getOperand(0));
2990 SDValue Src2 = getValue(I.getOperand(1));
2992 SmallVector<int, 8> Mask;
2993 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2994 unsigned MaskNumElts = Mask.size();
2996 const TargetLowering *TLI = TM.getTargetLowering();
2997 EVT VT = TLI->getValueType(I.getType());
2998 EVT SrcVT = Src1.getValueType();
2999 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3001 if (SrcNumElts == MaskNumElts) {
3002 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3007 // Normalize the shuffle vector since mask and vector length don't match.
3008 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3009 // Mask is longer than the source vectors and is a multiple of the source
3010 // vectors. We can use concatenate vector to make the mask and vectors
3012 if (SrcNumElts*2 == MaskNumElts) {
3013 // First check for Src1 in low and Src2 in high
3014 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3015 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3016 // The shuffle is concatenating two vectors together.
3017 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3021 // Then check for Src2 in low and Src1 in high
3022 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3023 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3024 // The shuffle is concatenating two vectors together.
3025 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3031 // Pad both vectors with undefs to make them the same length as the mask.
3032 unsigned NumConcat = MaskNumElts / SrcNumElts;
3033 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3034 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3035 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3037 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3038 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3042 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3044 &MOps1[0], NumConcat);
3045 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3047 &MOps2[0], NumConcat);
3049 // Readjust mask for new input vector length.
3050 SmallVector<int, 8> MappedOps;
3051 for (unsigned i = 0; i != MaskNumElts; ++i) {
3053 if (Idx >= (int)SrcNumElts)
3054 Idx -= SrcNumElts - MaskNumElts;
3055 MappedOps.push_back(Idx);
3058 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3063 if (SrcNumElts > MaskNumElts) {
3064 // Analyze the access pattern of the vector to see if we can extract
3065 // two subvectors and do the shuffle. The analysis is done by calculating
3066 // the range of elements the mask access on both vectors.
3067 int MinRange[2] = { static_cast<int>(SrcNumElts),
3068 static_cast<int>(SrcNumElts)};
3069 int MaxRange[2] = {-1, -1};
3071 for (unsigned i = 0; i != MaskNumElts; ++i) {
3077 if (Idx >= (int)SrcNumElts) {
3081 if (Idx > MaxRange[Input])
3082 MaxRange[Input] = Idx;
3083 if (Idx < MinRange[Input])
3084 MinRange[Input] = Idx;
3087 // Check if the access is smaller than the vector size and can we find
3088 // a reasonable extract index.
3089 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3091 int StartIdx[2]; // StartIdx to extract from
3092 for (unsigned Input = 0; Input < 2; ++Input) {
3093 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3094 RangeUse[Input] = 0; // Unused
3095 StartIdx[Input] = 0;
3099 // Find a good start index that is a multiple of the mask length. Then
3100 // see if the rest of the elements are in range.
3101 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3102 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3103 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3104 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3107 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3108 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3111 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3112 // Extract appropriate subvector and generate a vector shuffle
3113 for (unsigned Input = 0; Input < 2; ++Input) {
3114 SDValue &Src = Input == 0 ? Src1 : Src2;
3115 if (RangeUse[Input] == 0)
3116 Src = DAG.getUNDEF(VT);
3118 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
3119 Src, DAG.getConstant(StartIdx[Input],
3120 TLI->getVectorIdxTy()));
3123 // Calculate new mask.
3124 SmallVector<int, 8> MappedOps;
3125 for (unsigned i = 0; i != MaskNumElts; ++i) {
3128 if (Idx < (int)SrcNumElts)
3131 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3133 MappedOps.push_back(Idx);
3136 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3142 // We can't use either concat vectors or extract subvectors so fall back to
3143 // replacing the shuffle with extract and build vector.
3144 // to insert and build vector.
3145 EVT EltVT = VT.getVectorElementType();
3146 EVT IdxVT = TLI->getVectorIdxTy();
3147 SmallVector<SDValue,8> Ops;
3148 for (unsigned i = 0; i != MaskNumElts; ++i) {
3153 Res = DAG.getUNDEF(EltVT);
3155 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3156 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3158 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3159 EltVT, Src, DAG.getConstant(Idx, IdxVT));
3165 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
3166 VT, &Ops[0], Ops.size()));
3169 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3170 const Value *Op0 = I.getOperand(0);
3171 const Value *Op1 = I.getOperand(1);
3172 Type *AggTy = I.getType();
3173 Type *ValTy = Op1->getType();
3174 bool IntoUndef = isa<UndefValue>(Op0);
3175 bool FromUndef = isa<UndefValue>(Op1);
3177 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3179 const TargetLowering *TLI = TM.getTargetLowering();
3180 SmallVector<EVT, 4> AggValueVTs;
3181 ComputeValueVTs(*TLI, AggTy, AggValueVTs);
3182 SmallVector<EVT, 4> ValValueVTs;
3183 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3185 unsigned NumAggValues = AggValueVTs.size();
3186 unsigned NumValValues = ValValueVTs.size();
3187 SmallVector<SDValue, 4> Values(NumAggValues);
3189 SDValue Agg = getValue(Op0);
3191 // Copy the beginning value(s) from the original aggregate.
3192 for (; i != LinearIndex; ++i)
3193 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3194 SDValue(Agg.getNode(), Agg.getResNo() + i);
3195 // Copy values from the inserted value(s).
3197 SDValue Val = getValue(Op1);
3198 for (; i != LinearIndex + NumValValues; ++i)
3199 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3200 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3202 // Copy remaining value(s) from the original aggregate.
3203 for (; i != NumAggValues; ++i)
3204 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3205 SDValue(Agg.getNode(), Agg.getResNo() + i);
3207 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3208 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3209 &Values[0], NumAggValues));
3212 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3213 const Value *Op0 = I.getOperand(0);
3214 Type *AggTy = Op0->getType();
3215 Type *ValTy = I.getType();
3216 bool OutOfUndef = isa<UndefValue>(Op0);
3218 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3220 const TargetLowering *TLI = TM.getTargetLowering();
3221 SmallVector<EVT, 4> ValValueVTs;
3222 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3224 unsigned NumValValues = ValValueVTs.size();
3226 // Ignore a extractvalue that produces an empty object
3227 if (!NumValValues) {
3228 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3232 SmallVector<SDValue, 4> Values(NumValValues);
3234 SDValue Agg = getValue(Op0);
3235 // Copy out the selected value(s).
3236 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3237 Values[i - LinearIndex] =
3239 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3240 SDValue(Agg.getNode(), Agg.getResNo() + i);
3242 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3243 DAG.getVTList(&ValValueVTs[0], NumValValues),
3244 &Values[0], NumValValues));
3247 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3248 Value *Op0 = I.getOperand(0);
3249 // Note that the pointer operand may be a vector of pointers. Take the scalar
3250 // element which holds a pointer.
3251 Type *Ty = Op0->getType()->getScalarType();
3252 unsigned AS = Ty->getPointerAddressSpace();
3253 SDValue N = getValue(Op0);
3255 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3257 const Value *Idx = *OI;
3258 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3259 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3262 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
3263 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3264 DAG.getConstant(Offset, N.getValueType()));
3267 Ty = StTy->getElementType(Field);
3269 Ty = cast<SequentialType>(Ty)->getElementType();
3271 // If this is a constant subscript, handle it quickly.
3272 const TargetLowering *TLI = TM.getTargetLowering();
3273 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3274 if (CI->isZero()) continue;
3276 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3278 EVT PTy = TLI->getPointerTy(AS);
3279 unsigned PtrBits = PTy.getSizeInBits();
3281 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3282 DAG.getConstant(Offs, MVT::i64));
3284 OffsVal = DAG.getConstant(Offs, PTy);
3286 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3291 // N = N + Idx * ElementSize;
3292 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
3293 TD->getTypeAllocSize(Ty));
3294 SDValue IdxN = getValue(Idx);
3296 // If the index is smaller or larger than intptr_t, truncate or extend
3298 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3300 // If this is a multiply by a power of two, turn it into a shl
3301 // immediately. This is a very common case.
3302 if (ElementSize != 1) {
3303 if (ElementSize.isPowerOf2()) {
3304 unsigned Amt = ElementSize.logBase2();
3305 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3306 N.getValueType(), IdxN,
3307 DAG.getConstant(Amt, IdxN.getValueType()));
3309 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3310 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3311 N.getValueType(), IdxN, Scale);
3315 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3316 N.getValueType(), N, IdxN);
3323 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3324 // If this is a fixed sized alloca in the entry block of the function,
3325 // allocate it statically on the stack.
3326 if (FuncInfo.StaticAllocaMap.count(&I))
3327 return; // getValue will auto-populate this.
3329 Type *Ty = I.getAllocatedType();
3330 const TargetLowering *TLI = TM.getTargetLowering();
3331 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
3333 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
3336 SDValue AllocSize = getValue(I.getArraySize());
3338 EVT IntPtr = TLI->getPointerTy();
3339 if (AllocSize.getValueType() != IntPtr)
3340 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3342 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3344 DAG.getConstant(TySize, IntPtr));
3346 // Handle alignment. If the requested alignment is less than or equal to
3347 // the stack alignment, ignore it. If the size is greater than or equal to
3348 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3349 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3350 if (Align <= StackAlign)
3353 // Round the size of the allocation up to the stack alignment size
3354 // by add SA-1 to the size.
3355 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3356 AllocSize.getValueType(), AllocSize,
3357 DAG.getIntPtrConstant(StackAlign-1));
3359 // Mask out the low bits for alignment purposes.
3360 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3361 AllocSize.getValueType(), AllocSize,
3362 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3364 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3365 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3366 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
3369 DAG.setRoot(DSA.getValue(1));
3371 // Inform the Frame Information that we have just allocated a variable-sized
3373 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3376 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3378 return visitAtomicLoad(I);
3380 const Value *SV = I.getOperand(0);
3381 SDValue Ptr = getValue(SV);
3383 Type *Ty = I.getType();
3385 bool isVolatile = I.isVolatile();
3386 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3387 bool isInvariant = I.getMetadata("invariant.load") != 0;
3388 unsigned Alignment = I.getAlignment();
3389 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3390 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3392 SmallVector<EVT, 4> ValueVTs;
3393 SmallVector<uint64_t, 4> Offsets;
3394 ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
3395 unsigned NumValues = ValueVTs.size();
3400 bool ConstantMemory = false;
3401 if (I.isVolatile() || NumValues > MaxParallelChains)
3402 // Serialize volatile loads with other side effects.
3404 else if (AA->pointsToConstantMemory(
3405 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3406 // Do not serialize (non-volatile) loads of constant memory with anything.
3407 Root = DAG.getEntryNode();
3408 ConstantMemory = true;
3410 // Do not serialize non-volatile loads against each other.
3411 Root = DAG.getRoot();
3414 SmallVector<SDValue, 4> Values(NumValues);
3415 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3417 EVT PtrVT = Ptr.getValueType();
3418 unsigned ChainI = 0;
3419 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3420 // Serializing loads here may result in excessive register pressure, and
3421 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3422 // could recover a bit by hoisting nodes upward in the chain by recognizing
3423 // they are side-effect free or do not alias. The optimizer should really
3424 // avoid this case by converting large object/array copies to llvm.memcpy
3425 // (MaxParallelChains should always remain as failsafe).
3426 if (ChainI == MaxParallelChains) {
3427 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3428 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3429 MVT::Other, &Chains[0], ChainI);
3433 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3435 DAG.getConstant(Offsets[i], PtrVT));
3436 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3437 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3438 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3442 Chains[ChainI] = L.getValue(1);
3445 if (!ConstantMemory) {
3446 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3447 MVT::Other, &Chains[0], ChainI);
3451 PendingLoads.push_back(Chain);
3454 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3455 DAG.getVTList(&ValueVTs[0], NumValues),
3456 &Values[0], NumValues));
3459 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3461 return visitAtomicStore(I);
3463 const Value *SrcV = I.getOperand(0);
3464 const Value *PtrV = I.getOperand(1);
3466 SmallVector<EVT, 4> ValueVTs;
3467 SmallVector<uint64_t, 4> Offsets;
3468 ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
3469 unsigned NumValues = ValueVTs.size();
3473 // Get the lowered operands. Note that we do this after
3474 // checking if NumResults is zero, because with zero results
3475 // the operands won't have values in the map.
3476 SDValue Src = getValue(SrcV);
3477 SDValue Ptr = getValue(PtrV);
3479 SDValue Root = getRoot();
3480 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3482 EVT PtrVT = Ptr.getValueType();
3483 bool isVolatile = I.isVolatile();
3484 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3485 unsigned Alignment = I.getAlignment();
3486 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3488 unsigned ChainI = 0;
3489 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3490 // See visitLoad comments.
3491 if (ChainI == MaxParallelChains) {
3492 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3493 MVT::Other, &Chains[0], ChainI);
3497 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3498 DAG.getConstant(Offsets[i], PtrVT));
3499 SDValue St = DAG.getStore(Root, getCurSDLoc(),
3500 SDValue(Src.getNode(), Src.getResNo() + i),
3501 Add, MachinePointerInfo(PtrV, Offsets[i]),
3502 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3503 Chains[ChainI] = St;
3506 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3507 MVT::Other, &Chains[0], ChainI);
3508 DAG.setRoot(StoreNode);
3511 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
3512 SynchronizationScope Scope,
3513 bool Before, SDLoc dl,
3515 const TargetLowering &TLI) {
3516 // Fence, if necessary
3518 if (Order == AcquireRelease || Order == SequentiallyConsistent)
3520 else if (Order == Acquire || Order == Monotonic)
3523 if (Order == AcquireRelease)
3525 else if (Order == Release || Order == Monotonic)
3530 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3531 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
3532 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3535 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3536 SDLoc dl = getCurSDLoc();
3537 AtomicOrdering Order = I.getOrdering();
3538 SynchronizationScope Scope = I.getSynchScope();
3540 SDValue InChain = getRoot();
3542 const TargetLowering *TLI = TM.getTargetLowering();
3543 if (TLI->getInsertFencesForAtomic())
3544 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3548 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
3549 getValue(I.getCompareOperand()).getSimpleValueType(),
3551 getValue(I.getPointerOperand()),
3552 getValue(I.getCompareOperand()),
3553 getValue(I.getNewValOperand()),
3554 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
3555 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3558 SDValue OutChain = L.getValue(1);
3560 if (TLI->getInsertFencesForAtomic())
3561 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3565 DAG.setRoot(OutChain);
3568 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3569 SDLoc dl = getCurSDLoc();
3571 switch (I.getOperation()) {
3572 default: llvm_unreachable("Unknown atomicrmw operation");
3573 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3574 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3575 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3576 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3577 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3578 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3579 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3580 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3581 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3582 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3583 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3585 AtomicOrdering Order = I.getOrdering();
3586 SynchronizationScope Scope = I.getSynchScope();
3588 SDValue InChain = getRoot();
3590 const TargetLowering *TLI = TM.getTargetLowering();
3591 if (TLI->getInsertFencesForAtomic())
3592 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3596 DAG.getAtomic(NT, dl,
3597 getValue(I.getValOperand()).getSimpleValueType(),
3599 getValue(I.getPointerOperand()),
3600 getValue(I.getValOperand()),
3601 I.getPointerOperand(), 0 /* Alignment */,
3602 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3605 SDValue OutChain = L.getValue(1);
3607 if (TLI->getInsertFencesForAtomic())
3608 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3612 DAG.setRoot(OutChain);
3615 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3616 SDLoc dl = getCurSDLoc();
3617 const TargetLowering *TLI = TM.getTargetLowering();
3620 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
3621 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
3622 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
3625 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3626 SDLoc dl = getCurSDLoc();
3627 AtomicOrdering Order = I.getOrdering();
3628 SynchronizationScope Scope = I.getSynchScope();
3630 SDValue InChain = getRoot();
3632 const TargetLowering *TLI = TM.getTargetLowering();
3633 EVT VT = TLI->getValueType(I.getType());
3635 if (I.getAlignment() < VT.getSizeInBits() / 8)
3636 report_fatal_error("Cannot generate unaligned atomic load");
3639 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3640 getValue(I.getPointerOperand()),
3641 I.getPointerOperand(), I.getAlignment(),
3642 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3645 SDValue OutChain = L.getValue(1);
3647 if (TLI->getInsertFencesForAtomic())
3648 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3652 DAG.setRoot(OutChain);
3655 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3656 SDLoc dl = getCurSDLoc();
3658 AtomicOrdering Order = I.getOrdering();
3659 SynchronizationScope Scope = I.getSynchScope();
3661 SDValue InChain = getRoot();
3663 const TargetLowering *TLI = TM.getTargetLowering();
3664 EVT VT = TLI->getValueType(I.getValueOperand()->getType());
3666 if (I.getAlignment() < VT.getSizeInBits() / 8)
3667 report_fatal_error("Cannot generate unaligned atomic store");
3669 if (TLI->getInsertFencesForAtomic())
3670 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3674 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3676 getValue(I.getPointerOperand()),
3677 getValue(I.getValueOperand()),
3678 I.getPointerOperand(), I.getAlignment(),
3679 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3682 if (TLI->getInsertFencesForAtomic())
3683 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3686 DAG.setRoot(OutChain);
3689 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3691 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3692 unsigned Intrinsic) {
3693 bool HasChain = !I.doesNotAccessMemory();
3694 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3696 // Build the operand list.
3697 SmallVector<SDValue, 8> Ops;
3698 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3700 // We don't need to serialize loads against other loads.
3701 Ops.push_back(DAG.getRoot());
3703 Ops.push_back(getRoot());
3707 // Info is set by getTgtMemInstrinsic
3708 TargetLowering::IntrinsicInfo Info;
3709 const TargetLowering *TLI = TM.getTargetLowering();
3710 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
3712 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3713 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3714 Info.opc == ISD::INTRINSIC_W_CHAIN)
3715 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
3717 // Add all operands of the call to the operand list.
3718 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3719 SDValue Op = getValue(I.getArgOperand(i));
3723 SmallVector<EVT, 4> ValueVTs;
3724 ComputeValueVTs(*TLI, I.getType(), ValueVTs);
3727 ValueVTs.push_back(MVT::Other);
3729 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3733 if (IsTgtIntrinsic) {
3734 // This is target intrinsic that touches memory
3735 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3736 VTs, &Ops[0], Ops.size(),
3738 MachinePointerInfo(Info.ptrVal, Info.offset),
3739 Info.align, Info.vol,
3740 Info.readMem, Info.writeMem);
3741 } else if (!HasChain) {
3742 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
3743 VTs, &Ops[0], Ops.size());
3744 } else if (!I.getType()->isVoidTy()) {
3745 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
3746 VTs, &Ops[0], Ops.size());
3748 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
3749 VTs, &Ops[0], Ops.size());
3753 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3755 PendingLoads.push_back(Chain);
3760 if (!I.getType()->isVoidTy()) {
3761 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3762 EVT VT = TLI->getValueType(PTy);
3763 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3766 setValue(&I, Result);
3770 /// GetSignificand - Get the significand and build it into a floating-point
3771 /// number with exponent of 1:
3773 /// Op = (Op & 0x007fffff) | 0x3f800000;
3775 /// where Op is the hexadecimal representation of floating point value.
3777 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3778 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3779 DAG.getConstant(0x007fffff, MVT::i32));
3780 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3781 DAG.getConstant(0x3f800000, MVT::i32));
3782 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3785 /// GetExponent - Get the exponent:
3787 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3789 /// where Op is the hexadecimal representation of floating point value.
3791 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3793 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3794 DAG.getConstant(0x7f800000, MVT::i32));
3795 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3796 DAG.getConstant(23, TLI.getPointerTy()));
3797 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3798 DAG.getConstant(127, MVT::i32));
3799 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3802 /// getF32Constant - Get 32-bit floating point constant.
3804 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3805 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3809 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3810 /// limited-precision mode.
3811 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3812 const TargetLowering &TLI) {
3813 if (Op.getValueType() == MVT::f32 &&
3814 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3816 // Put the exponent in the right bit position for later addition to the
3819 // #define LOG2OFe 1.4426950f
3820 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3821 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3822 getF32Constant(DAG, 0x3fb8aa3b));
3823 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3825 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3826 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3827 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3829 // IntegerPartOfX <<= 23;
3830 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3831 DAG.getConstant(23, TLI.getPointerTy()));
3833 SDValue TwoToFracPartOfX;
3834 if (LimitFloatPrecision <= 6) {
3835 // For floating-point precision of 6:
3837 // TwoToFractionalPartOfX =
3839 // (0.735607626f + 0.252464424f * x) * x;
3841 // error 0.0144103317, which is 6 bits
3842 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3843 getF32Constant(DAG, 0x3e814304));
3844 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3845 getF32Constant(DAG, 0x3f3c50c8));
3846 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3847 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3848 getF32Constant(DAG, 0x3f7f5e7e));
3849 } else if (LimitFloatPrecision <= 12) {
3850 // For floating-point precision of 12:
3852 // TwoToFractionalPartOfX =
3855 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3857 // 0.000107046256 error, which is 13 to 14 bits
3858 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3859 getF32Constant(DAG, 0x3da235e3));
3860 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3861 getF32Constant(DAG, 0x3e65b8f3));
3862 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3863 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3864 getF32Constant(DAG, 0x3f324b07));
3865 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3866 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3867 getF32Constant(DAG, 0x3f7ff8fd));
3868 } else { // LimitFloatPrecision <= 18
3869 // For floating-point precision of 18:
3871 // TwoToFractionalPartOfX =
3875 // (0.554906021e-1f +
3876 // (0.961591928e-2f +
3877 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3879 // error 2.47208000*10^(-7), which is better than 18 bits
3880 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3881 getF32Constant(DAG, 0x3924b03e));
3882 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3883 getF32Constant(DAG, 0x3ab24b87));
3884 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3885 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3886 getF32Constant(DAG, 0x3c1d8c17));
3887 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3888 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3889 getF32Constant(DAG, 0x3d634a1d));
3890 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3891 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3892 getF32Constant(DAG, 0x3e75fe14));
3893 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3894 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3895 getF32Constant(DAG, 0x3f317234));
3896 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3897 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3898 getF32Constant(DAG, 0x3f800000));
3901 // Add the exponent into the result in integer domain.
3902 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
3903 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3904 DAG.getNode(ISD::ADD, dl, MVT::i32,
3905 t13, IntegerPartOfX));
3908 // No special expansion.
3909 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3912 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3913 /// limited-precision mode.
3914 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3915 const TargetLowering &TLI) {
3916 if (Op.getValueType() == MVT::f32 &&
3917 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3918 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3920 // Scale the exponent by log(2) [0.69314718f].
3921 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3922 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3923 getF32Constant(DAG, 0x3f317218));
3925 // Get the significand and build it into a floating-point number with
3927 SDValue X = GetSignificand(DAG, Op1, dl);
3929 SDValue LogOfMantissa;
3930 if (LimitFloatPrecision <= 6) {
3931 // For floating-point precision of 6:
3935 // (1.4034025f - 0.23903021f * x) * x;
3937 // error 0.0034276066, which is better than 8 bits
3938 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3939 getF32Constant(DAG, 0xbe74c456));
3940 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3941 getF32Constant(DAG, 0x3fb3a2b1));
3942 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3943 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3944 getF32Constant(DAG, 0x3f949a29));
3945 } else if (LimitFloatPrecision <= 12) {
3946 // For floating-point precision of 12:
3952 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3954 // error 0.000061011436, which is 14 bits
3955 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3956 getF32Constant(DAG, 0xbd67b6d6));
3957 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3958 getF32Constant(DAG, 0x3ee4f4b8));
3959 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3960 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3961 getF32Constant(DAG, 0x3fbc278b));
3962 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3963 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3964 getF32Constant(DAG, 0x40348e95));
3965 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3966 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3967 getF32Constant(DAG, 0x3fdef31a));
3968 } else { // LimitFloatPrecision <= 18
3969 // For floating-point precision of 18:
3977 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3979 // error 0.0000023660568, which is better than 18 bits
3980 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3981 getF32Constant(DAG, 0xbc91e5ac));
3982 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3983 getF32Constant(DAG, 0x3e4350aa));
3984 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3985 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3986 getF32Constant(DAG, 0x3f60d3e3));
3987 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3988 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3989 getF32Constant(DAG, 0x4011cdf0));
3990 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3991 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3992 getF32Constant(DAG, 0x406cfd1c));
3993 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3994 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3995 getF32Constant(DAG, 0x408797cb));
3996 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3997 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3998 getF32Constant(DAG, 0x4006dcab));
4001 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4004 // No special expansion.
4005 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4008 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4009 /// limited-precision mode.
4010 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4011 const TargetLowering &TLI) {
4012 if (Op.getValueType() == MVT::f32 &&
4013 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4014 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4016 // Get the exponent.
4017 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4019 // Get the significand and build it into a floating-point number with
4021 SDValue X = GetSignificand(DAG, Op1, dl);
4023 // Different possible minimax approximations of significand in
4024 // floating-point for various degrees of accuracy over [1,2].
4025 SDValue Log2ofMantissa;
4026 if (LimitFloatPrecision <= 6) {
4027 // For floating-point precision of 6:
4029 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4031 // error 0.0049451742, which is more than 7 bits
4032 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4033 getF32Constant(DAG, 0xbeb08fe0));
4034 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4035 getF32Constant(DAG, 0x40019463));
4036 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4037 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4038 getF32Constant(DAG, 0x3fd6633d));
4039 } else if (LimitFloatPrecision <= 12) {
4040 // For floating-point precision of 12:
4046 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4048 // error 0.0000876136000, which is better than 13 bits
4049 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4050 getF32Constant(DAG, 0xbda7262e));
4051 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4052 getF32Constant(DAG, 0x3f25280b));
4053 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4054 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4055 getF32Constant(DAG, 0x4007b923));
4056 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4057 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4058 getF32Constant(DAG, 0x40823e2f));
4059 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4060 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4061 getF32Constant(DAG, 0x4020d29c));
4062 } else { // LimitFloatPrecision <= 18
4063 // For floating-point precision of 18:
4072 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4074 // error 0.0000018516, which is better than 18 bits
4075 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4076 getF32Constant(DAG, 0xbcd2769e));
4077 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4078 getF32Constant(DAG, 0x3e8ce0b9));
4079 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4080 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4081 getF32Constant(DAG, 0x3fa22ae7));
4082 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4083 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4084 getF32Constant(DAG, 0x40525723));
4085 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4086 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4087 getF32Constant(DAG, 0x40aaf200));
4088 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4089 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4090 getF32Constant(DAG, 0x40c39dad));
4091 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4092 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4093 getF32Constant(DAG, 0x4042902c));
4096 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4099 // No special expansion.
4100 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4103 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4104 /// limited-precision mode.
4105 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4106 const TargetLowering &TLI) {
4107 if (Op.getValueType() == MVT::f32 &&
4108 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4109 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4111 // Scale the exponent by log10(2) [0.30102999f].
4112 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4113 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4114 getF32Constant(DAG, 0x3e9a209a));
4116 // Get the significand and build it into a floating-point number with
4118 SDValue X = GetSignificand(DAG, Op1, dl);
4120 SDValue Log10ofMantissa;
4121 if (LimitFloatPrecision <= 6) {
4122 // For floating-point precision of 6:
4124 // Log10ofMantissa =
4126 // (0.60948995f - 0.10380950f * x) * x;
4128 // error 0.0014886165, which is 6 bits
4129 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4130 getF32Constant(DAG, 0xbdd49a13));
4131 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4132 getF32Constant(DAG, 0x3f1c0789));
4133 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4134 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4135 getF32Constant(DAG, 0x3f011300));
4136 } else if (LimitFloatPrecision <= 12) {
4137 // For floating-point precision of 12:
4139 // Log10ofMantissa =
4142 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4144 // error 0.00019228036, which is better than 12 bits
4145 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4146 getF32Constant(DAG, 0x3d431f31));
4147 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4148 getF32Constant(DAG, 0x3ea21fb2));
4149 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4150 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4151 getF32Constant(DAG, 0x3f6ae232));
4152 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4153 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4154 getF32Constant(DAG, 0x3f25f7c3));
4155 } else { // LimitFloatPrecision <= 18
4156 // For floating-point precision of 18:
4158 // Log10ofMantissa =
4163 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4165 // error 0.0000037995730, which is better than 18 bits
4166 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4167 getF32Constant(DAG, 0x3c5d51ce));
4168 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4169 getF32Constant(DAG, 0x3e00685a));
4170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4171 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4172 getF32Constant(DAG, 0x3efb6798));
4173 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4174 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4175 getF32Constant(DAG, 0x3f88d192));
4176 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4177 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4178 getF32Constant(DAG, 0x3fc4316c));
4179 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4180 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4181 getF32Constant(DAG, 0x3f57ce70));
4184 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4187 // No special expansion.
4188 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4191 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4192 /// limited-precision mode.
4193 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4194 const TargetLowering &TLI) {
4195 if (Op.getValueType() == MVT::f32 &&
4196 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4197 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4199 // FractionalPartOfX = x - (float)IntegerPartOfX;
4200 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4201 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4203 // IntegerPartOfX <<= 23;
4204 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4205 DAG.getConstant(23, TLI.getPointerTy()));
4207 SDValue TwoToFractionalPartOfX;
4208 if (LimitFloatPrecision <= 6) {
4209 // For floating-point precision of 6:
4211 // TwoToFractionalPartOfX =
4213 // (0.735607626f + 0.252464424f * x) * x;
4215 // error 0.0144103317, which is 6 bits
4216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4217 getF32Constant(DAG, 0x3e814304));
4218 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4219 getF32Constant(DAG, 0x3f3c50c8));
4220 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4221 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4222 getF32Constant(DAG, 0x3f7f5e7e));
4223 } else if (LimitFloatPrecision <= 12) {
4224 // For floating-point precision of 12:
4226 // TwoToFractionalPartOfX =
4229 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4231 // error 0.000107046256, which is 13 to 14 bits
4232 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4233 getF32Constant(DAG, 0x3da235e3));
4234 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4235 getF32Constant(DAG, 0x3e65b8f3));
4236 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4237 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4238 getF32Constant(DAG, 0x3f324b07));
4239 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4240 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4241 getF32Constant(DAG, 0x3f7ff8fd));
4242 } else { // LimitFloatPrecision <= 18
4243 // For floating-point precision of 18:
4245 // TwoToFractionalPartOfX =
4249 // (0.554906021e-1f +
4250 // (0.961591928e-2f +
4251 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4252 // error 2.47208000*10^(-7), which is better than 18 bits
4253 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4254 getF32Constant(DAG, 0x3924b03e));
4255 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4256 getF32Constant(DAG, 0x3ab24b87));
4257 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4258 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4259 getF32Constant(DAG, 0x3c1d8c17));
4260 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4261 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4262 getF32Constant(DAG, 0x3d634a1d));
4263 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4264 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4265 getF32Constant(DAG, 0x3e75fe14));
4266 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4267 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4268 getF32Constant(DAG, 0x3f317234));
4269 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4270 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4271 getF32Constant(DAG, 0x3f800000));
4274 // Add the exponent into the result in integer domain.
4275 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4276 TwoToFractionalPartOfX);
4277 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4278 DAG.getNode(ISD::ADD, dl, MVT::i32,
4279 t13, IntegerPartOfX));
4282 // No special expansion.
4283 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4286 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4287 /// limited-precision mode with x == 10.0f.
4288 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4289 SelectionDAG &DAG, const TargetLowering &TLI) {
4290 bool IsExp10 = false;
4291 if (LHS.getValueType() == MVT::f32 && LHS.getValueType() == MVT::f32 &&
4292 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4293 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4295 IsExp10 = LHSC->isExactlyValue(Ten);
4300 // Put the exponent in the right bit position for later addition to the
4303 // #define LOG2OF10 3.3219281f
4304 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4306 getF32Constant(DAG, 0x40549a78));
4307 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4309 // FractionalPartOfX = x - (float)IntegerPartOfX;
4310 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4311 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4313 // IntegerPartOfX <<= 23;
4314 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4315 DAG.getConstant(23, TLI.getPointerTy()));
4317 SDValue TwoToFractionalPartOfX;
4318 if (LimitFloatPrecision <= 6) {
4319 // For floating-point precision of 6:
4321 // twoToFractionalPartOfX =
4323 // (0.735607626f + 0.252464424f * x) * x;
4325 // error 0.0144103317, which is 6 bits
4326 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4327 getF32Constant(DAG, 0x3e814304));
4328 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4329 getF32Constant(DAG, 0x3f3c50c8));
4330 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4331 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4332 getF32Constant(DAG, 0x3f7f5e7e));
4333 } else if (LimitFloatPrecision <= 12) {
4334 // For floating-point precision of 12:
4336 // TwoToFractionalPartOfX =
4339 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4341 // error 0.000107046256, which is 13 to 14 bits
4342 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4343 getF32Constant(DAG, 0x3da235e3));
4344 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4345 getF32Constant(DAG, 0x3e65b8f3));
4346 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4347 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4348 getF32Constant(DAG, 0x3f324b07));
4349 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4350 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4351 getF32Constant(DAG, 0x3f7ff8fd));
4352 } else { // LimitFloatPrecision <= 18
4353 // For floating-point precision of 18:
4355 // TwoToFractionalPartOfX =
4359 // (0.554906021e-1f +
4360 // (0.961591928e-2f +
4361 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4362 // error 2.47208000*10^(-7), which is better than 18 bits
4363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4364 getF32Constant(DAG, 0x3924b03e));
4365 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4366 getF32Constant(DAG, 0x3ab24b87));
4367 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4368 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4369 getF32Constant(DAG, 0x3c1d8c17));
4370 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4371 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4372 getF32Constant(DAG, 0x3d634a1d));
4373 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4374 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4375 getF32Constant(DAG, 0x3e75fe14));
4376 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4377 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4378 getF32Constant(DAG, 0x3f317234));
4379 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4380 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4381 getF32Constant(DAG, 0x3f800000));
4384 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
4385 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4386 DAG.getNode(ISD::ADD, dl, MVT::i32,
4387 t13, IntegerPartOfX));
4390 // No special expansion.
4391 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4395 /// ExpandPowI - Expand a llvm.powi intrinsic.
4396 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4397 SelectionDAG &DAG) {
4398 // If RHS is a constant, we can expand this out to a multiplication tree,
4399 // otherwise we end up lowering to a call to __powidf2 (for example). When
4400 // optimizing for size, we only want to do this if the expansion would produce
4401 // a small number of multiplies, otherwise we do the full expansion.
4402 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4403 // Get the exponent as a positive value.
4404 unsigned Val = RHSC->getSExtValue();
4405 if ((int)Val < 0) Val = -Val;
4407 // powi(x, 0) -> 1.0
4409 return DAG.getConstantFP(1.0, LHS.getValueType());
4411 const Function *F = DAG.getMachineFunction().getFunction();
4412 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4413 Attribute::OptimizeForSize) ||
4414 // If optimizing for size, don't insert too many multiplies. This
4415 // inserts up to 5 multiplies.
4416 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4417 // We use the simple binary decomposition method to generate the multiply
4418 // sequence. There are more optimal ways to do this (for example,
4419 // powi(x,15) generates one more multiply than it should), but this has
4420 // the benefit of being both really simple and much better than a libcall.
4421 SDValue Res; // Logically starts equal to 1.0
4422 SDValue CurSquare = LHS;
4426 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4428 Res = CurSquare; // 1.0*CurSquare.
4431 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4432 CurSquare, CurSquare);
4436 // If the original was negative, invert the result, producing 1/(x*x*x).
4437 if (RHSC->getSExtValue() < 0)
4438 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4439 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4444 // Otherwise, expand to a libcall.
4445 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4448 // getTruncatedArgReg - Find underlying register used for an truncated
4450 static unsigned getTruncatedArgReg(const SDValue &N) {
4451 if (N.getOpcode() != ISD::TRUNCATE)
4454 const SDValue &Ext = N.getOperand(0);
4455 if (Ext.getOpcode() == ISD::AssertZext ||
4456 Ext.getOpcode() == ISD::AssertSext) {
4457 const SDValue &CFR = Ext.getOperand(0);
4458 if (CFR.getOpcode() == ISD::CopyFromReg)
4459 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4460 if (CFR.getOpcode() == ISD::TRUNCATE)
4461 return getTruncatedArgReg(CFR);
4466 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4467 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4468 /// At the end of instruction selection, they will be inserted to the entry BB.
4470 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4473 const Argument *Arg = dyn_cast<Argument>(V);
4477 MachineFunction &MF = DAG.getMachineFunction();
4478 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4480 // Ignore inlined function arguments here.
4481 DIVariable DV(Variable);
4482 if (DV.isInlinedFnArgument(MF.getFunction()))
4485 Optional<MachineOperand> Op;
4486 // Some arguments' frame index is recorded during argument lowering.
4487 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4488 Op = MachineOperand::CreateFI(FI);
4490 if (!Op && N.getNode()) {
4492 if (N.getOpcode() == ISD::CopyFromReg)
4493 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4495 Reg = getTruncatedArgReg(N);
4496 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4497 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4498 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4503 Op = MachineOperand::CreateReg(Reg, false);
4507 // Check if ValueMap has reg number.
4508 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4509 if (VMI != FuncInfo.ValueMap.end())
4510 Op = MachineOperand::CreateReg(VMI->second, false);
4513 if (!Op && N.getNode())
4514 // Check if frame index is available.
4515 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4516 if (FrameIndexSDNode *FINode =
4517 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4518 Op = MachineOperand::CreateFI(FINode->getIndex());
4523 // FIXME: This does not handle register-indirect values at offset 0.
4524 bool IsIndirect = Offset != 0;
4526 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
4527 TII->get(TargetOpcode::DBG_VALUE),
4529 Op->getReg(), Offset, Variable));
4531 FuncInfo.ArgDbgValues.push_back(
4532 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4533 .addOperand(*Op).addImm(Offset).addMetadata(Variable));
4538 // VisualStudio defines setjmp as _setjmp
4539 #if defined(_MSC_VER) && defined(setjmp) && \
4540 !defined(setjmp_undefined_for_msvc)
4541 # pragma push_macro("setjmp")
4543 # define setjmp_undefined_for_msvc
4546 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4547 /// we want to emit this as a call to a named external function, return the name
4548 /// otherwise lower it and return null.
4550 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4551 const TargetLowering *TLI = TM.getTargetLowering();
4552 SDLoc sdl = getCurSDLoc();
4553 DebugLoc dl = getCurDebugLoc();
4556 switch (Intrinsic) {
4558 // By default, turn this into a target intrinsic node.
4559 visitTargetIntrinsic(I, Intrinsic);
4561 case Intrinsic::vastart: visitVAStart(I); return 0;
4562 case Intrinsic::vaend: visitVAEnd(I); return 0;
4563 case Intrinsic::vacopy: visitVACopy(I); return 0;
4564 case Intrinsic::returnaddress:
4565 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
4566 getValue(I.getArgOperand(0))));
4568 case Intrinsic::frameaddress:
4569 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
4570 getValue(I.getArgOperand(0))));
4572 case Intrinsic::setjmp:
4573 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
4574 case Intrinsic::longjmp:
4575 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
4576 case Intrinsic::memcpy: {
4577 // Assert for address < 256 since we support only user defined address
4579 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4581 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4583 "Unknown address space");
4584 SDValue Op1 = getValue(I.getArgOperand(0));
4585 SDValue Op2 = getValue(I.getArgOperand(1));
4586 SDValue Op3 = getValue(I.getArgOperand(2));
4587 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4589 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4590 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4591 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
4592 MachinePointerInfo(I.getArgOperand(0)),
4593 MachinePointerInfo(I.getArgOperand(1))));
4596 case Intrinsic::memset: {
4597 // Assert for address < 256 since we support only user defined address
4599 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4601 "Unknown address space");
4602 SDValue Op1 = getValue(I.getArgOperand(0));
4603 SDValue Op2 = getValue(I.getArgOperand(1));
4604 SDValue Op3 = getValue(I.getArgOperand(2));
4605 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4607 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4608 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4609 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4610 MachinePointerInfo(I.getArgOperand(0))));
4613 case Intrinsic::memmove: {
4614 // Assert for address < 256 since we support only user defined address
4616 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4618 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4620 "Unknown address space");
4621 SDValue Op1 = getValue(I.getArgOperand(0));
4622 SDValue Op2 = getValue(I.getArgOperand(1));
4623 SDValue Op3 = getValue(I.getArgOperand(2));
4624 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4626 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4627 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4628 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4629 MachinePointerInfo(I.getArgOperand(0)),
4630 MachinePointerInfo(I.getArgOperand(1))));
4633 case Intrinsic::dbg_declare: {
4634 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4635 MDNode *Variable = DI.getVariable();
4636 const Value *Address = DI.getAddress();
4637 DIVariable DIVar(Variable);
4638 assert((!DIVar || DIVar.isVariable()) &&
4639 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4640 if (!Address || !DIVar) {
4641 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4645 // Check if address has undef value.
4646 if (isa<UndefValue>(Address) ||
4647 (Address->use_empty() && !isa<Argument>(Address))) {
4648 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4652 SDValue &N = NodeMap[Address];
4653 if (!N.getNode() && isa<Argument>(Address))
4654 // Check unused arguments map.
4655 N = UnusedArgNodeMap[Address];
4658 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4659 Address = BCI->getOperand(0);
4660 // Parameters are handled specially.
4662 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4663 isa<Argument>(Address));
4665 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4667 if (isParameter && !AI) {
4668 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4670 // Byval parameter. We have a frame index at this point.
4671 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4672 0, dl, SDNodeOrder);
4674 // Address is an argument, so try to emit its dbg value using
4675 // virtual register info from the FuncInfo.ValueMap.
4676 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4680 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4681 0, dl, SDNodeOrder);
4683 // Can't do anything with other non-AI cases yet.
4684 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4685 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4686 DEBUG(Address->dump());
4689 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4691 // If Address is an argument then try to emit its dbg value using
4692 // virtual register info from the FuncInfo.ValueMap.
4693 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4694 // If variable is pinned by a alloca in dominating bb then
4695 // use StaticAllocaMap.
4696 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4697 if (AI->getParent() != DI.getParent()) {
4698 DenseMap<const AllocaInst*, int>::iterator SI =
4699 FuncInfo.StaticAllocaMap.find(AI);
4700 if (SI != FuncInfo.StaticAllocaMap.end()) {
4701 SDV = DAG.getDbgValue(Variable, SI->second,
4702 0, dl, SDNodeOrder);
4703 DAG.AddDbgValue(SDV, 0, false);
4708 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4713 case Intrinsic::dbg_value: {
4714 const DbgValueInst &DI = cast<DbgValueInst>(I);
4715 DIVariable DIVar(DI.getVariable());
4716 assert((!DIVar || DIVar.isVariable()) &&
4717 "Variable in DbgValueInst should be either null or a DIVariable.");
4721 MDNode *Variable = DI.getVariable();
4722 uint64_t Offset = DI.getOffset();
4723 const Value *V = DI.getValue();
4728 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4729 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4730 DAG.AddDbgValue(SDV, 0, false);
4732 // Do not use getValue() in here; we don't want to generate code at
4733 // this point if it hasn't been done yet.
4734 SDValue N = NodeMap[V];
4735 if (!N.getNode() && isa<Argument>(V))
4736 // Check unused arguments map.
4737 N = UnusedArgNodeMap[V];
4739 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4740 SDV = DAG.getDbgValue(Variable, N.getNode(),
4741 N.getResNo(), Offset, dl, SDNodeOrder);
4742 DAG.AddDbgValue(SDV, N.getNode(), false);
4744 } else if (!V->use_empty() ) {
4745 // Do not call getValue(V) yet, as we don't want to generate code.
4746 // Remember it for later.
4747 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4748 DanglingDebugInfoMap[V] = DDI;
4750 // We may expand this to cover more cases. One case where we have no
4751 // data available is an unreferenced parameter.
4752 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4756 // Build a debug info table entry.
4757 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4758 V = BCI->getOperand(0);
4759 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4760 // Don't handle byval struct arguments or VLAs, for example.
4762 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4763 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4766 DenseMap<const AllocaInst*, int>::iterator SI =
4767 FuncInfo.StaticAllocaMap.find(AI);
4768 if (SI == FuncInfo.StaticAllocaMap.end())
4770 int FI = SI->second;
4772 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4773 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4774 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4778 case Intrinsic::eh_typeid_for: {
4779 // Find the type id for the given typeinfo.
4780 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4781 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4782 Res = DAG.getConstant(TypeID, MVT::i32);
4787 case Intrinsic::eh_return_i32:
4788 case Intrinsic::eh_return_i64:
4789 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4790 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4793 getValue(I.getArgOperand(0)),
4794 getValue(I.getArgOperand(1))));
4796 case Intrinsic::eh_unwind_init:
4797 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4799 case Intrinsic::eh_dwarf_cfa: {
4800 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4801 TLI->getPointerTy());
4802 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4803 CfaArg.getValueType(),
4804 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4805 CfaArg.getValueType()),
4807 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
4808 TLI->getPointerTy(),
4809 DAG.getConstant(0, TLI->getPointerTy()));
4810 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4814 case Intrinsic::eh_sjlj_callsite: {
4815 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4816 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4817 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4818 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4820 MMI.setCurrentCallSite(CI->getZExtValue());
4823 case Intrinsic::eh_sjlj_functioncontext: {
4824 // Get and store the index of the function context.
4825 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4827 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4828 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4829 MFI->setFunctionContextIndex(FI);
4832 case Intrinsic::eh_sjlj_setjmp: {
4835 Ops[1] = getValue(I.getArgOperand(0));
4836 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4837 DAG.getVTList(MVT::i32, MVT::Other),
4839 setValue(&I, Op.getValue(0));
4840 DAG.setRoot(Op.getValue(1));
4843 case Intrinsic::eh_sjlj_longjmp: {
4844 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4845 getRoot(), getValue(I.getArgOperand(0))));
4849 case Intrinsic::x86_mmx_pslli_w:
4850 case Intrinsic::x86_mmx_pslli_d:
4851 case Intrinsic::x86_mmx_pslli_q:
4852 case Intrinsic::x86_mmx_psrli_w:
4853 case Intrinsic::x86_mmx_psrli_d:
4854 case Intrinsic::x86_mmx_psrli_q:
4855 case Intrinsic::x86_mmx_psrai_w:
4856 case Intrinsic::x86_mmx_psrai_d: {
4857 SDValue ShAmt = getValue(I.getArgOperand(1));
4858 if (isa<ConstantSDNode>(ShAmt)) {
4859 visitTargetIntrinsic(I, Intrinsic);
4862 unsigned NewIntrinsic = 0;
4863 EVT ShAmtVT = MVT::v2i32;
4864 switch (Intrinsic) {
4865 case Intrinsic::x86_mmx_pslli_w:
4866 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4868 case Intrinsic::x86_mmx_pslli_d:
4869 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4871 case Intrinsic::x86_mmx_pslli_q:
4872 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4874 case Intrinsic::x86_mmx_psrli_w:
4875 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4877 case Intrinsic::x86_mmx_psrli_d:
4878 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4880 case Intrinsic::x86_mmx_psrli_q:
4881 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4883 case Intrinsic::x86_mmx_psrai_w:
4884 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4886 case Intrinsic::x86_mmx_psrai_d:
4887 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4889 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4892 // The vector shift intrinsics with scalars uses 32b shift amounts but
4893 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4895 // We must do this early because v2i32 is not a legal type.
4898 ShOps[1] = DAG.getConstant(0, MVT::i32);
4899 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
4900 EVT DestVT = TLI->getValueType(I.getType());
4901 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4902 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4903 DAG.getConstant(NewIntrinsic, MVT::i32),
4904 getValue(I.getArgOperand(0)), ShAmt);
4908 case Intrinsic::x86_avx_vinsertf128_pd_256:
4909 case Intrinsic::x86_avx_vinsertf128_ps_256:
4910 case Intrinsic::x86_avx_vinsertf128_si_256:
4911 case Intrinsic::x86_avx2_vinserti128: {
4912 EVT DestVT = TLI->getValueType(I.getType());
4913 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
4914 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4915 ElVT.getVectorNumElements();
4916 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
4917 getValue(I.getArgOperand(0)),
4918 getValue(I.getArgOperand(1)),
4919 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
4923 case Intrinsic::x86_avx_vextractf128_pd_256:
4924 case Intrinsic::x86_avx_vextractf128_ps_256:
4925 case Intrinsic::x86_avx_vextractf128_si_256:
4926 case Intrinsic::x86_avx2_vextracti128: {
4927 EVT DestVT = TLI->getValueType(I.getType());
4928 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4929 DestVT.getVectorNumElements();
4930 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
4931 getValue(I.getArgOperand(0)),
4932 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
4936 case Intrinsic::convertff:
4937 case Intrinsic::convertfsi:
4938 case Intrinsic::convertfui:
4939 case Intrinsic::convertsif:
4940 case Intrinsic::convertuif:
4941 case Intrinsic::convertss:
4942 case Intrinsic::convertsu:
4943 case Intrinsic::convertus:
4944 case Intrinsic::convertuu: {
4945 ISD::CvtCode Code = ISD::CVT_INVALID;
4946 switch (Intrinsic) {
4947 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4948 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4949 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4950 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4951 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4952 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4953 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4954 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4955 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4956 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4958 EVT DestVT = TLI->getValueType(I.getType());
4959 const Value *Op1 = I.getArgOperand(0);
4960 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4961 DAG.getValueType(DestVT),
4962 DAG.getValueType(getValue(Op1).getValueType()),
4963 getValue(I.getArgOperand(1)),
4964 getValue(I.getArgOperand(2)),
4969 case Intrinsic::powi:
4970 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4971 getValue(I.getArgOperand(1)), DAG));
4973 case Intrinsic::log:
4974 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4976 case Intrinsic::log2:
4977 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4979 case Intrinsic::log10:
4980 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4982 case Intrinsic::exp:
4983 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4985 case Intrinsic::exp2:
4986 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4988 case Intrinsic::pow:
4989 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4990 getValue(I.getArgOperand(1)), DAG, *TLI));
4992 case Intrinsic::sqrt:
4993 case Intrinsic::fabs:
4994 case Intrinsic::sin:
4995 case Intrinsic::cos:
4996 case Intrinsic::floor:
4997 case Intrinsic::ceil:
4998 case Intrinsic::trunc:
4999 case Intrinsic::rint:
5000 case Intrinsic::nearbyint:
5001 case Intrinsic::round: {
5003 switch (Intrinsic) {
5004 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5005 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5006 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5007 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5008 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5009 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5010 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5011 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5012 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5013 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5014 case Intrinsic::round: Opcode = ISD::FROUND; break;
5017 setValue(&I, DAG.getNode(Opcode, sdl,
5018 getValue(I.getArgOperand(0)).getValueType(),
5019 getValue(I.getArgOperand(0))));
5022 case Intrinsic::copysign:
5023 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5024 getValue(I.getArgOperand(0)).getValueType(),
5025 getValue(I.getArgOperand(0)),
5026 getValue(I.getArgOperand(1))));
5028 case Intrinsic::fma:
5029 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5030 getValue(I.getArgOperand(0)).getValueType(),
5031 getValue(I.getArgOperand(0)),
5032 getValue(I.getArgOperand(1)),
5033 getValue(I.getArgOperand(2))));
5035 case Intrinsic::fmuladd: {
5036 EVT VT = TLI->getValueType(I.getType());
5037 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5038 TLI->isFMAFasterThanFMulAndFAdd(VT)) {
5039 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5040 getValue(I.getArgOperand(0)).getValueType(),
5041 getValue(I.getArgOperand(0)),
5042 getValue(I.getArgOperand(1)),
5043 getValue(I.getArgOperand(2))));
5045 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5046 getValue(I.getArgOperand(0)).getValueType(),
5047 getValue(I.getArgOperand(0)),
5048 getValue(I.getArgOperand(1)));
5049 SDValue Add = DAG.getNode(ISD::FADD, sdl,
5050 getValue(I.getArgOperand(0)).getValueType(),
5052 getValue(I.getArgOperand(2)));
5057 case Intrinsic::convert_to_fp16:
5058 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
5059 MVT::i16, getValue(I.getArgOperand(0))));
5061 case Intrinsic::convert_from_fp16:
5062 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
5063 MVT::f32, getValue(I.getArgOperand(0))));
5065 case Intrinsic::pcmarker: {
5066 SDValue Tmp = getValue(I.getArgOperand(0));
5067 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5070 case Intrinsic::readcyclecounter: {
5071 SDValue Op = getRoot();
5072 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5073 DAG.getVTList(MVT::i64, MVT::Other),
5076 DAG.setRoot(Res.getValue(1));
5079 case Intrinsic::bswap:
5080 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5081 getValue(I.getArgOperand(0)).getValueType(),
5082 getValue(I.getArgOperand(0))));
5084 case Intrinsic::cttz: {
5085 SDValue Arg = getValue(I.getArgOperand(0));
5086 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5087 EVT Ty = Arg.getValueType();
5088 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5092 case Intrinsic::ctlz: {
5093 SDValue Arg = getValue(I.getArgOperand(0));
5094 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5095 EVT Ty = Arg.getValueType();
5096 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5100 case Intrinsic::ctpop: {
5101 SDValue Arg = getValue(I.getArgOperand(0));
5102 EVT Ty = Arg.getValueType();
5103 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5106 case Intrinsic::stacksave: {
5107 SDValue Op = getRoot();
5108 Res = DAG.getNode(ISD::STACKSAVE, sdl,
5109 DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
5111 DAG.setRoot(Res.getValue(1));
5114 case Intrinsic::stackrestore: {
5115 Res = getValue(I.getArgOperand(0));
5116 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5119 case Intrinsic::stackprotector: {
5120 // Emit code into the DAG to store the stack guard onto the stack.
5121 MachineFunction &MF = DAG.getMachineFunction();
5122 MachineFrameInfo *MFI = MF.getFrameInfo();
5123 EVT PtrTy = TLI->getPointerTy();
5125 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5126 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5128 int FI = FuncInfo.StaticAllocaMap[Slot];
5129 MFI->setStackProtectorIndex(FI);
5131 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5133 // Store the stack protector onto the stack.
5134 Res = DAG.getStore(getRoot(), sdl, Src, FIN,
5135 MachinePointerInfo::getFixedStack(FI),
5141 case Intrinsic::objectsize: {
5142 // If we don't know by now, we're never going to know.
5143 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5145 assert(CI && "Non-constant type in __builtin_object_size?");
5147 SDValue Arg = getValue(I.getCalledValue());
5148 EVT Ty = Arg.getValueType();
5151 Res = DAG.getConstant(-1ULL, Ty);
5153 Res = DAG.getConstant(0, Ty);
5158 case Intrinsic::annotation:
5159 case Intrinsic::ptr_annotation:
5160 // Drop the intrinsic, but forward the value
5161 setValue(&I, getValue(I.getOperand(0)));
5163 case Intrinsic::var_annotation:
5164 // Discard annotate attributes
5167 case Intrinsic::init_trampoline: {
5168 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5172 Ops[1] = getValue(I.getArgOperand(0));
5173 Ops[2] = getValue(I.getArgOperand(1));
5174 Ops[3] = getValue(I.getArgOperand(2));
5175 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5176 Ops[5] = DAG.getSrcValue(F);
5178 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
5183 case Intrinsic::adjust_trampoline: {
5184 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5185 TLI->getPointerTy(),
5186 getValue(I.getArgOperand(0))));
5189 case Intrinsic::gcroot:
5191 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5192 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5194 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5195 GFI->addStackRoot(FI->getIndex(), TypeMap);
5198 case Intrinsic::gcread:
5199 case Intrinsic::gcwrite:
5200 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5201 case Intrinsic::flt_rounds:
5202 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5205 case Intrinsic::expect: {
5206 // Just replace __builtin_expect(exp, c) with EXP.
5207 setValue(&I, getValue(I.getArgOperand(0)));
5211 case Intrinsic::debugtrap:
5212 case Intrinsic::trap: {
5213 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5214 if (TrapFuncName.empty()) {
5215 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5216 ISD::TRAP : ISD::DEBUGTRAP;
5217 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5220 TargetLowering::ArgListTy Args;
5222 CallLoweringInfo CLI(getRoot(), I.getType(),
5223 false, false, false, false, 0, CallingConv::C,
5224 /*isTailCall=*/false,
5225 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
5226 DAG.getExternalSymbol(TrapFuncName.data(),
5227 TLI->getPointerTy()),
5229 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
5230 DAG.setRoot(Result.second);
5234 case Intrinsic::uadd_with_overflow:
5235 case Intrinsic::sadd_with_overflow:
5236 case Intrinsic::usub_with_overflow:
5237 case Intrinsic::ssub_with_overflow:
5238 case Intrinsic::umul_with_overflow:
5239 case Intrinsic::smul_with_overflow: {
5241 switch (Intrinsic) {
5242 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5243 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5244 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5245 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5246 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5247 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5248 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5250 SDValue Op1 = getValue(I.getArgOperand(0));
5251 SDValue Op2 = getValue(I.getArgOperand(1));
5253 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5254 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5257 case Intrinsic::prefetch: {
5259 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5261 Ops[1] = getValue(I.getArgOperand(0));
5262 Ops[2] = getValue(I.getArgOperand(1));
5263 Ops[3] = getValue(I.getArgOperand(2));
5264 Ops[4] = getValue(I.getArgOperand(3));
5265 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5266 DAG.getVTList(MVT::Other),
5268 EVT::getIntegerVT(*Context, 8),
5269 MachinePointerInfo(I.getArgOperand(0)),
5271 false, /* volatile */
5273 rw==1)); /* write */
5276 case Intrinsic::lifetime_start:
5277 case Intrinsic::lifetime_end: {
5278 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5279 // Stack coloring is not enabled in O0, discard region information.
5280 if (TM.getOptLevel() == CodeGenOpt::None)
5283 SmallVector<Value *, 4> Allocas;
5284 GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD);
5286 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5287 E = Allocas.end(); Object != E; ++Object) {
5288 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5290 // Could not find an Alloca.
5291 if (!LifetimeObject)
5294 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5298 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
5299 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5301 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
5306 case Intrinsic::invariant_start:
5307 // Discard region information.
5308 setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
5310 case Intrinsic::invariant_end:
5311 // Discard region information.
5313 case Intrinsic::stackprotectorcheck: {
5314 // Do not actually emit anything for this basic block. Instead we initialize
5315 // the stack protector descriptor and export the guard variable so we can
5316 // access it in FinishBasicBlock.
5317 const BasicBlock *BB = I.getParent();
5318 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5319 ExportFromCurrentBlock(SPDescriptor.getGuard());
5321 // Flush our exports since we are going to process a terminator.
5322 (void)getControlRoot();
5325 case Intrinsic::donothing:
5328 case Intrinsic::experimental_stackmap: {
5332 case Intrinsic::experimental_patchpoint_void:
5333 case Intrinsic::experimental_patchpoint_i64: {
5340 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5342 MachineBasicBlock *LandingPad) {
5343 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5344 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5345 Type *RetTy = FTy->getReturnType();
5346 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5347 MCSymbol *BeginLabel = 0;
5349 TargetLowering::ArgListTy Args;
5350 TargetLowering::ArgListEntry Entry;
5351 Args.reserve(CS.arg_size());
5353 // Check whether the function can return without sret-demotion.
5354 SmallVector<ISD::OutputArg, 4> Outs;
5355 const TargetLowering *TLI = TM.getTargetLowering();
5356 GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
5358 bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
5359 DAG.getMachineFunction(),
5360 FTy->isVarArg(), Outs,
5363 SDValue DemoteStackSlot;
5364 int DemoteStackIdx = -100;
5366 if (!CanLowerReturn) {
5367 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
5368 FTy->getReturnType());
5369 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(
5370 FTy->getReturnType());
5371 MachineFunction &MF = DAG.getMachineFunction();
5372 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5373 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
5375 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
5376 Entry.Node = DemoteStackSlot;
5377 Entry.Ty = StackSlotPtrType;
5378 Entry.isSExt = false;
5379 Entry.isZExt = false;
5380 Entry.isInReg = false;
5381 Entry.isSRet = true;
5382 Entry.isNest = false;
5383 Entry.isByVal = false;
5384 Entry.isReturned = false;
5385 Entry.Alignment = Align;
5386 Args.push_back(Entry);
5387 RetTy = Type::getVoidTy(FTy->getContext());
5390 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5392 const Value *V = *i;
5395 if (V->getType()->isEmptyTy())
5398 SDValue ArgNode = getValue(V);
5399 Entry.Node = ArgNode; Entry.Ty = V->getType();
5401 // Skip the first return-type Attribute to get to params.
5402 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5403 Args.push_back(Entry);
5407 // Insert a label before the invoke call to mark the try range. This can be
5408 // used to detect deletion of the invoke via the MachineModuleInfo.
5409 BeginLabel = MMI.getContext().CreateTempSymbol();
5411 // For SjLj, keep track of which landing pads go with which invokes
5412 // so as to maintain the ordering of pads in the LSDA.
5413 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5414 if (CallSiteIndex) {
5415 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5416 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5418 // Now that the call site is handled, stop tracking it.
5419 MMI.setCurrentCallSite(0);
5422 // Both PendingLoads and PendingExports must be flushed here;
5423 // this call might not return.
5425 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5428 // Check if target-independent constraints permit a tail call here.
5429 // Target-dependent constraints are checked within TLI->LowerCallTo.
5430 if (isTailCall && !isInTailCallPosition(CS, *TLI))
5434 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
5436 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
5437 assert((isTailCall || Result.second.getNode()) &&
5438 "Non-null chain expected with non-tail call!");
5439 assert((Result.second.getNode() || !Result.first.getNode()) &&
5440 "Null value expected with tail call!");
5441 if (Result.first.getNode()) {
5442 setValue(CS.getInstruction(), Result.first);
5443 } else if (!CanLowerReturn && Result.second.getNode()) {
5444 // The instruction result is the result of loading from the
5445 // hidden sret parameter.
5446 SmallVector<EVT, 1> PVTs;
5447 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5449 ComputeValueVTs(*TLI, PtrRetTy, PVTs);
5450 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5451 EVT PtrVT = PVTs[0];
5453 SmallVector<EVT, 4> RetTys;
5454 SmallVector<uint64_t, 4> Offsets;
5455 RetTy = FTy->getReturnType();
5456 ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
5458 unsigned NumValues = RetTys.size();
5459 SmallVector<SDValue, 4> Values(NumValues);
5460 SmallVector<SDValue, 4> Chains(NumValues);
5462 for (unsigned i = 0; i < NumValues; ++i) {
5463 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
5465 DAG.getConstant(Offsets[i], PtrVT));
5466 SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
5467 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5468 false, false, false, 1);
5470 Chains[i] = L.getValue(1);
5473 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
5474 MVT::Other, &Chains[0], NumValues);
5475 PendingLoads.push_back(Chain);
5477 setValue(CS.getInstruction(),
5478 DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
5479 DAG.getVTList(&RetTys[0], RetTys.size()),
5480 &Values[0], Values.size()));
5483 if (!Result.second.getNode()) {
5484 // As a special case, a null chain means that a tail call has been emitted
5485 // and the DAG root is already updated.
5488 // Since there's no actual continuation from this block, nothing can be
5489 // relying on us setting vregs for them.
5490 PendingExports.clear();
5492 DAG.setRoot(Result.second);
5496 // Insert a label at the end of the invoke call to mark the try range. This
5497 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5498 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5499 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5501 // Inform MachineModuleInfo of range.
5502 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5506 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5507 /// value is equal or not-equal to zero.
5508 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5509 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5511 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5512 if (IC->isEquality())
5513 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5514 if (C->isNullValue())
5516 // Unknown instruction.
5522 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5524 SelectionDAGBuilder &Builder) {
5526 // Check to see if this load can be trivially constant folded, e.g. if the
5527 // input is from a string literal.
5528 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5529 // Cast pointer to the type we really want to load.
5530 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5531 PointerType::getUnqual(LoadTy));
5533 if (const Constant *LoadCst =
5534 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5536 return Builder.getValue(LoadCst);
5539 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5540 // still constant memory, the input chain can be the entry node.
5542 bool ConstantMemory = false;
5544 // Do not serialize (non-volatile) loads of constant memory with anything.
5545 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5546 Root = Builder.DAG.getEntryNode();
5547 ConstantMemory = true;
5549 // Do not serialize non-volatile loads against each other.
5550 Root = Builder.DAG.getRoot();
5553 SDValue Ptr = Builder.getValue(PtrVal);
5554 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5555 Ptr, MachinePointerInfo(PtrVal),
5557 false /*nontemporal*/,
5558 false /*isinvariant*/, 1 /* align=1 */);
5560 if (!ConstantMemory)
5561 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5565 /// processIntegerCallValue - Record the value for an instruction that
5566 /// produces an integer result, converting the type where necessary.
5567 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5570 EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
5572 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5574 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5575 setValue(&I, Value);
5578 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5579 /// If so, return true and lower it, otherwise return false and it will be
5580 /// lowered like a normal call.
5581 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5582 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5583 if (I.getNumArgOperands() != 3)
5586 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5587 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5588 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5589 !I.getType()->isIntegerTy())
5592 const Value *Size = I.getArgOperand(2);
5593 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5594 if (CSize && CSize->getZExtValue() == 0) {
5595 EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
5596 setValue(&I, DAG.getConstant(0, CallVT));
5600 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5601 std::pair<SDValue, SDValue> Res =
5602 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5603 getValue(LHS), getValue(RHS), getValue(Size),
5604 MachinePointerInfo(LHS),
5605 MachinePointerInfo(RHS));
5606 if (Res.first.getNode()) {
5607 processIntegerCallValue(I, Res.first, true);
5608 PendingLoads.push_back(Res.second);
5612 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5613 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5614 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5615 bool ActuallyDoIt = true;
5618 switch (CSize->getZExtValue()) {
5620 LoadVT = MVT::Other;
5622 ActuallyDoIt = false;
5626 LoadTy = Type::getInt16Ty(CSize->getContext());
5630 LoadTy = Type::getInt32Ty(CSize->getContext());
5634 LoadTy = Type::getInt64Ty(CSize->getContext());
5638 LoadVT = MVT::v4i32;
5639 LoadTy = Type::getInt32Ty(CSize->getContext());
5640 LoadTy = VectorType::get(LoadTy, 4);
5645 // This turns into unaligned loads. We only do this if the target natively
5646 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5647 // we'll only produce a small number of byte loads.
5649 // Require that we can find a legal MVT, and only do this if the target
5650 // supports unaligned loads of that type. Expanding into byte loads would
5652 const TargetLowering *TLI = TM.getTargetLowering();
5653 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5654 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5655 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5656 if (!TLI->isTypeLegal(LoadVT) ||!TLI->allowsUnalignedMemoryAccesses(LoadVT))
5657 ActuallyDoIt = false;
5661 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5662 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5664 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5666 processIntegerCallValue(I, Res, false);
5675 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5676 /// form. If so, return true and lower it, otherwise return false and it
5677 /// will be lowered like a normal call.
5678 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5679 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5680 if (I.getNumArgOperands() != 3)
5683 const Value *Src = I.getArgOperand(0);
5684 const Value *Char = I.getArgOperand(1);
5685 const Value *Length = I.getArgOperand(2);
5686 if (!Src->getType()->isPointerTy() ||
5687 !Char->getType()->isIntegerTy() ||
5688 !Length->getType()->isIntegerTy() ||
5689 !I.getType()->isPointerTy())
5692 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5693 std::pair<SDValue, SDValue> Res =
5694 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5695 getValue(Src), getValue(Char), getValue(Length),
5696 MachinePointerInfo(Src));
5697 if (Res.first.getNode()) {
5698 setValue(&I, Res.first);
5699 PendingLoads.push_back(Res.second);
5706 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5707 /// optimized form. If so, return true and lower it, otherwise return false
5708 /// and it will be lowered like a normal call.
5709 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5710 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5711 if (I.getNumArgOperands() != 2)
5714 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5715 if (!Arg0->getType()->isPointerTy() ||
5716 !Arg1->getType()->isPointerTy() ||
5717 !I.getType()->isPointerTy())
5720 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5721 std::pair<SDValue, SDValue> Res =
5722 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5723 getValue(Arg0), getValue(Arg1),
5724 MachinePointerInfo(Arg0),
5725 MachinePointerInfo(Arg1), isStpcpy);
5726 if (Res.first.getNode()) {
5727 setValue(&I, Res.first);
5728 DAG.setRoot(Res.second);
5735 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5736 /// If so, return true and lower it, otherwise return false and it will be
5737 /// lowered like a normal call.
5738 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5739 // Verify that the prototype makes sense. int strcmp(void*,void*)
5740 if (I.getNumArgOperands() != 2)
5743 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5744 if (!Arg0->getType()->isPointerTy() ||
5745 !Arg1->getType()->isPointerTy() ||
5746 !I.getType()->isIntegerTy())
5749 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5750 std::pair<SDValue, SDValue> Res =
5751 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5752 getValue(Arg0), getValue(Arg1),
5753 MachinePointerInfo(Arg0),
5754 MachinePointerInfo(Arg1));
5755 if (Res.first.getNode()) {
5756 processIntegerCallValue(I, Res.first, true);
5757 PendingLoads.push_back(Res.second);
5764 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5765 /// form. If so, return true and lower it, otherwise return false and it
5766 /// will be lowered like a normal call.
5767 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5768 // Verify that the prototype makes sense. size_t strlen(char *)
5769 if (I.getNumArgOperands() != 1)
5772 const Value *Arg0 = I.getArgOperand(0);
5773 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5776 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5777 std::pair<SDValue, SDValue> Res =
5778 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5779 getValue(Arg0), MachinePointerInfo(Arg0));
5780 if (Res.first.getNode()) {
5781 processIntegerCallValue(I, Res.first, false);
5782 PendingLoads.push_back(Res.second);
5789 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5790 /// form. If so, return true and lower it, otherwise return false and it
5791 /// will be lowered like a normal call.
5792 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5793 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5794 if (I.getNumArgOperands() != 2)
5797 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5798 if (!Arg0->getType()->isPointerTy() ||
5799 !Arg1->getType()->isIntegerTy() ||
5800 !I.getType()->isIntegerTy())
5803 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5804 std::pair<SDValue, SDValue> Res =
5805 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5806 getValue(Arg0), getValue(Arg1),
5807 MachinePointerInfo(Arg0));
5808 if (Res.first.getNode()) {
5809 processIntegerCallValue(I, Res.first, false);
5810 PendingLoads.push_back(Res.second);
5817 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5818 /// operation (as expected), translate it to an SDNode with the specified opcode
5819 /// and return true.
5820 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5822 // Sanity check that it really is a unary floating-point call.
5823 if (I.getNumArgOperands() != 1 ||
5824 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5825 I.getType() != I.getArgOperand(0)->getType() ||
5826 !I.onlyReadsMemory())
5829 SDValue Tmp = getValue(I.getArgOperand(0));
5830 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5834 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5835 // Handle inline assembly differently.
5836 if (isa<InlineAsm>(I.getCalledValue())) {
5841 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5842 ComputeUsesVAFloatArgument(I, &MMI);
5844 const char *RenameFn = 0;
5845 if (Function *F = I.getCalledFunction()) {
5846 if (F->isDeclaration()) {
5847 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5848 if (unsigned IID = II->getIntrinsicID(F)) {
5849 RenameFn = visitIntrinsicCall(I, IID);
5854 if (unsigned IID = F->getIntrinsicID()) {
5855 RenameFn = visitIntrinsicCall(I, IID);
5861 // Check for well-known libc/libm calls. If the function is internal, it
5862 // can't be a library call.
5864 if (!F->hasLocalLinkage() && F->hasName() &&
5865 LibInfo->getLibFunc(F->getName(), Func) &&
5866 LibInfo->hasOptimizedCodeGen(Func)) {
5869 case LibFunc::copysign:
5870 case LibFunc::copysignf:
5871 case LibFunc::copysignl:
5872 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5873 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5874 I.getType() == I.getArgOperand(0)->getType() &&
5875 I.getType() == I.getArgOperand(1)->getType() &&
5876 I.onlyReadsMemory()) {
5877 SDValue LHS = getValue(I.getArgOperand(0));
5878 SDValue RHS = getValue(I.getArgOperand(1));
5879 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5880 LHS.getValueType(), LHS, RHS));
5885 case LibFunc::fabsf:
5886 case LibFunc::fabsl:
5887 if (visitUnaryFloatCall(I, ISD::FABS))
5893 if (visitUnaryFloatCall(I, ISD::FSIN))
5899 if (visitUnaryFloatCall(I, ISD::FCOS))
5903 case LibFunc::sqrtf:
5904 case LibFunc::sqrtl:
5905 case LibFunc::sqrt_finite:
5906 case LibFunc::sqrtf_finite:
5907 case LibFunc::sqrtl_finite:
5908 if (visitUnaryFloatCall(I, ISD::FSQRT))
5911 case LibFunc::floor:
5912 case LibFunc::floorf:
5913 case LibFunc::floorl:
5914 if (visitUnaryFloatCall(I, ISD::FFLOOR))
5917 case LibFunc::nearbyint:
5918 case LibFunc::nearbyintf:
5919 case LibFunc::nearbyintl:
5920 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
5924 case LibFunc::ceilf:
5925 case LibFunc::ceill:
5926 if (visitUnaryFloatCall(I, ISD::FCEIL))
5930 case LibFunc::rintf:
5931 case LibFunc::rintl:
5932 if (visitUnaryFloatCall(I, ISD::FRINT))
5935 case LibFunc::round:
5936 case LibFunc::roundf:
5937 case LibFunc::roundl:
5938 if (visitUnaryFloatCall(I, ISD::FROUND))
5941 case LibFunc::trunc:
5942 case LibFunc::truncf:
5943 case LibFunc::truncl:
5944 if (visitUnaryFloatCall(I, ISD::FTRUNC))
5948 case LibFunc::log2f:
5949 case LibFunc::log2l:
5950 if (visitUnaryFloatCall(I, ISD::FLOG2))
5954 case LibFunc::exp2f:
5955 case LibFunc::exp2l:
5956 if (visitUnaryFloatCall(I, ISD::FEXP2))
5959 case LibFunc::memcmp:
5960 if (visitMemCmpCall(I))
5963 case LibFunc::memchr:
5964 if (visitMemChrCall(I))
5967 case LibFunc::strcpy:
5968 if (visitStrCpyCall(I, false))
5971 case LibFunc::stpcpy:
5972 if (visitStrCpyCall(I, true))
5975 case LibFunc::strcmp:
5976 if (visitStrCmpCall(I))
5979 case LibFunc::strlen:
5980 if (visitStrLenCall(I))
5983 case LibFunc::strnlen:
5984 if (visitStrNLenCall(I))
5993 Callee = getValue(I.getCalledValue());
5995 Callee = DAG.getExternalSymbol(RenameFn,
5996 TM.getTargetLowering()->getPointerTy());
5998 // Check if we can potentially perform a tail call. More detailed checking is
5999 // be done within LowerCallTo, after more information about the call is known.
6000 LowerCallTo(&I, Callee, I.isTailCall());
6005 /// AsmOperandInfo - This contains information for each constraint that we are
6007 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6009 /// CallOperand - If this is the result output operand or a clobber
6010 /// this is null, otherwise it is the incoming operand to the CallInst.
6011 /// This gets modified as the asm is processed.
6012 SDValue CallOperand;
6014 /// AssignedRegs - If this is a register or register class operand, this
6015 /// contains the set of register corresponding to the operand.
6016 RegsForValue AssignedRegs;
6018 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6019 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
6022 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6023 /// corresponds to. If there is no Value* for this operand, it returns
6025 EVT getCallOperandValEVT(LLVMContext &Context,
6026 const TargetLowering &TLI,
6027 const DataLayout *TD) const {
6028 if (CallOperandVal == 0) return MVT::Other;
6030 if (isa<BasicBlock>(CallOperandVal))
6031 return TLI.getPointerTy();
6033 llvm::Type *OpTy = CallOperandVal->getType();
6035 // FIXME: code duplicated from TargetLowering::ParseConstraints().
6036 // If this is an indirect operand, the operand is a pointer to the
6039 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6041 report_fatal_error("Indirect operand for inline asm not a pointer!");
6042 OpTy = PtrTy->getElementType();
6045 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6046 if (StructType *STy = dyn_cast<StructType>(OpTy))
6047 if (STy->getNumElements() == 1)
6048 OpTy = STy->getElementType(0);
6050 // If OpTy is not a single value, it may be a struct/union that we
6051 // can tile with integers.
6052 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6053 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
6062 OpTy = IntegerType::get(Context, BitSize);
6067 return TLI.getValueType(OpTy, true);
6071 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6073 } // end anonymous namespace
6075 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6076 /// specified operand. We prefer to assign virtual registers, to allow the
6077 /// register allocator to handle the assignment process. However, if the asm
6078 /// uses features that we can't model on machineinstrs, we have SDISel do the
6079 /// allocation. This produces generally horrible, but correct, code.
6081 /// OpInfo describes the operand.
6083 static void GetRegistersForValue(SelectionDAG &DAG,
6084 const TargetLowering &TLI,
6086 SDISelAsmOperandInfo &OpInfo) {
6087 LLVMContext &Context = *DAG.getContext();
6089 MachineFunction &MF = DAG.getMachineFunction();
6090 SmallVector<unsigned, 4> Regs;
6092 // If this is a constraint for a single physreg, or a constraint for a
6093 // register class, find it.
6094 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
6095 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6096 OpInfo.ConstraintVT);
6098 unsigned NumRegs = 1;
6099 if (OpInfo.ConstraintVT != MVT::Other) {
6100 // If this is a FP input in an integer register (or visa versa) insert a bit
6101 // cast of the input value. More generally, handle any case where the input
6102 // value disagrees with the register class we plan to stick this in.
6103 if (OpInfo.Type == InlineAsm::isInput &&
6104 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6105 // Try to convert to the first EVT that the reg class contains. If the
6106 // types are identical size, use a bitcast to convert (e.g. two differing
6108 MVT RegVT = *PhysReg.second->vt_begin();
6109 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
6110 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6111 RegVT, OpInfo.CallOperand);
6112 OpInfo.ConstraintVT = RegVT;
6113 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6114 // If the input is a FP value and we want it in FP registers, do a
6115 // bitcast to the corresponding integer type. This turns an f64 value
6116 // into i64, which can be passed with two i32 values on a 32-bit
6118 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6119 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6120 RegVT, OpInfo.CallOperand);
6121 OpInfo.ConstraintVT = RegVT;
6125 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6129 EVT ValueVT = OpInfo.ConstraintVT;
6131 // If this is a constraint for a specific physical register, like {r17},
6133 if (unsigned AssignedReg = PhysReg.first) {
6134 const TargetRegisterClass *RC = PhysReg.second;
6135 if (OpInfo.ConstraintVT == MVT::Other)
6136 ValueVT = *RC->vt_begin();
6138 // Get the actual register value type. This is important, because the user
6139 // may have asked for (e.g.) the AX register in i32 type. We need to
6140 // remember that AX is actually i16 to get the right extension.
6141 RegVT = *RC->vt_begin();
6143 // This is a explicit reference to a physical register.
6144 Regs.push_back(AssignedReg);
6146 // If this is an expanded reference, add the rest of the regs to Regs.
6148 TargetRegisterClass::iterator I = RC->begin();
6149 for (; *I != AssignedReg; ++I)
6150 assert(I != RC->end() && "Didn't find reg!");
6152 // Already added the first reg.
6154 for (; NumRegs; --NumRegs, ++I) {
6155 assert(I != RC->end() && "Ran out of registers to allocate!");
6160 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6164 // Otherwise, if this was a reference to an LLVM register class, create vregs
6165 // for this reference.
6166 if (const TargetRegisterClass *RC = PhysReg.second) {
6167 RegVT = *RC->vt_begin();
6168 if (OpInfo.ConstraintVT == MVT::Other)
6171 // Create the appropriate number of virtual registers.
6172 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6173 for (; NumRegs; --NumRegs)
6174 Regs.push_back(RegInfo.createVirtualRegister(RC));
6176 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6180 // Otherwise, we couldn't allocate enough registers for this.
6183 /// visitInlineAsm - Handle a call to an InlineAsm object.
6185 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6186 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6188 /// ConstraintOperands - Information about all of the constraints.
6189 SDISelAsmOperandInfoVector ConstraintOperands;
6191 const TargetLowering *TLI = TM.getTargetLowering();
6192 TargetLowering::AsmOperandInfoVector
6193 TargetConstraints = TLI->ParseConstraints(CS);
6195 bool hasMemory = false;
6197 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6198 unsigned ResNo = 0; // ResNo - The result number of the next output.
6199 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6200 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6201 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6203 MVT OpVT = MVT::Other;
6205 // Compute the value type for each operand.
6206 switch (OpInfo.Type) {
6207 case InlineAsm::isOutput:
6208 // Indirect outputs just consume an argument.
6209 if (OpInfo.isIndirect) {
6210 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6214 // The return value of the call is this value. As such, there is no
6215 // corresponding argument.
6216 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6217 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6218 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
6220 assert(ResNo == 0 && "Asm only has one result!");
6221 OpVT = TLI->getSimpleValueType(CS.getType());
6225 case InlineAsm::isInput:
6226 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6228 case InlineAsm::isClobber:
6233 // If this is an input or an indirect output, process the call argument.
6234 // BasicBlocks are labels, currently appearing only in asm's.
6235 if (OpInfo.CallOperandVal) {
6236 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6237 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6239 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6242 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, TD).
6246 OpInfo.ConstraintVT = OpVT;
6248 // Indirect operand accesses access memory.
6249 if (OpInfo.isIndirect)
6252 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6253 TargetLowering::ConstraintType
6254 CType = TLI->getConstraintType(OpInfo.Codes[j]);
6255 if (CType == TargetLowering::C_Memory) {
6263 SDValue Chain, Flag;
6265 // We won't need to flush pending loads if this asm doesn't touch
6266 // memory and is nonvolatile.
6267 if (hasMemory || IA->hasSideEffects())
6270 Chain = DAG.getRoot();
6272 // Second pass over the constraints: compute which constraint option to use
6273 // and assign registers to constraints that want a specific physreg.
6274 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6275 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6277 // If this is an output operand with a matching input operand, look up the
6278 // matching input. If their types mismatch, e.g. one is an integer, the
6279 // other is floating point, or their sizes are different, flag it as an
6281 if (OpInfo.hasMatchingInput()) {
6282 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6284 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6285 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6286 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6287 OpInfo.ConstraintVT);
6288 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6289 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
6290 Input.ConstraintVT);
6291 if ((OpInfo.ConstraintVT.isInteger() !=
6292 Input.ConstraintVT.isInteger()) ||
6293 (MatchRC.second != InputRC.second)) {
6294 report_fatal_error("Unsupported asm: input constraint"
6295 " with a matching output constraint of"
6296 " incompatible type!");
6298 Input.ConstraintVT = OpInfo.ConstraintVT;
6302 // Compute the constraint code and ConstraintType to use.
6303 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6305 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6306 OpInfo.Type == InlineAsm::isClobber)
6309 // If this is a memory input, and if the operand is not indirect, do what we
6310 // need to to provide an address for the memory input.
6311 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6312 !OpInfo.isIndirect) {
6313 assert((OpInfo.isMultipleAlternative ||
6314 (OpInfo.Type == InlineAsm::isInput)) &&
6315 "Can only indirectify direct input operands!");
6317 // Memory operands really want the address of the value. If we don't have
6318 // an indirect input, put it in the constpool if we can, otherwise spill
6319 // it to a stack slot.
6320 // TODO: This isn't quite right. We need to handle these according to
6321 // the addressing mode that the constraint wants. Also, this may take
6322 // an additional register for the computation and we don't want that
6325 // If the operand is a float, integer, or vector constant, spill to a
6326 // constant pool entry to get its address.
6327 const Value *OpVal = OpInfo.CallOperandVal;
6328 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6329 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6330 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6331 TLI->getPointerTy());
6333 // Otherwise, create a stack slot and emit a store to it before the
6335 Type *Ty = OpVal->getType();
6336 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
6337 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
6338 MachineFunction &MF = DAG.getMachineFunction();
6339 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6340 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
6341 Chain = DAG.getStore(Chain, getCurSDLoc(),
6342 OpInfo.CallOperand, StackSlot,
6343 MachinePointerInfo::getFixedStack(SSFI),
6345 OpInfo.CallOperand = StackSlot;
6348 // There is no longer a Value* corresponding to this operand.
6349 OpInfo.CallOperandVal = 0;
6351 // It is now an indirect operand.
6352 OpInfo.isIndirect = true;
6355 // If this constraint is for a specific register, allocate it before
6357 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6358 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6361 // Second pass - Loop over all of the operands, assigning virtual or physregs
6362 // to register class operands.
6363 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6364 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6366 // C_Register operands have already been allocated, Other/Memory don't need
6368 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6369 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6372 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6373 std::vector<SDValue> AsmNodeOperands;
6374 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6375 AsmNodeOperands.push_back(
6376 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6377 TLI->getPointerTy()));
6379 // If we have a !srcloc metadata node associated with it, we want to attach
6380 // this to the ultimately generated inline asm machineinstr. To do this, we
6381 // pass in the third operand as this (potentially null) inline asm MDNode.
6382 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6383 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6385 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6386 // bits as operand 3.
6387 unsigned ExtraInfo = 0;
6388 if (IA->hasSideEffects())
6389 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6390 if (IA->isAlignStack())
6391 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6392 // Set the asm dialect.
6393 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6395 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6396 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6397 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6399 // Compute the constraint code and ConstraintType to use.
6400 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6402 // Ideally, we would only check against memory constraints. However, the
6403 // meaning of an other constraint can be target-specific and we can't easily
6404 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6405 // for other constriants as well.
6406 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6407 OpInfo.ConstraintType == TargetLowering::C_Other) {
6408 if (OpInfo.Type == InlineAsm::isInput)
6409 ExtraInfo |= InlineAsm::Extra_MayLoad;
6410 else if (OpInfo.Type == InlineAsm::isOutput)
6411 ExtraInfo |= InlineAsm::Extra_MayStore;
6412 else if (OpInfo.Type == InlineAsm::isClobber)
6413 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6417 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6418 TLI->getPointerTy()));
6420 // Loop over all of the inputs, copying the operand values into the
6421 // appropriate registers and processing the output regs.
6422 RegsForValue RetValRegs;
6424 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6425 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6427 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6428 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6430 switch (OpInfo.Type) {
6431 case InlineAsm::isOutput: {
6432 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6433 OpInfo.ConstraintType != TargetLowering::C_Register) {
6434 // Memory output, or 'other' output (e.g. 'X' constraint).
6435 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6437 // Add information to the INLINEASM node to know about this output.
6438 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6439 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6440 TLI->getPointerTy()));
6441 AsmNodeOperands.push_back(OpInfo.CallOperand);
6445 // Otherwise, this is a register or register class output.
6447 // Copy the output from the appropriate register. Find a register that
6449 if (OpInfo.AssignedRegs.Regs.empty()) {
6450 LLVMContext &Ctx = *DAG.getContext();
6451 Ctx.emitError(CS.getInstruction(),
6452 "couldn't allocate output register for constraint '" +
6453 Twine(OpInfo.ConstraintCode) + "'");
6457 // If this is an indirect operand, store through the pointer after the
6459 if (OpInfo.isIndirect) {
6460 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6461 OpInfo.CallOperandVal));
6463 // This is the result value of the call.
6464 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6465 // Concatenate this output onto the outputs list.
6466 RetValRegs.append(OpInfo.AssignedRegs);
6469 // Add information to the INLINEASM node to know that this register is
6472 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6473 ? InlineAsm::Kind_RegDefEarlyClobber
6474 : InlineAsm::Kind_RegDef,
6475 false, 0, DAG, AsmNodeOperands);
6478 case InlineAsm::isInput: {
6479 SDValue InOperandVal = OpInfo.CallOperand;
6481 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6482 // If this is required to match an output register we have already set,
6483 // just use its register.
6484 unsigned OperandNo = OpInfo.getMatchedOperand();
6486 // Scan until we find the definition we already emitted of this operand.
6487 // When we find it, create a RegsForValue operand.
6488 unsigned CurOp = InlineAsm::Op_FirstOperand;
6489 for (; OperandNo; --OperandNo) {
6490 // Advance to the next operand.
6492 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6493 assert((InlineAsm::isRegDefKind(OpFlag) ||
6494 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6495 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6496 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6500 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6501 if (InlineAsm::isRegDefKind(OpFlag) ||
6502 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6503 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6504 if (OpInfo.isIndirect) {
6505 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6506 LLVMContext &Ctx = *DAG.getContext();
6507 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6508 " don't know how to handle tied "
6509 "indirect register inputs");
6513 RegsForValue MatchedRegs;
6514 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6515 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6516 MatchedRegs.RegVTs.push_back(RegVT);
6517 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6518 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6520 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
6521 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6523 LLVMContext &Ctx = *DAG.getContext();
6524 Ctx.emitError(CS.getInstruction(),
6525 "inline asm error: This value"
6526 " type register class is not natively supported!");
6530 // Use the produced MatchedRegs object to
6531 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6532 Chain, &Flag, CS.getInstruction());
6533 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6534 true, OpInfo.getMatchedOperand(),
6535 DAG, AsmNodeOperands);
6539 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6540 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6541 "Unexpected number of operands");
6542 // Add information to the INLINEASM node to know about this input.
6543 // See InlineAsm.h isUseOperandTiedToDef.
6544 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6545 OpInfo.getMatchedOperand());
6546 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6547 TLI->getPointerTy()));
6548 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6552 // Treat indirect 'X' constraint as memory.
6553 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6555 OpInfo.ConstraintType = TargetLowering::C_Memory;
6557 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6558 std::vector<SDValue> Ops;
6559 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6562 LLVMContext &Ctx = *DAG.getContext();
6563 Ctx.emitError(CS.getInstruction(),
6564 "invalid operand for inline asm constraint '" +
6565 Twine(OpInfo.ConstraintCode) + "'");
6569 // Add information to the INLINEASM node to know about this input.
6570 unsigned ResOpType =
6571 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6572 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6573 TLI->getPointerTy()));
6574 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6578 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6579 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6580 assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
6581 "Memory operands expect pointer values");
6583 // Add information to the INLINEASM node to know about this input.
6584 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6585 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6586 TLI->getPointerTy()));
6587 AsmNodeOperands.push_back(InOperandVal);
6591 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6592 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6593 "Unknown constraint type!");
6595 // TODO: Support this.
6596 if (OpInfo.isIndirect) {
6597 LLVMContext &Ctx = *DAG.getContext();
6598 Ctx.emitError(CS.getInstruction(),
6599 "Don't know how to handle indirect register inputs yet "
6600 "for constraint '" +
6601 Twine(OpInfo.ConstraintCode) + "'");
6605 // Copy the input into the appropriate registers.
6606 if (OpInfo.AssignedRegs.Regs.empty()) {
6607 LLVMContext &Ctx = *DAG.getContext();
6608 Ctx.emitError(CS.getInstruction(),
6609 "couldn't allocate input reg for constraint '" +
6610 Twine(OpInfo.ConstraintCode) + "'");
6614 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6615 Chain, &Flag, CS.getInstruction());
6617 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6618 DAG, AsmNodeOperands);
6621 case InlineAsm::isClobber: {
6622 // Add the clobbered value to the operand list, so that the register
6623 // allocator is aware that the physreg got clobbered.
6624 if (!OpInfo.AssignedRegs.Regs.empty())
6625 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6633 // Finish up input operands. Set the input chain and add the flag last.
6634 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6635 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6637 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6638 DAG.getVTList(MVT::Other, MVT::Glue),
6639 &AsmNodeOperands[0], AsmNodeOperands.size());
6640 Flag = Chain.getValue(1);
6642 // If this asm returns a register value, copy the result from that register
6643 // and set it as the value of the call.
6644 if (!RetValRegs.Regs.empty()) {
6645 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6646 Chain, &Flag, CS.getInstruction());
6648 // FIXME: Why don't we do this for inline asms with MRVs?
6649 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6650 EVT ResultType = TLI->getValueType(CS.getType());
6652 // If any of the results of the inline asm is a vector, it may have the
6653 // wrong width/num elts. This can happen for register classes that can
6654 // contain multiple different value types. The preg or vreg allocated may
6655 // not have the same VT as was expected. Convert it to the right type
6656 // with bit_convert.
6657 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6658 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6661 } else if (ResultType != Val.getValueType() &&
6662 ResultType.isInteger() && Val.getValueType().isInteger()) {
6663 // If a result value was tied to an input value, the computed result may
6664 // have a wider width than the expected result. Extract the relevant
6666 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6669 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6672 setValue(CS.getInstruction(), Val);
6673 // Don't need to use this as a chain in this case.
6674 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6678 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6680 // Process indirect outputs, first output all of the flagged copies out of
6682 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6683 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6684 const Value *Ptr = IndirectStoresToEmit[i].second;
6685 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6687 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6690 // Emit the non-flagged stores from the physregs.
6691 SmallVector<SDValue, 8> OutChains;
6692 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6693 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6694 StoresToEmit[i].first,
6695 getValue(StoresToEmit[i].second),
6696 MachinePointerInfo(StoresToEmit[i].second),
6698 OutChains.push_back(Val);
6701 if (!OutChains.empty())
6702 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
6703 &OutChains[0], OutChains.size());
6708 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6709 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6710 MVT::Other, getRoot(),
6711 getValue(I.getArgOperand(0)),
6712 DAG.getSrcValue(I.getArgOperand(0))));
6715 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6716 const TargetLowering *TLI = TM.getTargetLowering();
6717 const DataLayout &TD = *TLI->getDataLayout();
6718 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
6719 getRoot(), getValue(I.getOperand(0)),
6720 DAG.getSrcValue(I.getOperand(0)),
6721 TD.getABITypeAlignment(I.getType()));
6723 DAG.setRoot(V.getValue(1));
6726 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6727 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6728 MVT::Other, getRoot(),
6729 getValue(I.getArgOperand(0)),
6730 DAG.getSrcValue(I.getArgOperand(0))));
6733 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6734 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6735 MVT::Other, getRoot(),
6736 getValue(I.getArgOperand(0)),
6737 getValue(I.getArgOperand(1)),
6738 DAG.getSrcValue(I.getArgOperand(0)),
6739 DAG.getSrcValue(I.getArgOperand(1))));
6742 /// \brief Lower an argument list according to the target calling convention.
6744 /// \return A tuple of <return-value, token-chain>
6746 /// This is a helper for lowering intrinsics that follow a target calling
6747 /// convention or require stack pointer adjustment. Only a subset of the
6748 /// intrinsic's operands need to participate in the calling convention.
6749 std::pair<SDValue, SDValue>
6750 SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
6751 unsigned NumArgs, SDValue Callee,
6753 TargetLowering::ArgListTy Args;
6754 Args.reserve(NumArgs);
6756 // Populate the argument list.
6757 // Attributes for args start at offset 1, after the return attribute.
6758 ImmutableCallSite CS(&CI);
6759 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6760 ArgI != ArgE; ++ArgI) {
6761 const Value *V = CI.getOperand(ArgI);
6763 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6765 TargetLowering::ArgListEntry Entry;
6766 Entry.Node = getValue(V);
6767 Entry.Ty = V->getType();
6768 Entry.setAttributes(&CS, AttrI);
6769 Args.push_back(Entry);
6772 Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
6773 TargetLowering::CallLoweringInfo CLI(getRoot(), retTy, /*retSExt*/ false,
6774 /*retZExt*/ false, /*isVarArg*/ false, /*isInReg*/ false, NumArgs,
6775 CI.getCallingConv(), /*isTailCall*/ false, /*doesNotReturn*/ false,
6776 /*isReturnValueUsed*/ CI.use_empty(), Callee, Args, DAG, getCurSDLoc());
6778 const TargetLowering *TLI = TM.getTargetLowering();
6779 return TLI->LowerCallTo(CLI);
6782 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6783 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6784 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6785 // [live variables...])
6787 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6789 SDValue Callee = getValue(CI.getCalledValue());
6791 // Lower into a call sequence with no args and no return value.
6792 std::pair<SDValue, SDValue> Result = LowerCallOperands(CI, 0, 0, Callee);
6793 // Set the root to the target-lowered call chain.
6794 SDValue Chain = Result.second;
6797 /// Get a call instruction from the call sequence chain.
6798 /// Tail calls are not allowed.
6799 SDNode *CallEnd = Chain.getNode();
6800 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6801 "Expected a callseq node.");
6802 SDNode *Call = CallEnd->getOperand(0).getNode();
6803 bool hasGlue = Call->getGluedNode();
6805 // Replace the target specific call node with the stackmap intrinsic.
6806 SmallVector<SDValue, 8> Ops;
6808 // Add the <id> and <numShadowBytes> constants.
6809 for (unsigned i = 0; i < 2; ++i) {
6810 SDValue tmp = getValue(CI.getOperand(i));
6811 Ops.push_back(DAG.getTargetConstant(
6812 cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
6814 // Push live variables for the stack map.
6815 for (unsigned i = 2, e = CI.getNumArgOperands(); i != e; ++i)
6816 Ops.push_back(getValue(CI.getArgOperand(i)));
6818 // Push the chain (this is originally the first operand of the call, but
6819 // becomes now the last or second to last operand).
6820 Ops.push_back(*(Call->op_begin()));
6822 // Push the glue flag (last operand).
6824 Ops.push_back(*(Call->op_end()-1));
6826 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6828 // Replace the target specific call node with a STACKMAP node.
6829 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::STACKMAP, getCurSDLoc(),
6832 // StackMap generates no value, so nothing goes in the NodeMap.
6834 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6836 DAG.ReplaceAllUsesWith(Call, MN);
6838 DAG.DeleteNode(Call);
6841 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6842 void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
6843 // void|i64 @llvm.experimental.patchpoint.void|i64(i32 <id>,
6848 // [live variables...])
6850 CallingConv::ID CC = CI.getCallingConv();
6851 bool isAnyRegCC = CC == CallingConv::AnyReg;
6852 bool hasDef = !CI.getType()->isVoidTy();
6853 SDValue Callee = getValue(CI.getOperand(2)); // <target>
6855 // Get the real number of arguments participating in the call <numArgs>
6857 cast<ConstantSDNode>(getValue(CI.getArgOperand(3)))->getZExtValue();
6859 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6860 assert(CI.getNumArgOperands() >= NumArgs + 4 &&
6861 "Not enough arguments provided to the patchpoint intrinsic");
6863 // For AnyRegCC the arguments are lowered later on manually.
6864 unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
6865 std::pair<SDValue, SDValue> Result =
6866 LowerCallOperands(CI, 4, NumCallArgs, Callee, isAnyRegCC);
6868 // Set the root to the target-lowered call chain.
6869 SDValue Chain = Result.second;
6872 SDNode *CallEnd = Chain.getNode();
6873 if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6874 CallEnd = CallEnd->getOperand(0).getNode();
6876 /// Get a call instruction from the call sequence chain.
6877 /// Tail calls are not allowed.
6878 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6879 "Expected a callseq node.");
6880 SDNode *Call = CallEnd->getOperand(0).getNode();
6881 bool hasGlue = Call->getGluedNode();
6883 // Replace the target specific call node with the patchable intrinsic.
6884 SmallVector<SDValue, 8> Ops;
6886 // Add the <id> and <numNopBytes> constants.
6887 for (unsigned i = 0; i < 2; ++i) {
6888 SDValue tmp = getValue(CI.getOperand(i));
6889 Ops.push_back(DAG.getTargetConstant(
6890 cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
6892 // Assume that the Callee is a constant address.
6894 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
6895 /*isTarget=*/true));
6897 // Adjust <numArgs> to account for any arguments that have been passed on the
6899 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
6900 unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
6901 NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
6902 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
6904 // Add the calling convention
6905 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
6907 // Add the arguments we omitted previously. The register allocator should
6908 // place these in any free register.
6910 for (unsigned i = 4, e = NumArgs + 4; i != e; ++i)
6911 Ops.push_back(getValue(CI.getArgOperand(i)));
6913 // Push the arguments from the call instruction.
6914 SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
6915 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
6918 // Push live variables for the stack map.
6919 for (unsigned i = NumArgs + 4, e = CI.getNumArgOperands(); i != e; ++i) {
6920 SDValue OpVal = getValue(CI.getArgOperand(i));
6921 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6923 DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6925 DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
6927 Ops.push_back(OpVal);
6930 // Push the register mask info.
6932 Ops.push_back(*(Call->op_end()-2));
6934 Ops.push_back(*(Call->op_end()-1));
6936 // Push the chain (this is originally the first operand of the call, but
6937 // becomes now the last or second to last operand).
6938 Ops.push_back(*(Call->op_begin()));
6940 // Push the glue flag (last operand).
6942 Ops.push_back(*(Call->op_end()-1));
6945 if (isAnyRegCC && hasDef) {
6946 // Create the return types based on the intrinsic definition
6947 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6948 SmallVector<EVT, 3> ValueVTs;
6949 ComputeValueVTs(TLI, CI.getType(), ValueVTs);
6950 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
6952 // There is always a chain and a glue type at the end
6953 ValueVTs.push_back(MVT::Other);
6954 ValueVTs.push_back(MVT::Glue);
6955 NodeTys = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
6957 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6959 // Replace the target specific call node with a PATCHPOINT node.
6960 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
6961 getCurSDLoc(), NodeTys, Ops);
6963 // Update the NodeMap.
6966 setValue(&CI, SDValue(MN, 0));
6968 setValue(&CI, Result.first);
6971 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6972 // call sequence. Furthermore the location of the chain and glue can change
6973 // when the AnyReg calling convention is used and the intrinsic returns a
6975 if (isAnyRegCC && hasDef) {
6976 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
6977 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
6978 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
6980 DAG.ReplaceAllUsesWith(Call, MN);
6981 DAG.DeleteNode(Call);
6984 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6985 /// implementation, which just calls LowerCall.
6986 /// FIXME: When all targets are
6987 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6988 std::pair<SDValue, SDValue>
6989 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
6990 // Handle the incoming return values from the call.
6992 SmallVector<EVT, 4> RetTys;
6993 ComputeValueVTs(*this, CLI.RetTy, RetTys);
6994 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6996 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6997 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
6998 for (unsigned i = 0; i != NumRegs; ++i) {
6999 ISD::InputArg MyFlags;
7000 MyFlags.VT = RegisterVT;
7002 MyFlags.Used = CLI.IsReturnValueUsed;
7004 MyFlags.Flags.setSExt();
7006 MyFlags.Flags.setZExt();
7008 MyFlags.Flags.setInReg();
7009 CLI.Ins.push_back(MyFlags);
7013 // Handle all of the outgoing arguments.
7015 CLI.OutVals.clear();
7016 ArgListTy &Args = CLI.Args;
7017 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7018 SmallVector<EVT, 4> ValueVTs;
7019 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7020 for (unsigned Value = 0, NumValues = ValueVTs.size();
7021 Value != NumValues; ++Value) {
7022 EVT VT = ValueVTs[Value];
7023 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7024 SDValue Op = SDValue(Args[i].Node.getNode(),
7025 Args[i].Node.getResNo() + Value);
7026 ISD::ArgFlagsTy Flags;
7027 unsigned OriginalAlignment =
7028 getDataLayout()->getABITypeAlignment(ArgTy);
7034 if (Args[i].isInReg)
7038 if (Args[i].isByVal) {
7040 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7041 Type *ElementTy = Ty->getElementType();
7042 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
7043 // For ByVal, alignment should come from FE. BE will guess if this
7044 // info is not there but there are cases it cannot get right.
7045 unsigned FrameAlign;
7046 if (Args[i].Alignment)
7047 FrameAlign = Args[i].Alignment;
7049 FrameAlign = getByValTypeAlignment(ElementTy);
7050 Flags.setByValAlign(FrameAlign);
7054 Flags.setOrigAlign(OriginalAlignment);
7056 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7057 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7058 SmallVector<SDValue, 4> Parts(NumParts);
7059 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7062 ExtendKind = ISD::SIGN_EXTEND;
7063 else if (Args[i].isZExt)
7064 ExtendKind = ISD::ZERO_EXTEND;
7066 // Conservatively only handle 'returned' on non-vectors for now
7067 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7068 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7069 "unexpected use of 'returned'");
7070 // Before passing 'returned' to the target lowering code, ensure that
7071 // either the register MVT and the actual EVT are the same size or that
7072 // the return value and argument are extended in the same way; in these
7073 // cases it's safe to pass the argument register value unchanged as the
7074 // return register value (although it's at the target's option whether
7076 // TODO: allow code generation to take advantage of partially preserved
7077 // registers rather than clobbering the entire register when the
7078 // parameter extension method is not compatible with the return
7080 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7081 (ExtendKind != ISD::ANY_EXTEND &&
7082 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7083 Flags.setReturned();
7086 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
7087 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
7089 for (unsigned j = 0; j != NumParts; ++j) {
7090 // if it isn't first piece, alignment must be 1
7091 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7092 i < CLI.NumFixedArgs,
7093 i, j*Parts[j].getValueType().getStoreSize());
7094 if (NumParts > 1 && j == 0)
7095 MyFlags.Flags.setSplit();
7097 MyFlags.Flags.setOrigAlign(1);
7099 CLI.Outs.push_back(MyFlags);
7100 CLI.OutVals.push_back(Parts[j]);
7105 SmallVector<SDValue, 4> InVals;
7106 CLI.Chain = LowerCall(CLI, InVals);
7108 // Verify that the target's LowerCall behaved as expected.
7109 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7110 "LowerCall didn't return a valid chain!");
7111 assert((!CLI.IsTailCall || InVals.empty()) &&
7112 "LowerCall emitted a return value for a tail call!");
7113 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7114 "LowerCall didn't emit the correct number of values!");
7116 // For a tail call, the return value is merely live-out and there aren't
7117 // any nodes in the DAG representing it. Return a special value to
7118 // indicate that a tail call has been emitted and no more Instructions
7119 // should be processed in the current block.
7120 if (CLI.IsTailCall) {
7121 CLI.DAG.setRoot(CLI.Chain);
7122 return std::make_pair(SDValue(), SDValue());
7125 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7126 assert(InVals[i].getNode() &&
7127 "LowerCall emitted a null value!");
7128 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7129 "LowerCall emitted a value with the wrong type!");
7132 // Collect the legal value parts into potentially illegal values
7133 // that correspond to the original function's return values.
7134 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7136 AssertOp = ISD::AssertSext;
7137 else if (CLI.RetZExt)
7138 AssertOp = ISD::AssertZext;
7139 SmallVector<SDValue, 4> ReturnValues;
7140 unsigned CurReg = 0;
7141 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7143 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7144 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7146 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7147 NumRegs, RegisterVT, VT, NULL,
7152 // For a function returning void, there is no return value. We can't create
7153 // such a node, so we just return a null return value in that case. In
7154 // that case, nothing will actually look at the value.
7155 if (ReturnValues.empty())
7156 return std::make_pair(SDValue(), CLI.Chain);
7158 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7159 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
7160 &ReturnValues[0], ReturnValues.size());
7161 return std::make_pair(Res, CLI.Chain);
7164 void TargetLowering::LowerOperationWrapper(SDNode *N,
7165 SmallVectorImpl<SDValue> &Results,
7166 SelectionDAG &DAG) const {
7167 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7169 Results.push_back(Res);
7172 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7173 llvm_unreachable("LowerOperation not implemented for this target!");
7177 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7178 SDValue Op = getNonRegisterValue(V);
7179 assert((Op.getOpcode() != ISD::CopyFromReg ||
7180 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7181 "Copy from a reg to the same reg!");
7182 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7184 const TargetLowering *TLI = TM.getTargetLowering();
7185 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
7186 SDValue Chain = DAG.getEntryNode();
7187 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V);
7188 PendingExports.push_back(Chain);
7191 #include "llvm/CodeGen/SelectionDAGISel.h"
7193 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7194 /// entry block, return true. This includes arguments used by switches, since
7195 /// the switch may expand into multiple basic blocks.
7196 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7197 // With FastISel active, we may be splitting blocks, so force creation
7198 // of virtual registers for all non-dead arguments.
7200 return A->use_empty();
7202 const BasicBlock *Entry = A->getParent()->begin();
7203 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
7205 const User *U = *UI;
7206 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7207 return false; // Use not in entry block.
7212 void SelectionDAGISel::LowerArguments(const Function &F) {
7213 SelectionDAG &DAG = SDB->DAG;
7214 SDLoc dl = SDB->getCurSDLoc();
7215 const TargetLowering *TLI = getTargetLowering();
7216 const DataLayout *TD = TLI->getDataLayout();
7217 SmallVector<ISD::InputArg, 16> Ins;
7219 if (!FuncInfo->CanLowerReturn) {
7220 // Put in an sret pointer parameter before all the other parameters.
7221 SmallVector<EVT, 1> ValueVTs;
7222 ComputeValueVTs(*getTargetLowering(),
7223 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7225 // NOTE: Assuming that a pointer will never break down to more than one VT
7227 ISD::ArgFlagsTy Flags;
7229 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7230 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
7231 Ins.push_back(RetArg);
7234 // Set up the incoming argument description vector.
7236 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7237 I != E; ++I, ++Idx) {
7238 SmallVector<EVT, 4> ValueVTs;
7239 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7240 bool isArgValueUsed = !I->use_empty();
7241 unsigned PartBase = 0;
7242 for (unsigned Value = 0, NumValues = ValueVTs.size();
7243 Value != NumValues; ++Value) {
7244 EVT VT = ValueVTs[Value];
7245 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7246 ISD::ArgFlagsTy Flags;
7247 unsigned OriginalAlignment =
7248 TD->getABITypeAlignment(ArgTy);
7250 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7252 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7254 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7256 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7258 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) {
7260 PointerType *Ty = cast<PointerType>(I->getType());
7261 Type *ElementTy = Ty->getElementType();
7262 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
7263 // For ByVal, alignment should be passed from FE. BE will guess if
7264 // this info is not there but there are cases it cannot get right.
7265 unsigned FrameAlign;
7266 if (F.getParamAlignment(Idx))
7267 FrameAlign = F.getParamAlignment(Idx);
7269 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7270 Flags.setByValAlign(FrameAlign);
7272 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7274 Flags.setOrigAlign(OriginalAlignment);
7276 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7277 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7278 for (unsigned i = 0; i != NumRegs; ++i) {
7279 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7280 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7281 if (NumRegs > 1 && i == 0)
7282 MyFlags.Flags.setSplit();
7283 // if it isn't first piece, alignment must be 1
7285 MyFlags.Flags.setOrigAlign(1);
7286 Ins.push_back(MyFlags);
7288 PartBase += VT.getStoreSize();
7292 // Call the target to set up the argument values.
7293 SmallVector<SDValue, 8> InVals;
7294 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
7298 // Verify that the target's LowerFormalArguments behaved as expected.
7299 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7300 "LowerFormalArguments didn't return a valid chain!");
7301 assert(InVals.size() == Ins.size() &&
7302 "LowerFormalArguments didn't emit the correct number of values!");
7304 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7305 assert(InVals[i].getNode() &&
7306 "LowerFormalArguments emitted a null value!");
7307 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7308 "LowerFormalArguments emitted a value with the wrong type!");
7312 // Update the DAG with the new chain value resulting from argument lowering.
7313 DAG.setRoot(NewRoot);
7315 // Set up the argument values.
7318 if (!FuncInfo->CanLowerReturn) {
7319 // Create a virtual register for the sret pointer, and put in a copy
7320 // from the sret argument into it.
7321 SmallVector<EVT, 1> ValueVTs;
7322 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7323 MVT VT = ValueVTs[0].getSimpleVT();
7324 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7325 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7326 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7327 RegVT, VT, NULL, AssertOp);
7329 MachineFunction& MF = SDB->DAG.getMachineFunction();
7330 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7331 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7332 FuncInfo->DemoteRegister = SRetReg;
7333 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
7335 DAG.setRoot(NewRoot);
7337 // i indexes lowered arguments. Bump it past the hidden sret argument.
7338 // Idx indexes LLVM arguments. Don't touch it.
7342 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7344 SmallVector<SDValue, 4> ArgValues;
7345 SmallVector<EVT, 4> ValueVTs;
7346 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7347 unsigned NumValues = ValueVTs.size();
7349 // If this argument is unused then remember its value. It is used to generate
7350 // debugging information.
7351 if (I->use_empty() && NumValues) {
7352 SDB->setUnusedArgValue(I, InVals[i]);
7354 // Also remember any frame index for use in FastISel.
7355 if (FrameIndexSDNode *FI =
7356 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7357 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7360 for (unsigned Val = 0; Val != NumValues; ++Val) {
7361 EVT VT = ValueVTs[Val];
7362 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7363 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7365 if (!I->use_empty()) {
7366 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7367 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7368 AssertOp = ISD::AssertSext;
7369 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7370 AssertOp = ISD::AssertZext;
7372 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7373 NumParts, PartVT, VT,
7380 // We don't need to do anything else for unused arguments.
7381 if (ArgValues.empty())
7384 // Note down frame index.
7385 if (FrameIndexSDNode *FI =
7386 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7387 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7389 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
7390 SDB->getCurSDLoc());
7392 SDB->setValue(I, Res);
7393 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7394 if (LoadSDNode *LNode =
7395 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7396 if (FrameIndexSDNode *FI =
7397 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7398 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7401 // If this argument is live outside of the entry block, insert a copy from
7402 // wherever we got it to the vreg that other BB's will reference it as.
7403 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7404 // If we can, though, try to skip creating an unnecessary vreg.
7405 // FIXME: This isn't very clean... it would be nice to make this more
7406 // general. It's also subtly incompatible with the hacks FastISel
7408 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7409 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7410 FuncInfo->ValueMap[I] = Reg;
7414 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7415 FuncInfo->InitializeRegForValue(I);
7416 SDB->CopyToExportRegsIfNeeded(I);
7420 assert(i == InVals.size() && "Argument register count mismatch!");
7422 // Finally, if the target has anything special to do, allow it to do so.
7423 // FIXME: this should insert code into the DAG!
7424 EmitFunctionEntryCode();
7427 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7428 /// ensure constants are generated when needed. Remember the virtual registers
7429 /// that need to be added to the Machine PHI nodes as input. We cannot just
7430 /// directly add them, because expansion might result in multiple MBB's for one
7431 /// BB. As such, the start of the BB might correspond to a different MBB than
7435 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7436 const TerminatorInst *TI = LLVMBB->getTerminator();
7438 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7440 // Check successor nodes' PHI nodes that expect a constant to be available
7442 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7443 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7444 if (!isa<PHINode>(SuccBB->begin())) continue;
7445 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7447 // If this terminator has multiple identical successors (common for
7448 // switches), only handle each succ once.
7449 if (!SuccsHandled.insert(SuccMBB)) continue;
7451 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7453 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7454 // nodes and Machine PHI nodes, but the incoming operands have not been
7456 for (BasicBlock::const_iterator I = SuccBB->begin();
7457 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7458 // Ignore dead phi's.
7459 if (PN->use_empty()) continue;
7462 if (PN->getType()->isEmptyTy())
7466 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7468 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7469 unsigned &RegOut = ConstantsOut[C];
7471 RegOut = FuncInfo.CreateRegs(C->getType());
7472 CopyValueToVirtualRegister(C, RegOut);
7476 DenseMap<const Value *, unsigned>::iterator I =
7477 FuncInfo.ValueMap.find(PHIOp);
7478 if (I != FuncInfo.ValueMap.end())
7481 assert(isa<AllocaInst>(PHIOp) &&
7482 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7483 "Didn't codegen value into a register!??");
7484 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7485 CopyValueToVirtualRegister(PHIOp, Reg);
7489 // Remember that this register needs to added to the machine PHI node as
7490 // the input for this MBB.
7491 SmallVector<EVT, 4> ValueVTs;
7492 const TargetLowering *TLI = TM.getTargetLowering();
7493 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
7494 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7495 EVT VT = ValueVTs[vti];
7496 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
7497 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7498 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7499 Reg += NumRegisters;
7504 ConstantsOut.clear();
7507 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7510 SelectionDAGBuilder::StackProtectorDescriptor::
7511 AddSuccessorMBB(const BasicBlock *BB,
7512 MachineBasicBlock *ParentMBB,
7513 MachineBasicBlock *SuccMBB) {
7514 // If SuccBB has not been created yet, create it.
7516 MachineFunction *MF = ParentMBB->getParent();
7517 MachineFunction::iterator BBI = ParentMBB;
7518 SuccMBB = MF->CreateMachineBasicBlock(BB);
7519 MF->insert(++BBI, SuccMBB);
7521 // Add it as a successor of ParentMBB.
7522 ParentMBB->addSuccessor(SuccMBB);