1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/GCMetadata.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/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugInfo.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GCStrategy.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/InlineAsm.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/Statepoint.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetFrameLowering.h"
59 #include "llvm/Target/TargetInstrInfo.h"
60 #include "llvm/Target/TargetIntrinsicInfo.h"
61 #include "llvm/Target/TargetLowering.h"
62 #include "llvm/Target/TargetOptions.h"
63 #include "llvm/Target/TargetSelectionDAGInfo.h"
64 #include "llvm/Target/TargetSubtargetInfo.h"
65 #include <algorithm>
66 using namespace llvm;
68 #define DEBUG_TYPE "isel"
70 /// LimitFloatPrecision - Generate low-precision inline sequences for
71 /// some float libcalls (6, 8 or 12 bits).
72 static unsigned LimitFloatPrecision;
74 static cl::opt<unsigned, true>
75 LimitFPPrecision("limit-float-precision",
76 cl::desc("Generate low-precision inline sequences "
77 "for some float libcalls"),
78 cl::location(LimitFloatPrecision),
79 cl::init(0));
81 // Limit the width of DAG chains. This is important in general to prevent
82 // prevent DAG-based analysis from blowing up. For example, alias analysis and
83 // load clustering may not complete in reasonable time. It is difficult to
84 // recognize and avoid this situation within each individual analysis, and
85 // future analyses are likely to have the same behavior. Limiting DAG width is
86 // the safe approach, and will be especially important with global DAGs.
87 //
88 // MaxParallelChains default is arbitrarily high to avoid affecting
89 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
90 // sequence over this should have been converted to llvm.memcpy by the
91 // frontend. It easy to induce this behavior with .ll code such as:
92 // %buffer = alloca [4096 x i8]
93 // %data = load [4096 x i8]* %argPtr
94 // store [4096 x i8] %data, [4096 x i8]* %buffer
95 static const unsigned MaxParallelChains = 64;
97 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
98 const SDValue *Parts, unsigned NumParts,
99 MVT PartVT, EVT ValueVT, const Value *V);
101 /// getCopyFromParts - Create a value that contains the specified legal parts
102 /// combined into the value they represent. If the parts combine to a type
103 /// larger then ValueVT then AssertOp can be used to specify whether the extra
104 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
105 /// (ISD::AssertSext).
106 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
107 const SDValue *Parts,
108 unsigned NumParts, MVT PartVT, EVT ValueVT,
109 const Value *V,
110 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
111 if (ValueVT.isVector())
112 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
113 PartVT, ValueVT, V);
115 assert(NumParts > 0 && "No parts to assemble!");
116 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
117 SDValue Val = Parts[0];
119 if (NumParts > 1) {
120 // Assemble the value from multiple parts.
121 if (ValueVT.isInteger()) {
122 unsigned PartBits = PartVT.getSizeInBits();
123 unsigned ValueBits = ValueVT.getSizeInBits();
125 // Assemble the power of 2 part.
126 unsigned RoundParts = NumParts & (NumParts - 1) ?
127 1 << Log2_32(NumParts) : NumParts;
128 unsigned RoundBits = PartBits * RoundParts;
129 EVT RoundVT = RoundBits == ValueBits ?
130 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
131 SDValue Lo, Hi;
133 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
135 if (RoundParts > 2) {
136 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
137 PartVT, HalfVT, V);
138 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
139 RoundParts / 2, PartVT, HalfVT, V);
140 } else {
141 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
142 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
143 }
145 if (TLI.isBigEndian())
146 std::swap(Lo, Hi);
148 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
150 if (RoundParts < NumParts) {
151 // Assemble the trailing non-power-of-2 part.
152 unsigned OddParts = NumParts - RoundParts;
153 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
154 Hi = getCopyFromParts(DAG, DL,
155 Parts + RoundParts, OddParts, PartVT, OddVT, V);
157 // Combine the round and odd parts.
158 Lo = Val;
159 if (TLI.isBigEndian())
160 std::swap(Lo, Hi);
161 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
162 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
163 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
164 DAG.getConstant(Lo.getValueType().getSizeInBits(),
165 TLI.getPointerTy()));
166 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
167 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
168 }
169 } else if (PartVT.isFloatingPoint()) {
170 // FP split into multiple FP parts (for ppcf128)
171 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
172 "Unexpected split");
173 SDValue Lo, Hi;
174 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
175 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
176 if (TLI.hasBigEndianPartOrdering(ValueVT))
177 std::swap(Lo, Hi);
178 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
179 } else {
180 // FP split into integer parts (soft fp)
181 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
182 !PartVT.isVector() && "Unexpected split");
183 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
184 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
185 }
186 }
188 // There is now one part, held in Val. Correct it to match ValueVT.
189 EVT PartEVT = Val.getValueType();
191 if (PartEVT == ValueVT)
192 return Val;
194 if (PartEVT.isInteger() && ValueVT.isInteger()) {
195 if (ValueVT.bitsLT(PartEVT)) {
196 // For a truncate, see if we have any information to
197 // indicate whether the truncated bits will always be
198 // zero or sign-extension.
199 if (AssertOp != ISD::DELETED_NODE)
200 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
201 DAG.getValueType(ValueVT));
202 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
203 }
204 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
205 }
207 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
208 // FP_ROUND's are always exact here.
209 if (ValueVT.bitsLT(Val.getValueType()))
210 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
211 DAG.getTargetConstant(1, TLI.getPointerTy()));
213 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
214 }
216 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
217 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
219 llvm_unreachable("Unknown mismatch!");
220 }
222 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
223 const Twine &ErrMsg) {
224 const Instruction *I = dyn_cast_or_null<Instruction>(V);
225 if (!V)
226 return Ctx.emitError(ErrMsg);
228 const char *AsmError = ", possible invalid constraint for vector type";
229 if (const CallInst *CI = dyn_cast<CallInst>(I))
230 if (isa<InlineAsm>(CI->getCalledValue()))
231 return Ctx.emitError(I, ErrMsg + AsmError);
233 return Ctx.emitError(I, ErrMsg);
234 }
236 /// getCopyFromPartsVector - Create a value that contains the specified legal
237 /// parts combined into the value they represent. If the parts combine to a
238 /// type larger then ValueVT then AssertOp can be used to specify whether the
239 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
240 /// ValueVT (ISD::AssertSext).
241 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
242 const SDValue *Parts, unsigned NumParts,
243 MVT PartVT, EVT ValueVT, const Value *V) {
244 assert(ValueVT.isVector() && "Not a vector value");
245 assert(NumParts > 0 && "No parts to assemble!");
246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
247 SDValue Val = Parts[0];
249 // Handle a multi-element vector.
250 if (NumParts > 1) {
251 EVT IntermediateVT;
252 MVT RegisterVT;
253 unsigned NumIntermediates;
254 unsigned NumRegs =
255 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
256 NumIntermediates, RegisterVT);
257 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
258 NumParts = NumRegs; // Silence a compiler warning.
259 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
260 assert(RegisterVT == Parts[0].getSimpleValueType() &&
261 "Part type doesn't match part!");
263 // Assemble the parts into intermediate operands.
264 SmallVector<SDValue, 8> Ops(NumIntermediates);
265 if (NumIntermediates == NumParts) {
266 // If the register was not expanded, truncate or copy the value,
267 // as appropriate.
268 for (unsigned i = 0; i != NumParts; ++i)
269 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
270 PartVT, IntermediateVT, V);
271 } else if (NumParts > 0) {
272 // If the intermediate type was expanded, build the intermediate
273 // operands from the parts.
274 assert(NumParts % NumIntermediates == 0 &&
275 "Must expand into a divisible number of parts!");
276 unsigned Factor = NumParts / NumIntermediates;
277 for (unsigned i = 0; i != NumIntermediates; ++i)
278 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
279 PartVT, IntermediateVT, V);
280 }
282 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
283 // intermediate operands.
284 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
285 : ISD::BUILD_VECTOR,
286 DL, ValueVT, Ops);
287 }
289 // There is now one part, held in Val. Correct it to match ValueVT.
290 EVT PartEVT = Val.getValueType();
292 if (PartEVT == ValueVT)
293 return Val;
295 if (PartEVT.isVector()) {
296 // If the element type of the source/dest vectors are the same, but the
297 // parts vector has more elements than the value vector, then we have a
298 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
299 // elements we want.
300 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
301 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
302 "Cannot narrow, it would be a lossy transformation");
303 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
304 DAG.getConstant(0, TLI.getVectorIdxTy()));
305 }
307 // Vector/Vector bitcast.
308 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
309 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
311 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
312 "Cannot handle this kind of promotion");
313 // Promoted vector extract
314 bool Smaller = ValueVT.bitsLE(PartEVT);
315 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
316 DL, ValueVT, Val);
318 }
320 // Trivial bitcast if the types are the same size and the destination
321 // vector type is legal.
322 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
323 TLI.isTypeLegal(ValueVT))
324 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
326 // Handle cases such as i8 -> <1 x i1>
327 if (ValueVT.getVectorNumElements() != 1) {
328 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
329 "non-trivial scalar-to-vector conversion");
330 return DAG.getUNDEF(ValueVT);
331 }
333 if (ValueVT.getVectorNumElements() == 1 &&
334 ValueVT.getVectorElementType() != PartEVT) {
335 bool Smaller = ValueVT.bitsLE(PartEVT);
336 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
337 DL, ValueVT.getScalarType(), Val);
338 }
340 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
341 }
343 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
344 SDValue Val, SDValue *Parts, unsigned NumParts,
345 MVT PartVT, const Value *V);
347 /// getCopyToParts - Create a series of nodes that contain the specified value
348 /// split into legal parts. If the parts contain more bits than Val, then, for
349 /// integers, ExtendKind can be used to specify how to generate the extra bits.
350 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
351 SDValue Val, SDValue *Parts, unsigned NumParts,
352 MVT PartVT, const Value *V,
353 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
354 EVT ValueVT = Val.getValueType();
356 // Handle the vector case separately.
357 if (ValueVT.isVector())
358 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
361 unsigned PartBits = PartVT.getSizeInBits();
362 unsigned OrigNumParts = NumParts;
363 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
365 if (NumParts == 0)
366 return;
368 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
369 EVT PartEVT = PartVT;
370 if (PartEVT == ValueVT) {
371 assert(NumParts == 1 && "No-op copy with multiple parts!");
372 Parts[0] = Val;
373 return;
374 }
376 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
377 // If the parts cover more bits than the value has, promote the value.
378 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
379 assert(NumParts == 1 && "Do not know what to promote to!");
380 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
381 } else {
382 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
383 ValueVT.isInteger() &&
384 "Unknown mismatch!");
385 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
386 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
387 if (PartVT == MVT::x86mmx)
388 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
389 }
390 } else if (PartBits == ValueVT.getSizeInBits()) {
391 // Different types of the same size.
392 assert(NumParts == 1 && PartEVT != ValueVT);
393 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
394 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
395 // If the parts cover less bits than value has, truncate the value.
396 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
397 ValueVT.isInteger() &&
398 "Unknown mismatch!");
399 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
400 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
401 if (PartVT == MVT::x86mmx)
402 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
403 }
405 // The value may have changed - recompute ValueVT.
406 ValueVT = Val.getValueType();
407 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
408 "Failed to tile the value with PartVT!");
410 if (NumParts == 1) {
411 if (PartEVT != ValueVT)
412 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
413 "scalar-to-vector conversion failed");
415 Parts[0] = Val;
416 return;
417 }
419 // Expand the value into multiple parts.
420 if (NumParts & (NumParts - 1)) {
421 // The number of parts is not a power of 2. Split off and copy the tail.
422 assert(PartVT.isInteger() && ValueVT.isInteger() &&
423 "Do not know what to expand to!");
424 unsigned RoundParts = 1 << Log2_32(NumParts);
425 unsigned RoundBits = RoundParts * PartBits;
426 unsigned OddParts = NumParts - RoundParts;
427 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
428 DAG.getIntPtrConstant(RoundBits));
429 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
431 if (TLI.isBigEndian())
432 // The odd parts were reversed by getCopyToParts - unreverse them.
433 std::reverse(Parts + RoundParts, Parts + NumParts);
435 NumParts = RoundParts;
436 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
437 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
438 }
440 // The number of parts is a power of 2. Repeatedly bisect the value using
441 // EXTRACT_ELEMENT.
442 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
443 EVT::getIntegerVT(*DAG.getContext(),
444 ValueVT.getSizeInBits()),
445 Val);
447 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
448 for (unsigned i = 0; i < NumParts; i += StepSize) {
449 unsigned ThisBits = StepSize * PartBits / 2;
450 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
451 SDValue &Part0 = Parts[i];
452 SDValue &Part1 = Parts[i+StepSize/2];
454 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
455 ThisVT, Part0, DAG.getIntPtrConstant(1));
456 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
457 ThisVT, Part0, DAG.getIntPtrConstant(0));
459 if (ThisBits == PartBits && ThisVT != PartVT) {
460 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
461 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
462 }
463 }
464 }
466 if (TLI.isBigEndian())
467 std::reverse(Parts, Parts + OrigNumParts);
468 }
471 /// getCopyToPartsVector - Create a series of nodes that contain the specified
472 /// value split into legal parts.
473 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
474 SDValue Val, SDValue *Parts, unsigned NumParts,
475 MVT PartVT, const Value *V) {
476 EVT ValueVT = Val.getValueType();
477 assert(ValueVT.isVector() && "Not a vector");
478 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
480 if (NumParts == 1) {
481 EVT PartEVT = PartVT;
482 if (PartEVT == ValueVT) {
483 // Nothing to do.
484 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
485 // Bitconvert vector->vector case.
486 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
487 } else if (PartVT.isVector() &&
488 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
489 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
490 EVT ElementVT = PartVT.getVectorElementType();
491 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
492 // undef elements.
493 SmallVector<SDValue, 16> Ops;
494 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
495 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
496 ElementVT, Val, DAG.getConstant(i,
497 TLI.getVectorIdxTy())));
499 for (unsigned i = ValueVT.getVectorNumElements(),
500 e = PartVT.getVectorNumElements(); i != e; ++i)
501 Ops.push_back(DAG.getUNDEF(ElementVT));
503 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
505 // FIXME: Use CONCAT for 2x -> 4x.
507 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
508 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
509 } else if (PartVT.isVector() &&
510 PartEVT.getVectorElementType().bitsGE(
511 ValueVT.getVectorElementType()) &&
512 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
514 // Promoted vector extract
515 bool Smaller = PartEVT.bitsLE(ValueVT);
516 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
517 DL, PartVT, Val);
518 } else{
519 // Vector -> scalar conversion.
520 assert(ValueVT.getVectorNumElements() == 1 &&
521 "Only trivial vector-to-scalar conversions should get here!");
522 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
523 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
525 bool Smaller = ValueVT.bitsLE(PartVT);
526 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
527 DL, PartVT, Val);
528 }
530 Parts[0] = Val;
531 return;
532 }
534 // Handle a multi-element vector.
535 EVT IntermediateVT;
536 MVT RegisterVT;
537 unsigned NumIntermediates;
538 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
539 IntermediateVT,
540 NumIntermediates, RegisterVT);
541 unsigned NumElements = ValueVT.getVectorNumElements();
543 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
544 NumParts = NumRegs; // Silence a compiler warning.
545 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
547 // Split the vector into intermediate operands.
548 SmallVector<SDValue, 8> Ops(NumIntermediates);
549 for (unsigned i = 0; i != NumIntermediates; ++i) {
550 if (IntermediateVT.isVector())
551 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
552 IntermediateVT, Val,
553 DAG.getConstant(i * (NumElements / NumIntermediates),
554 TLI.getVectorIdxTy()));
555 else
556 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
557 IntermediateVT, Val,
558 DAG.getConstant(i, TLI.getVectorIdxTy()));
559 }
561 // Split the intermediate operands into legal parts.
562 if (NumParts == NumIntermediates) {
563 // If the register was not expanded, promote or copy the value,
564 // as appropriate.
565 for (unsigned i = 0; i != NumParts; ++i)
566 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
567 } else if (NumParts > 0) {
568 // If the intermediate type was expanded, split each the value into
569 // legal parts.
570 assert(NumIntermediates != 0 && "division by zero");
571 assert(NumParts % NumIntermediates == 0 &&
572 "Must expand into a divisible number of parts!");
573 unsigned Factor = NumParts / NumIntermediates;
574 for (unsigned i = 0; i != NumIntermediates; ++i)
575 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
576 }
577 }
579 namespace {
580 /// RegsForValue - This struct represents the registers (physical or virtual)
581 /// that a particular set of values is assigned, and the type information
582 /// about the value. The most common situation is to represent one value at a
583 /// time, but struct or array values are handled element-wise as multiple
584 /// values. The splitting of aggregates is performed recursively, so that we
585 /// never have aggregate-typed registers. The values at this point do not
586 /// necessarily have legal types, so each value may require one or more
587 /// registers of some legal type.
588 ///
589 struct RegsForValue {
590 /// ValueVTs - The value types of the values, which may not be legal, and
591 /// may need be promoted or synthesized from one or more registers.
592 ///
593 SmallVector<EVT, 4> ValueVTs;
595 /// RegVTs - The value types of the registers. This is the same size as
596 /// ValueVTs and it records, for each value, what the type of the assigned
597 /// register or registers are. (Individual values are never synthesized
598 /// from more than one type of register.)
599 ///
600 /// With virtual registers, the contents of RegVTs is redundant with TLI's
601 /// getRegisterType member function, however when with physical registers
602 /// it is necessary to have a separate record of the types.
603 ///
604 SmallVector<MVT, 4> RegVTs;
606 /// Regs - This list holds the registers assigned to the values.
607 /// Each legal or promoted value requires one register, and each
608 /// expanded value requires multiple registers.
609 ///
610 SmallVector<unsigned, 4> Regs;
612 RegsForValue() {}
614 RegsForValue(const SmallVector<unsigned, 4> ®s,
615 MVT regvt, EVT valuevt)
616 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
618 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
619 unsigned Reg, Type *Ty) {
620 ComputeValueVTs(tli, Ty, ValueVTs);
622 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
623 EVT ValueVT = ValueVTs[Value];
624 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
625 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
626 for (unsigned i = 0; i != NumRegs; ++i)
627 Regs.push_back(Reg + i);
628 RegVTs.push_back(RegisterVT);
629 Reg += NumRegs;
630 }
631 }
633 /// append - Add the specified values to this one.
634 void append(const RegsForValue &RHS) {
635 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
636 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
637 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
638 }
640 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
641 /// this value and returns the result as a ValueVTs value. This uses
642 /// Chain/Flag as the input and updates them for the output Chain/Flag.
643 /// If the Flag pointer is NULL, no flag is used.
644 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
645 SDLoc dl,
646 SDValue &Chain, SDValue *Flag,
647 const Value *V = nullptr) const;
649 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
650 /// specified value into the registers specified by this object. This uses
651 /// Chain/Flag as the input and updates them for the output Chain/Flag.
652 /// If the Flag pointer is NULL, no flag is used.
653 void
654 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
655 SDValue *Flag, const Value *V,
656 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
658 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
659 /// operand list. This adds the code marker, matching input operand index
660 /// (if applicable), and includes the number of values added into it.
661 void AddInlineAsmOperands(unsigned Kind,
662 bool HasMatching, unsigned MatchingIdx,
663 SelectionDAG &DAG,
664 std::vector<SDValue> &Ops) const;
665 };
666 }
668 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
669 /// this value and returns the result as a ValueVT value. This uses
670 /// Chain/Flag as the input and updates them for the output Chain/Flag.
671 /// If the Flag pointer is NULL, no flag is used.
672 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
673 FunctionLoweringInfo &FuncInfo,
674 SDLoc dl,
675 SDValue &Chain, SDValue *Flag,
676 const Value *V) const {
677 // A Value with type {} or [0 x %t] needs no registers.
678 if (ValueVTs.empty())
679 return SDValue();
681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
683 // Assemble the legal parts into the final values.
684 SmallVector<SDValue, 4> Values(ValueVTs.size());
685 SmallVector<SDValue, 8> Parts;
686 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
687 // Copy the legal parts from the registers.
688 EVT ValueVT = ValueVTs[Value];
689 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
690 MVT RegisterVT = RegVTs[Value];
692 Parts.resize(NumRegs);
693 for (unsigned i = 0; i != NumRegs; ++i) {
694 SDValue P;
695 if (!Flag) {
696 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
697 } else {
698 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
699 *Flag = P.getValue(2);
700 }
702 Chain = P.getValue(1);
703 Parts[i] = P;
705 // If the source register was virtual and if we know something about it,
706 // add an assert node.
707 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
708 !RegisterVT.isInteger() || RegisterVT.isVector())
709 continue;
711 const FunctionLoweringInfo::LiveOutInfo *LOI =
712 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
713 if (!LOI)
714 continue;
716 unsigned RegSize = RegisterVT.getSizeInBits();
717 unsigned NumSignBits = LOI->NumSignBits;
718 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
720 if (NumZeroBits == RegSize) {
721 // The current value is a zero.
722 // Explicitly express that as it would be easier for
723 // optimizations to kick in.
724 Parts[i] = DAG.getConstant(0, RegisterVT);
725 continue;
726 }
728 // FIXME: We capture more information than the dag can represent. For
729 // now, just use the tightest assertzext/assertsext possible.
730 bool isSExt = true;
731 EVT FromVT(MVT::Other);
732 if (NumSignBits == RegSize)
733 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
734 else if (NumZeroBits >= RegSize-1)
735 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
736 else if (NumSignBits > RegSize-8)
737 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
738 else if (NumZeroBits >= RegSize-8)
739 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
740 else if (NumSignBits > RegSize-16)
741 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
742 else if (NumZeroBits >= RegSize-16)
743 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
744 else if (NumSignBits > RegSize-32)
745 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
746 else if (NumZeroBits >= RegSize-32)
747 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
748 else
749 continue;
751 // Add an assertion node.
752 assert(FromVT != MVT::Other);
753 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
754 RegisterVT, P, DAG.getValueType(FromVT));
755 }
757 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
758 NumRegs, RegisterVT, ValueVT, V);
759 Part += NumRegs;
760 Parts.clear();
761 }
763 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
764 }
766 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
767 /// specified value into the registers specified by this object. This uses
768 /// Chain/Flag as the input and updates them for the output Chain/Flag.
769 /// If the Flag pointer is NULL, no flag is used.
770 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
771 SDValue &Chain, SDValue *Flag, const Value *V,
772 ISD::NodeType PreferredExtendType) const {
773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
774 ISD::NodeType ExtendKind = PreferredExtendType;
776 // Get the list of the values's legal parts.
777 unsigned NumRegs = Regs.size();
778 SmallVector<SDValue, 8> Parts(NumRegs);
779 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
780 EVT ValueVT = ValueVTs[Value];
781 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
782 MVT RegisterVT = RegVTs[Value];
784 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
785 ExtendKind = ISD::ZERO_EXTEND;
787 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
788 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
789 Part += NumParts;
790 }
792 // Copy the parts into the registers.
793 SmallVector<SDValue, 8> Chains(NumRegs);
794 for (unsigned i = 0; i != NumRegs; ++i) {
795 SDValue Part;
796 if (!Flag) {
797 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
798 } else {
799 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
800 *Flag = Part.getValue(1);
801 }
803 Chains[i] = Part.getValue(0);
804 }
806 if (NumRegs == 1 || Flag)
807 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
808 // flagged to it. That is the CopyToReg nodes and the user are considered
809 // a single scheduling unit. If we create a TokenFactor and return it as
810 // chain, then the TokenFactor is both a predecessor (operand) of the
811 // user as well as a successor (the TF operands are flagged to the user).
812 // c1, f1 = CopyToReg
813 // c2, f2 = CopyToReg
814 // c3 = TokenFactor c1, c2
815 // ...
816 // = op c3, ..., f2
817 Chain = Chains[NumRegs-1];
818 else
819 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
820 }
822 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
823 /// operand list. This adds the code marker and includes the number of
824 /// values added into it.
825 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
826 unsigned MatchingIdx,
827 SelectionDAG &DAG,
828 std::vector<SDValue> &Ops) const {
829 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
831 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
832 if (HasMatching)
833 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
834 else if (!Regs.empty() &&
835 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
836 // Put the register class of the virtual registers in the flag word. That
837 // way, later passes can recompute register class constraints for inline
838 // assembly as well as normal instructions.
839 // Don't do this for tied operands that can use the regclass information
840 // from the def.
841 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
842 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
843 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
844 }
846 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
847 Ops.push_back(Res);
849 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
850 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
851 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
852 MVT RegisterVT = RegVTs[Value];
853 for (unsigned i = 0; i != NumRegs; ++i) {
854 assert(Reg < Regs.size() && "Mismatch in # registers expected");
855 unsigned TheReg = Regs[Reg++];
856 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
858 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
859 // If we clobbered the stack pointer, MFI should know about it.
860 assert(DAG.getMachineFunction().getFrameInfo()->
861 hasInlineAsmWithSPAdjust());
862 }
863 }
864 }
865 }
867 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
868 const TargetLibraryInfo *li) {
869 AA = &aa;
870 GFI = gfi;
871 LibInfo = li;
872 DL = DAG.getSubtarget().getDataLayout();
873 Context = DAG.getContext();
874 LPadToCallSiteMap.clear();
875 }
877 /// clear - Clear out the current SelectionDAG and the associated
878 /// state and prepare this SelectionDAGBuilder object to be used
879 /// for a new block. This doesn't clear out information about
880 /// additional blocks that are needed to complete switch lowering
881 /// or PHI node updating; that information is cleared out as it is
882 /// consumed.
883 void SelectionDAGBuilder::clear() {
884 NodeMap.clear();
885 UnusedArgNodeMap.clear();
886 PendingLoads.clear();
887 PendingExports.clear();
888 CurInst = nullptr;
889 HasTailCall = false;
890 SDNodeOrder = LowestSDNodeOrder;
891 StatepointLowering.clear();
892 }
894 /// clearDanglingDebugInfo - Clear the dangling debug information
895 /// map. This function is separated from the clear so that debug
896 /// information that is dangling in a basic block can be properly
897 /// resolved in a different basic block. This allows the
898 /// SelectionDAG to resolve dangling debug information attached
899 /// to PHI nodes.
900 void SelectionDAGBuilder::clearDanglingDebugInfo() {
901 DanglingDebugInfoMap.clear();
902 }
904 /// getRoot - Return the current virtual root of the Selection DAG,
905 /// flushing any PendingLoad items. This must be done before emitting
906 /// a store or any other node that may need to be ordered after any
907 /// prior load instructions.
908 ///
909 SDValue SelectionDAGBuilder::getRoot() {
910 if (PendingLoads.empty())
911 return DAG.getRoot();
913 if (PendingLoads.size() == 1) {
914 SDValue Root = PendingLoads[0];
915 DAG.setRoot(Root);
916 PendingLoads.clear();
917 return Root;
918 }
920 // Otherwise, we have to make a token factor node.
921 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
922 PendingLoads);
923 PendingLoads.clear();
924 DAG.setRoot(Root);
925 return Root;
926 }
928 /// getControlRoot - Similar to getRoot, but instead of flushing all the
929 /// PendingLoad items, flush all the PendingExports items. It is necessary
930 /// to do this before emitting a terminator instruction.
931 ///
932 SDValue SelectionDAGBuilder::getControlRoot() {
933 SDValue Root = DAG.getRoot();
935 if (PendingExports.empty())
936 return Root;
938 // Turn all of the CopyToReg chains into one factored node.
939 if (Root.getOpcode() != ISD::EntryToken) {
940 unsigned i = 0, e = PendingExports.size();
941 for (; i != e; ++i) {
942 assert(PendingExports[i].getNode()->getNumOperands() > 1);
943 if (PendingExports[i].getNode()->getOperand(0) == Root)
944 break; // Don't add the root if we already indirectly depend on it.
945 }
947 if (i == e)
948 PendingExports.push_back(Root);
949 }
951 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
952 PendingExports);
953 PendingExports.clear();
954 DAG.setRoot(Root);
955 return Root;
956 }
958 void SelectionDAGBuilder::visit(const Instruction &I) {
959 // Set up outgoing PHI node register values before emitting the terminator.
960 if (isa<TerminatorInst>(&I))
961 HandlePHINodesInSuccessorBlocks(I.getParent());
963 ++SDNodeOrder;
965 CurInst = &I;
967 visit(I.getOpcode(), I);
969 if (!isa<TerminatorInst>(&I) && !HasTailCall)
970 CopyToExportRegsIfNeeded(&I);
972 CurInst = nullptr;
973 }
975 void SelectionDAGBuilder::visitPHI(const PHINode &) {
976 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
977 }
979 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
980 // Note: this doesn't use InstVisitor, because it has to work with
981 // ConstantExpr's in addition to instructions.
982 switch (Opcode) {
983 default: llvm_unreachable("Unknown instruction type encountered!");
984 // Build the switch statement using the Instruction.def file.
985 #define HANDLE_INST(NUM, OPCODE, CLASS) \
986 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
987 #include "llvm/IR/Instruction.def"
988 }
989 }
991 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
992 // generate the debug data structures now that we've seen its definition.
993 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
994 SDValue Val) {
995 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
996 if (DDI.getDI()) {
997 const DbgValueInst *DI = DDI.getDI();
998 DebugLoc dl = DDI.getdl();
999 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1000 MDNode *Variable = DI->getVariable();
1001 MDNode *Expr = DI->getExpression();
1002 uint64_t Offset = DI->getOffset();
1003 // A dbg.value for an alloca is always indirect.
1004 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1005 SDDbgValue *SDV;
1006 if (Val.getNode()) {
1007 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1008 Val)) {
1009 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1010 IsIndirect, Offset, dl, DbgSDNodeOrder);
1011 DAG.AddDbgValue(SDV, Val.getNode(), false);
1012 }
1013 } else
1014 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1015 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1016 }
1017 }
1019 /// getValue - Return an SDValue for the given Value.
1020 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1021 // If we already have an SDValue for this value, use it. It's important
1022 // to do this first, so that we don't create a CopyFromReg if we already
1023 // have a regular SDValue.
1024 SDValue &N = NodeMap[V];
1025 if (N.getNode()) return N;
1027 // If there's a virtual register allocated and initialized for this
1028 // value, use it.
1029 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1030 if (It != FuncInfo.ValueMap.end()) {
1031 unsigned InReg = It->second;
1032 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1033 V->getType());
1034 SDValue Chain = DAG.getEntryNode();
1035 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1036 resolveDanglingDebugInfo(V, N);
1037 return N;
1038 }
1040 // Otherwise create a new SDValue and remember it.
1041 SDValue Val = getValueImpl(V);
1042 NodeMap[V] = Val;
1043 resolveDanglingDebugInfo(V, Val);
1044 return Val;
1045 }
1047 /// getNonRegisterValue - Return an SDValue for the given Value, but
1048 /// don't look in FuncInfo.ValueMap for a virtual register.
1049 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1050 // If we already have an SDValue for this value, use it.
1051 SDValue &N = NodeMap[V];
1052 if (N.getNode()) return N;
1054 // Otherwise create a new SDValue and remember it.
1055 SDValue Val = getValueImpl(V);
1056 NodeMap[V] = Val;
1057 resolveDanglingDebugInfo(V, Val);
1058 return Val;
1059 }
1061 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1062 /// Create an SDValue for the given value.
1063 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1064 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1066 if (const Constant *C = dyn_cast<Constant>(V)) {
1067 EVT VT = TLI.getValueType(V->getType(), true);
1069 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1070 return DAG.getConstant(*CI, VT);
1072 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1073 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1075 if (isa<ConstantPointerNull>(C)) {
1076 unsigned AS = V->getType()->getPointerAddressSpace();
1077 return DAG.getConstant(0, TLI.getPointerTy(AS));
1078 }
1080 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1081 return DAG.getConstantFP(*CFP, VT);
1083 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1084 return DAG.getUNDEF(VT);
1086 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1087 visit(CE->getOpcode(), *CE);
1088 SDValue N1 = NodeMap[V];
1089 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1090 return N1;
1091 }
1093 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1094 SmallVector<SDValue, 4> Constants;
1095 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1096 OI != OE; ++OI) {
1097 SDNode *Val = getValue(*OI).getNode();
1098 // If the operand is an empty aggregate, there are no values.
1099 if (!Val) continue;
1100 // Add each leaf value from the operand to the Constants list
1101 // to form a flattened list of all the values.
1102 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1103 Constants.push_back(SDValue(Val, i));
1104 }
1106 return DAG.getMergeValues(Constants, getCurSDLoc());
1107 }
1109 if (const ConstantDataSequential *CDS =
1110 dyn_cast<ConstantDataSequential>(C)) {
1111 SmallVector<SDValue, 4> Ops;
1112 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1113 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1114 // Add each leaf value from the operand to the Constants list
1115 // to form a flattened list of all the values.
1116 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1117 Ops.push_back(SDValue(Val, i));
1118 }
1120 if (isa<ArrayType>(CDS->getType()))
1121 return DAG.getMergeValues(Ops, getCurSDLoc());
1122 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1123 VT, Ops);
1124 }
1126 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1127 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1128 "Unknown struct or array constant!");
1130 SmallVector<EVT, 4> ValueVTs;
1131 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1132 unsigned NumElts = ValueVTs.size();
1133 if (NumElts == 0)
1134 return SDValue(); // empty struct
1135 SmallVector<SDValue, 4> Constants(NumElts);
1136 for (unsigned i = 0; i != NumElts; ++i) {
1137 EVT EltVT = ValueVTs[i];
1138 if (isa<UndefValue>(C))
1139 Constants[i] = DAG.getUNDEF(EltVT);
1140 else if (EltVT.isFloatingPoint())
1141 Constants[i] = DAG.getConstantFP(0, EltVT);
1142 else
1143 Constants[i] = DAG.getConstant(0, EltVT);
1144 }
1146 return DAG.getMergeValues(Constants, getCurSDLoc());
1147 }
1149 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1150 return DAG.getBlockAddress(BA, VT);
1152 VectorType *VecTy = cast<VectorType>(V->getType());
1153 unsigned NumElements = VecTy->getNumElements();
1155 // Now that we know the number and type of the elements, get that number of
1156 // elements into the Ops array based on what kind of constant it is.
1157 SmallVector<SDValue, 16> Ops;
1158 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1159 for (unsigned i = 0; i != NumElements; ++i)
1160 Ops.push_back(getValue(CV->getOperand(i)));
1161 } else {
1162 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1163 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1165 SDValue Op;
1166 if (EltVT.isFloatingPoint())
1167 Op = DAG.getConstantFP(0, EltVT);
1168 else
1169 Op = DAG.getConstant(0, EltVT);
1170 Ops.assign(NumElements, Op);
1171 }
1173 // Create a BUILD_VECTOR node.
1174 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1175 }
1177 // If this is a static alloca, generate it as the frameindex instead of
1178 // computation.
1179 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1180 DenseMap<const AllocaInst*, int>::iterator SI =
1181 FuncInfo.StaticAllocaMap.find(AI);
1182 if (SI != FuncInfo.StaticAllocaMap.end())
1183 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1184 }
1186 // If this is an instruction which fast-isel has deferred, select it now.
1187 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1188 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1189 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1190 SDValue Chain = DAG.getEntryNode();
1191 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1192 }
1194 llvm_unreachable("Can't get register for value!");
1195 }
1197 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1198 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1199 SDValue Chain = getControlRoot();
1200 SmallVector<ISD::OutputArg, 8> Outs;
1201 SmallVector<SDValue, 8> OutVals;
1203 if (!FuncInfo.CanLowerReturn) {
1204 unsigned DemoteReg = FuncInfo.DemoteRegister;
1205 const Function *F = I.getParent()->getParent();
1207 // Emit a store of the return value through the virtual register.
1208 // Leave Outs empty so that LowerReturn won't try to load return
1209 // registers the usual way.
1210 SmallVector<EVT, 1> PtrValueVTs;
1211 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1212 PtrValueVTs);
1214 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1215 SDValue RetOp = getValue(I.getOperand(0));
1217 SmallVector<EVT, 4> ValueVTs;
1218 SmallVector<uint64_t, 4> Offsets;
1219 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1220 unsigned NumValues = ValueVTs.size();
1222 SmallVector<SDValue, 4> Chains(NumValues);
1223 for (unsigned i = 0; i != NumValues; ++i) {
1224 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1225 RetPtr.getValueType(), RetPtr,
1226 DAG.getIntPtrConstant(Offsets[i]));
1227 Chains[i] =
1228 DAG.getStore(Chain, getCurSDLoc(),
1229 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1230 // FIXME: better loc info would be nice.
1231 Add, MachinePointerInfo(), false, false, 0);
1232 }
1234 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1235 MVT::Other, Chains);
1236 } else if (I.getNumOperands() != 0) {
1237 SmallVector<EVT, 4> ValueVTs;
1238 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1239 unsigned NumValues = ValueVTs.size();
1240 if (NumValues) {
1241 SDValue RetOp = getValue(I.getOperand(0));
1243 const Function *F = I.getParent()->getParent();
1245 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1246 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1247 Attribute::SExt))
1248 ExtendKind = ISD::SIGN_EXTEND;
1249 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1250 Attribute::ZExt))
1251 ExtendKind = ISD::ZERO_EXTEND;
1253 LLVMContext &Context = F->getContext();
1254 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1255 Attribute::InReg);
1257 for (unsigned j = 0; j != NumValues; ++j) {
1258 EVT VT = ValueVTs[j];
1260 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1261 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
1263 unsigned NumParts = TLI.getNumRegisters(Context, VT);
1264 MVT PartVT = TLI.getRegisterType(Context, VT);
1265 SmallVector<SDValue, 4> Parts(NumParts);
1266 getCopyToParts(DAG, getCurSDLoc(),
1267 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1268 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1270 // 'inreg' on function refers to return value
1271 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1272 if (RetInReg)
1273 Flags.setInReg();
1275 // Propagate extension type if any
1276 if (ExtendKind == ISD::SIGN_EXTEND)
1277 Flags.setSExt();
1278 else if (ExtendKind == ISD::ZERO_EXTEND)
1279 Flags.setZExt();
1281 for (unsigned i = 0; i < NumParts; ++i) {
1282 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1283 VT, /*isfixed=*/true, 0, 0));
1284 OutVals.push_back(Parts[i]);
1285 }
1286 }
1287 }
1288 }
1290 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1291 CallingConv::ID CallConv =
1292 DAG.getMachineFunction().getFunction()->getCallingConv();
1293 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1294 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1296 // Verify that the target's LowerReturn behaved as expected.
1297 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1298 "LowerReturn didn't return a valid chain!");
1300 // Update the DAG with the new chain value resulting from return lowering.
1301 DAG.setRoot(Chain);
1302 }
1304 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1305 /// created for it, emit nodes to copy the value into the virtual
1306 /// registers.
1307 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1308 // Skip empty types
1309 if (V->getType()->isEmptyTy())
1310 return;
1312 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1313 if (VMI != FuncInfo.ValueMap.end()) {
1314 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1315 CopyValueToVirtualRegister(V, VMI->second);
1316 }
1317 }
1319 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1320 /// the current basic block, add it to ValueMap now so that we'll get a
1321 /// CopyTo/FromReg.
1322 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1323 // No need to export constants.
1324 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1326 // Already exported?
1327 if (FuncInfo.isExportedInst(V)) return;
1329 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1330 CopyValueToVirtualRegister(V, Reg);
1331 }
1333 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1334 const BasicBlock *FromBB) {
1335 // The operands of the setcc have to be in this block. We don't know
1336 // how to export them from some other block.
1337 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1338 // Can export from current BB.
1339 if (VI->getParent() == FromBB)
1340 return true;
1342 // Is already exported, noop.
1343 return FuncInfo.isExportedInst(V);
1344 }
1346 // If this is an argument, we can export it if the BB is the entry block or
1347 // if it is already exported.
1348 if (isa<Argument>(V)) {
1349 if (FromBB == &FromBB->getParent()->getEntryBlock())
1350 return true;
1352 // Otherwise, can only export this if it is already exported.
1353 return FuncInfo.isExportedInst(V);
1354 }
1356 // Otherwise, constants can always be exported.
1357 return true;
1358 }
1360 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1361 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1362 const MachineBasicBlock *Dst) const {
1363 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1364 if (!BPI)
1365 return 0;
1366 const BasicBlock *SrcBB = Src->getBasicBlock();
1367 const BasicBlock *DstBB = Dst->getBasicBlock();
1368 return BPI->getEdgeWeight(SrcBB, DstBB);
1369 }
1371 void SelectionDAGBuilder::
1372 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1373 uint32_t Weight /* = 0 */) {
1374 if (!Weight)
1375 Weight = getEdgeWeight(Src, Dst);
1376 Src->addSuccessor(Dst, Weight);
1377 }
1380 static bool InBlock(const Value *V, const BasicBlock *BB) {
1381 if (const Instruction *I = dyn_cast<Instruction>(V))
1382 return I->getParent() == BB;
1383 return true;
1384 }
1386 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1387 /// This function emits a branch and is used at the leaves of an OR or an
1388 /// AND operator tree.
1389 ///
1390 void
1391 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1392 MachineBasicBlock *TBB,
1393 MachineBasicBlock *FBB,
1394 MachineBasicBlock *CurBB,
1395 MachineBasicBlock *SwitchBB,
1396 uint32_t TWeight,
1397 uint32_t FWeight) {
1398 const BasicBlock *BB = CurBB->getBasicBlock();
1400 // If the leaf of the tree is a comparison, merge the condition into
1401 // the caseblock.
1402 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1403 // The operands of the cmp have to be in this block. We don't know
1404 // how to export them from some other block. If this is the first block
1405 // of the sequence, no exporting is needed.
1406 if (CurBB == SwitchBB ||
1407 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1408 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1409 ISD::CondCode Condition;
1410 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1411 Condition = getICmpCondCode(IC->getPredicate());
1412 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1413 Condition = getFCmpCondCode(FC->getPredicate());
1414 if (TM.Options.NoNaNsFPMath)
1415 Condition = getFCmpCodeWithoutNaN(Condition);
1416 } else {
1417 (void)Condition; // silence warning.
1418 llvm_unreachable("Unknown compare instruction");
1419 }
1421 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1422 TBB, FBB, CurBB, TWeight, FWeight);
1423 SwitchCases.push_back(CB);
1424 return;
1425 }
1426 }
1428 // Create a CaseBlock record representing this branch.
1429 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1430 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1431 SwitchCases.push_back(CB);
1432 }
1434 /// Scale down both weights to fit into uint32_t.
1435 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1436 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1437 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1438 NewTrue = NewTrue / Scale;
1439 NewFalse = NewFalse / Scale;
1440 }
1442 /// FindMergedConditions - If Cond is an expression like
1443 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1444 MachineBasicBlock *TBB,
1445 MachineBasicBlock *FBB,
1446 MachineBasicBlock *CurBB,
1447 MachineBasicBlock *SwitchBB,
1448 unsigned Opc, uint32_t TWeight,
1449 uint32_t FWeight) {
1450 // If this node is not part of the or/and tree, emit it as a branch.
1451 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1452 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1453 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1454 BOp->getParent() != CurBB->getBasicBlock() ||
1455 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1456 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1457 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1458 TWeight, FWeight);
1459 return;
1460 }
1462 // Create TmpBB after CurBB.
1463 MachineFunction::iterator BBI = CurBB;
1464 MachineFunction &MF = DAG.getMachineFunction();
1465 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1466 CurBB->getParent()->insert(++BBI, TmpBB);
1468 if (Opc == Instruction::Or) {
1469 // Codegen X | Y as:
1470 // BB1:
1471 // jmp_if_X TBB
1472 // jmp TmpBB
1473 // TmpBB:
1474 // jmp_if_Y TBB
1475 // jmp FBB
1476 //
1478 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1479 // The requirement is that
1480 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1481 // = TrueProb for orignal BB.
1482 // Assuming the orignal weights are A and B, one choice is to set BB1's
1483 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1484 // assumes that
1485 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1486 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1487 // TmpBB, but the math is more complicated.
1489 uint64_t NewTrueWeight = TWeight;
1490 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1491 ScaleWeights(NewTrueWeight, NewFalseWeight);
1492 // Emit the LHS condition.
1493 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1494 NewTrueWeight, NewFalseWeight);
1496 NewTrueWeight = TWeight;
1497 NewFalseWeight = 2 * (uint64_t)FWeight;
1498 ScaleWeights(NewTrueWeight, NewFalseWeight);
1499 // Emit the RHS condition into TmpBB.
1500 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1501 NewTrueWeight, NewFalseWeight);
1502 } else {
1503 assert(Opc == Instruction::And && "Unknown merge op!");
1504 // Codegen X & Y as:
1505 // BB1:
1506 // jmp_if_X TmpBB
1507 // jmp FBB
1508 // TmpBB:
1509 // jmp_if_Y TBB
1510 // jmp FBB
1511 //
1512 // This requires creation of TmpBB after CurBB.
1514 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1515 // The requirement is that
1516 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1517 // = FalseProb for orignal BB.
1518 // Assuming the orignal weights are A and B, one choice is to set BB1's
1519 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1520 // assumes that
1521 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1523 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1524 uint64_t NewFalseWeight = FWeight;
1525 ScaleWeights(NewTrueWeight, NewFalseWeight);
1526 // Emit the LHS condition.
1527 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1528 NewTrueWeight, NewFalseWeight);
1530 NewTrueWeight = 2 * (uint64_t)TWeight;
1531 NewFalseWeight = FWeight;
1532 ScaleWeights(NewTrueWeight, NewFalseWeight);
1533 // Emit the RHS condition into TmpBB.
1534 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1535 NewTrueWeight, NewFalseWeight);
1536 }
1537 }
1539 /// If the set of cases should be emitted as a series of branches, return true.
1540 /// If we should emit this as a bunch of and/or'd together conditions, return
1541 /// false.
1542 bool
1543 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1544 if (Cases.size() != 2) return true;
1546 // If this is two comparisons of the same values or'd or and'd together, they
1547 // will get folded into a single comparison, so don't emit two blocks.
1548 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1549 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1550 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1551 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1552 return false;
1553 }
1555 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1556 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1557 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1558 Cases[0].CC == Cases[1].CC &&
1559 isa<Constant>(Cases[0].CmpRHS) &&
1560 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1561 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1562 return false;
1563 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1564 return false;
1565 }
1567 return true;
1568 }
1570 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1571 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1573 // Update machine-CFG edges.
1574 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1576 // Figure out which block is immediately after the current one.
1577 MachineBasicBlock *NextBlock = nullptr;
1578 MachineFunction::iterator BBI = BrMBB;
1579 if (++BBI != FuncInfo.MF->end())
1580 NextBlock = BBI;
1582 if (I.isUnconditional()) {
1583 // Update machine-CFG edges.
1584 BrMBB->addSuccessor(Succ0MBB);
1586 // If this is not a fall-through branch or optimizations are switched off,
1587 // emit the branch.
1588 if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
1589 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1590 MVT::Other, getControlRoot(),
1591 DAG.getBasicBlock(Succ0MBB)));
1593 return;
1594 }
1596 // If this condition is one of the special cases we handle, do special stuff
1597 // now.
1598 const Value *CondVal = I.getCondition();
1599 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1601 // If this is a series of conditions that are or'd or and'd together, emit
1602 // this as a sequence of branches instead of setcc's with and/or operations.
1603 // As long as jumps are not expensive, this should improve performance.
1604 // For example, instead of something like:
1605 // cmp A, B
1606 // C = seteq
1607 // cmp D, E
1608 // F = setle
1609 // or C, F
1610 // jnz foo
1611 // Emit:
1612 // cmp A, B
1613 // je foo
1614 // cmp D, E
1615 // jle foo
1616 //
1617 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1618 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1619 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1620 BOp->getOpcode() == Instruction::Or)) {
1621 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1622 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1623 getEdgeWeight(BrMBB, Succ1MBB));
1624 // If the compares in later blocks need to use values not currently
1625 // exported from this block, export them now. This block should always
1626 // be the first entry.
1627 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1629 // Allow some cases to be rejected.
1630 if (ShouldEmitAsBranches(SwitchCases)) {
1631 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1632 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1633 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1634 }
1636 // Emit the branch for this block.
1637 visitSwitchCase(SwitchCases[0], BrMBB);
1638 SwitchCases.erase(SwitchCases.begin());
1639 return;
1640 }
1642 // Okay, we decided not to do this, remove any inserted MBB's and clear
1643 // SwitchCases.
1644 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1645 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1647 SwitchCases.clear();
1648 }
1649 }
1651 // Create a CaseBlock record representing this branch.
1652 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1653 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1655 // Use visitSwitchCase to actually insert the fast branch sequence for this
1656 // cond branch.
1657 visitSwitchCase(CB, BrMBB);
1658 }
1660 /// visitSwitchCase - Emits the necessary code to represent a single node in
1661 /// the binary search tree resulting from lowering a switch instruction.
1662 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1663 MachineBasicBlock *SwitchBB) {
1664 SDValue Cond;
1665 SDValue CondLHS = getValue(CB.CmpLHS);
1666 SDLoc dl = getCurSDLoc();
1668 // Build the setcc now.
1669 if (!CB.CmpMHS) {
1670 // Fold "(X == true)" to X and "(X == false)" to !X to
1671 // handle common cases produced by branch lowering.
1672 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1673 CB.CC == ISD::SETEQ)
1674 Cond = CondLHS;
1675 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1676 CB.CC == ISD::SETEQ) {
1677 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1678 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1679 } else
1680 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1681 } else {
1682 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1684 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1685 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1687 SDValue CmpOp = getValue(CB.CmpMHS);
1688 EVT VT = CmpOp.getValueType();
1690 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1691 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1692 ISD::SETLE);
1693 } else {
1694 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1695 VT, CmpOp, DAG.getConstant(Low, VT));
1696 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1697 DAG.getConstant(High-Low, VT), ISD::SETULE);
1698 }
1699 }
1701 // Update successor info
1702 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1703 // TrueBB and FalseBB are always different unless the incoming IR is
1704 // degenerate. This only happens when running llc on weird IR.
1705 if (CB.TrueBB != CB.FalseBB)
1706 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1708 // Set NextBlock to be the MBB immediately after the current one, if any.
1709 // This is used to avoid emitting unnecessary branches to the next block.
1710 MachineBasicBlock *NextBlock = nullptr;
1711 MachineFunction::iterator BBI = SwitchBB;
1712 if (++BBI != FuncInfo.MF->end())
1713 NextBlock = BBI;
1715 // If the lhs block is the next block, invert the condition so that we can
1716 // fall through to the lhs instead of the rhs block.
1717 if (CB.TrueBB == NextBlock) {
1718 std::swap(CB.TrueBB, CB.FalseBB);
1719 SDValue True = DAG.getConstant(1, Cond.getValueType());
1720 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1721 }
1723 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1724 MVT::Other, getControlRoot(), Cond,
1725 DAG.getBasicBlock(CB.TrueBB));
1727 // Insert the false branch. Do this even if it's a fall through branch,
1728 // this makes it easier to do DAG optimizations which require inverting
1729 // the branch condition.
1730 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1731 DAG.getBasicBlock(CB.FalseBB));
1733 DAG.setRoot(BrCond);
1734 }
1736 /// visitJumpTable - Emit JumpTable node in the current MBB
1737 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1738 // Emit the code for the jump table
1739 assert(JT.Reg != -1U && "Should lower JT Header first!");
1740 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1741 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1742 JT.Reg, PTy);
1743 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1744 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1745 MVT::Other, Index.getValue(1),
1746 Table, Index);
1747 DAG.setRoot(BrJumpTable);
1748 }
1750 /// visitJumpTableHeader - This function emits necessary code to produce index
1751 /// in the JumpTable from switch case.
1752 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1753 JumpTableHeader &JTH,
1754 MachineBasicBlock *SwitchBB) {
1755 // Subtract the lowest switch case value from the value being switched on and
1756 // conditional branch to default mbb if the result is greater than the
1757 // difference between smallest and largest cases.
1758 SDValue SwitchOp = getValue(JTH.SValue);
1759 EVT VT = SwitchOp.getValueType();
1760 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1761 DAG.getConstant(JTH.First, VT));
1763 // The SDNode we just created, which holds the value being switched on minus
1764 // the smallest case value, needs to be copied to a virtual register so it
1765 // can be used as an index into the jump table in a subsequent basic block.
1766 // This value may be smaller or larger than the target's pointer type, and
1767 // therefore require extension or truncating.
1768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1769 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
1771 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1772 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1773 JumpTableReg, SwitchOp);
1774 JT.Reg = JumpTableReg;
1776 // Emit the range check for the jump table, and branch to the default block
1777 // for the switch statement if the value being switched on exceeds the largest
1778 // case in the switch.
1779 SDValue CMP =
1780 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1781 Sub.getValueType()),
1782 Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
1784 // Set NextBlock to be the MBB immediately after the current one, if any.
1785 // This is used to avoid emitting unnecessary branches to the next block.
1786 MachineBasicBlock *NextBlock = nullptr;
1787 MachineFunction::iterator BBI = SwitchBB;
1789 if (++BBI != FuncInfo.MF->end())
1790 NextBlock = BBI;
1792 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1793 MVT::Other, CopyTo, CMP,
1794 DAG.getBasicBlock(JT.Default));
1796 if (JT.MBB != NextBlock)
1797 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1798 DAG.getBasicBlock(JT.MBB));
1800 DAG.setRoot(BrCond);
1801 }
1803 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1804 /// tail spliced into a stack protector check success bb.
1805 ///
1806 /// For a high level explanation of how this fits into the stack protector
1807 /// generation see the comment on the declaration of class
1808 /// StackProtectorDescriptor.
1809 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1810 MachineBasicBlock *ParentBB) {
1812 // First create the loads to the guard/stack slot for the comparison.
1813 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1814 EVT PtrTy = TLI.getPointerTy();
1816 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1817 int FI = MFI->getStackProtectorIndex();
1819 const Value *IRGuard = SPD.getGuard();
1820 SDValue GuardPtr = getValue(IRGuard);
1821 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1823 unsigned Align =
1824 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1826 SDValue Guard;
1828 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1829 // guard value from the virtual register holding the value. Otherwise, emit a
1830 // volatile load to retrieve the stack guard value.
1831 unsigned GuardReg = SPD.getGuardReg();
1833 if (GuardReg && TLI.useLoadStackGuardNode())
1834 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1835 PtrTy);
1836 else
1837 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1838 GuardPtr, MachinePointerInfo(IRGuard, 0),
1839 true, false, false, Align);
1841 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1842 StackSlotPtr,
1843 MachinePointerInfo::getFixedStack(FI),
1844 true, false, false, Align);
1846 // Perform the comparison via a subtract/getsetcc.
1847 EVT VT = Guard.getValueType();
1848 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1850 SDValue Cmp =
1851 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1852 Sub.getValueType()),
1853 Sub, DAG.getConstant(0, VT), ISD::SETNE);
1855 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1856 // branch to failure MBB.
1857 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1858 MVT::Other, StackSlot.getOperand(0),
1859 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1860 // Otherwise branch to success MBB.
1861 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1862 MVT::Other, BrCond,
1863 DAG.getBasicBlock(SPD.getSuccessMBB()));
1865 DAG.setRoot(Br);
1866 }
1868 /// Codegen the failure basic block for a stack protector check.
1869 ///
1870 /// A failure stack protector machine basic block consists simply of a call to
1871 /// __stack_chk_fail().
1872 ///
1873 /// For a high level explanation of how this fits into the stack protector
1874 /// generation see the comment on the declaration of class
1875 /// StackProtectorDescriptor.
1876 void
1877 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1878 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1879 SDValue Chain =
1880 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1881 nullptr, 0, false, getCurSDLoc(), false, false).second;
1882 DAG.setRoot(Chain);
1883 }
1885 /// visitBitTestHeader - This function emits necessary code to produce value
1886 /// suitable for "bit tests"
1887 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1888 MachineBasicBlock *SwitchBB) {
1889 // Subtract the minimum value
1890 SDValue SwitchOp = getValue(B.SValue);
1891 EVT VT = SwitchOp.getValueType();
1892 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1893 DAG.getConstant(B.First, VT));
1895 // Check range
1896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1897 SDValue RangeCmp =
1898 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1899 Sub.getValueType()),
1900 Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
1902 // Determine the type of the test operands.
1903 bool UsePtrType = false;
1904 if (!TLI.isTypeLegal(VT))
1905 UsePtrType = true;
1906 else {
1907 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1908 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1909 // Switch table case range are encoded into series of masks.
1910 // Just use pointer type, it's guaranteed to fit.
1911 UsePtrType = true;
1912 break;
1913 }
1914 }
1915 if (UsePtrType) {
1916 VT = TLI.getPointerTy();
1917 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1918 }
1920 B.RegVT = VT.getSimpleVT();
1921 B.Reg = FuncInfo.CreateReg(B.RegVT);
1922 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1923 B.Reg, Sub);
1925 // Set NextBlock to be the MBB immediately after the current one, if any.
1926 // This is used to avoid emitting unnecessary branches to the next block.
1927 MachineBasicBlock *NextBlock = nullptr;
1928 MachineFunction::iterator BBI = SwitchBB;
1929 if (++BBI != FuncInfo.MF->end())
1930 NextBlock = BBI;
1932 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1934 addSuccessorWithWeight(SwitchBB, B.Default);
1935 addSuccessorWithWeight(SwitchBB, MBB);
1937 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1938 MVT::Other, CopyTo, RangeCmp,
1939 DAG.getBasicBlock(B.Default));
1941 if (MBB != NextBlock)
1942 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1943 DAG.getBasicBlock(MBB));
1945 DAG.setRoot(BrRange);
1946 }
1948 /// visitBitTestCase - this function produces one "bit test"
1949 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1950 MachineBasicBlock* NextMBB,
1951 uint32_t BranchWeightToNext,
1952 unsigned Reg,
1953 BitTestCase &B,
1954 MachineBasicBlock *SwitchBB) {
1955 MVT VT = BB.RegVT;
1956 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1957 Reg, VT);
1958 SDValue Cmp;
1959 unsigned PopCount = CountPopulation_64(B.Mask);
1960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1961 if (PopCount == 1) {
1962 // Testing for a single bit; just compare the shift count with what it
1963 // would need to be to shift a 1 bit in that position.
1964 Cmp = DAG.getSetCC(
1965 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1966 DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
1967 } else if (PopCount == BB.Range) {
1968 // There is only one zero bit in the range, test for it directly.
1969 Cmp = DAG.getSetCC(
1970 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1971 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
1972 } else {
1973 // Make desired shift
1974 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1975 DAG.getConstant(1, VT), ShiftOp);
1977 // Emit bit tests and jumps
1978 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1979 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1980 Cmp = DAG.getSetCC(getCurSDLoc(),
1981 TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1982 DAG.getConstant(0, VT), ISD::SETNE);
1983 }
1985 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1986 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1987 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1988 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1990 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1991 MVT::Other, getControlRoot(),
1992 Cmp, DAG.getBasicBlock(B.TargetBB));
1994 // Set NextBlock to be the MBB immediately after the current one, if any.
1995 // This is used to avoid emitting unnecessary branches to the next block.
1996 MachineBasicBlock *NextBlock = nullptr;
1997 MachineFunction::iterator BBI = SwitchBB;
1998 if (++BBI != FuncInfo.MF->end())
1999 NextBlock = BBI;
2001 if (NextMBB != NextBlock)
2002 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
2003 DAG.getBasicBlock(NextMBB));
2005 DAG.setRoot(BrAnd);
2006 }
2008 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2009 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2011 // Retrieve successors.
2012 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2013 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2015 const Value *Callee(I.getCalledValue());
2016 const Function *Fn = dyn_cast<Function>(Callee);
2017 if (isa<InlineAsm>(Callee))
2018 visitInlineAsm(&I);
2019 else if (Fn && Fn->isIntrinsic()) {
2020 switch (Fn->getIntrinsicID()) {
2021 default:
2022 llvm_unreachable("Cannot invoke this intrinsic");
2023 case Intrinsic::donothing:
2024 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2025 break;
2026 case Intrinsic::experimental_patchpoint_void:
2027 case Intrinsic::experimental_patchpoint_i64:
2028 visitPatchpoint(&I, LandingPad);
2029 break;
2030 }
2031 } else
2032 LowerCallTo(&I, getValue(Callee), false, LandingPad);
2034 // If the value of the invoke is used outside of its defining block, make it
2035 // available as a virtual register.
2036 CopyToExportRegsIfNeeded(&I);
2038 // Update successor info
2039 addSuccessorWithWeight(InvokeMBB, Return);
2040 addSuccessorWithWeight(InvokeMBB, LandingPad);
2042 // Drop into normal successor.
2043 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2044 MVT::Other, getControlRoot(),
2045 DAG.getBasicBlock(Return)));
2046 }
2048 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2049 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2050 }
2052 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2053 assert(FuncInfo.MBB->isLandingPad() &&
2054 "Call to landingpad not in landing pad!");
2056 MachineBasicBlock *MBB = FuncInfo.MBB;
2057 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2058 AddLandingPadInfo(LP, MMI, MBB);
2060 // If there aren't registers to copy the values into (e.g., during SjLj
2061 // exceptions), then don't bother to create these DAG nodes.
2062 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2063 if (TLI.getExceptionPointerRegister() == 0 &&
2064 TLI.getExceptionSelectorRegister() == 0)
2065 return;
2067 SmallVector<EVT, 2> ValueVTs;
2068 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2069 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2071 // Get the two live-in registers as SDValues. The physregs have already been
2072 // copied into virtual registers.
2073 SDValue Ops[2];
2074 if (FuncInfo.ExceptionPointerVirtReg) {
2075 Ops[0] = DAG.getZExtOrTrunc(
2076 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2077 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2078 getCurSDLoc(), ValueVTs[0]);
2079 } else {
2080 Ops[0] = DAG.getConstant(0, TLI.getPointerTy());
2081 }
2082 Ops[1] = DAG.getZExtOrTrunc(
2083 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2084 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2085 getCurSDLoc(), ValueVTs[1]);
2087 // Merge into one.
2088 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2089 DAG.getVTList(ValueVTs), Ops);
2090 setValue(&LP, Res);
2091 }
2093 unsigned
2094 SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV,
2095 MachineBasicBlock *LPadBB) {
2096 SDValue Chain = getControlRoot();
2098 // Get the typeid that we will dispatch on later.
2099 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2100 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy());
2101 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
2102 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV);
2103 SDValue Sel = DAG.getConstant(TypeID, TLI.getPointerTy());
2104 Chain = DAG.getCopyToReg(Chain, getCurSDLoc(), VReg, Sel);
2106 // Branch to the main landing pad block.
2107 MachineBasicBlock *ClauseMBB = FuncInfo.MBB;
2108 ClauseMBB->addSuccessor(LPadBB);
2109 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, Chain,
2110 DAG.getBasicBlock(LPadBB)));
2111 return VReg;
2112 }
2114 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2115 /// small case ranges).
2116 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2117 CaseRecVector& WorkList,
2118 const Value* SV,
2119 MachineBasicBlock *Default,
2120 MachineBasicBlock *SwitchBB) {
2121 // Size is the number of Cases represented by this range.
2122 size_t Size = CR.Range.second - CR.Range.first;
2123 if (Size > 3)
2124 return false;
2126 // Get the MachineFunction which holds the current MBB. This is used when
2127 // inserting any additional MBBs necessary to represent the switch.
2128 MachineFunction *CurMF = FuncInfo.MF;
2130 // Figure out which block is immediately after the current one.
2131 MachineBasicBlock *NextBlock = nullptr;
2132 MachineFunction::iterator BBI = CR.CaseBB;
2134 if (++BBI != FuncInfo.MF->end())
2135 NextBlock = BBI;
2137 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2138 // If any two of the cases has the same destination, and if one value
2139 // is the same as the other, but has one bit unset that the other has set,
2140 // use bit manipulation to do two compares at once. For example:
2141 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2142 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2143 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2144 if (Size == 2 && CR.CaseBB == SwitchBB) {
2145 Case &Small = *CR.Range.first;
2146 Case &Big = *(CR.Range.second-1);
2148 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2149 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2150 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2152 // Check that there is only one bit different.
2153 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2154 (SmallValue | BigValue) == BigValue) {
2155 // Isolate the common bit.
2156 APInt CommonBit = BigValue & ~SmallValue;
2157 assert((SmallValue | CommonBit) == BigValue &&
2158 CommonBit.countPopulation() == 1 && "Not a common bit?");
2160 SDValue CondLHS = getValue(SV);
2161 EVT VT = CondLHS.getValueType();
2162 SDLoc DL = getCurSDLoc();
2164 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2165 DAG.getConstant(CommonBit, VT));
2166 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2167 Or, DAG.getConstant(BigValue, VT),
2168 ISD::SETEQ);
2170 // Update successor info.
2171 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2172 addSuccessorWithWeight(SwitchBB, Small.BB,
2173 Small.ExtraWeight + Big.ExtraWeight);
2174 addSuccessorWithWeight(SwitchBB, Default,
2175 // The default destination is the first successor in IR.
2176 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2178 // Insert the true branch.
2179 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2180 getControlRoot(), Cond,
2181 DAG.getBasicBlock(Small.BB));
2183 // Insert the false branch.
2184 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2185 DAG.getBasicBlock(Default));
2187 DAG.setRoot(BrCond);
2188 return true;
2189 }
2190 }
2191 }
2193 // Order cases by weight so the most likely case will be checked first.
2194 uint32_t UnhandledWeights = 0;
2195 if (BPI) {
2196 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2197 uint32_t IWeight = I->ExtraWeight;
2198 UnhandledWeights += IWeight;
2199 for (CaseItr J = CR.Range.first; J < I; ++J) {
2200 uint32_t JWeight = J->ExtraWeight;
2201 if (IWeight > JWeight)
2202 std::swap(*I, *J);
2203 }
2204 }
2205 }
2206 // Rearrange the case blocks so that the last one falls through if possible.
2207 Case &BackCase = *(CR.Range.second-1);
2208 if (Size > 1 &&
2209 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2210 // The last case block won't fall through into 'NextBlock' if we emit the
2211 // branches in this order. See if rearranging a case value would help.
2212 // We start at the bottom as it's the case with the least weight.
2213 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2214 if (I->BB == NextBlock) {
2215 std::swap(*I, BackCase);
2216 break;
2217 }
2218 }
2220 // Create a CaseBlock record representing a conditional branch to
2221 // the Case's target mbb if the value being switched on SV is equal
2222 // to C.
2223 MachineBasicBlock *CurBlock = CR.CaseBB;
2224 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2225 MachineBasicBlock *FallThrough;
2226 if (I != E-1) {
2227 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2228 CurMF->insert(BBI, FallThrough);
2230 // Put SV in a virtual register to make it available from the new blocks.
2231 ExportFromCurrentBlock(SV);
2232 } else {
2233 // If the last case doesn't match, go to the default block.
2234 FallThrough = Default;
2235 }
2237 const Value *RHS, *LHS, *MHS;
2238 ISD::CondCode CC;
2239 if (I->High == I->Low) {
2240 // This is just small small case range :) containing exactly 1 case
2241 CC = ISD::SETEQ;
2242 LHS = SV; RHS = I->High; MHS = nullptr;
2243 } else {
2244 CC = ISD::SETLE;
2245 LHS = I->Low; MHS = SV; RHS = I->High;
2246 }
2248 // The false weight should be sum of all un-handled cases.
2249 UnhandledWeights -= I->ExtraWeight;
2250 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2251 /* me */ CurBlock,
2252 /* trueweight */ I->ExtraWeight,
2253 /* falseweight */ UnhandledWeights);
2255 // If emitting the first comparison, just call visitSwitchCase to emit the
2256 // code into the current block. Otherwise, push the CaseBlock onto the
2257 // vector to be later processed by SDISel, and insert the node's MBB
2258 // before the next MBB.
2259 if (CurBlock == SwitchBB)
2260 visitSwitchCase(CB, SwitchBB);
2261 else
2262 SwitchCases.push_back(CB);
2264 CurBlock = FallThrough;
2265 }
2267 return true;
2268 }
2270 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2271 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2272 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
2273 }
2275 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2276 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2277 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2278 return (LastExt - FirstExt + 1ULL);
2279 }
2281 /// handleJTSwitchCase - Emit jumptable for current switch case range
2282 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2283 CaseRecVector &WorkList,
2284 const Value *SV,
2285 MachineBasicBlock *Default,
2286 MachineBasicBlock *SwitchBB) {
2287 Case& FrontCase = *CR.Range.first;
2288 Case& BackCase = *(CR.Range.second-1);
2290 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2291 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2293 APInt TSize(First.getBitWidth(), 0);
2294 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2295 TSize += I->size();
2297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2298 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
2299 return false;
2301 APInt Range = ComputeRange(First, Last);
2302 // The density is TSize / Range. Require at least 40%.
2303 // It should not be possible for IntTSize to saturate for sane code, but make
2304 // sure we handle Range saturation correctly.
2305 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2306 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2307 if (IntTSize * 10 < IntRange * 4)
2308 return false;
2310 DEBUG(dbgs() << "Lowering jump table\n"
2311 << "First entry: " << First << ". Last entry: " << Last << '\n'
2312 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2314 // Get the MachineFunction which holds the current MBB. This is used when
2315 // inserting any additional MBBs necessary to represent the switch.
2316 MachineFunction *CurMF = FuncInfo.MF;
2318 // Figure out which block is immediately after the current one.
2319 MachineFunction::iterator BBI = CR.CaseBB;
2320 ++BBI;
2322 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2324 // Create a new basic block to hold the code for loading the address
2325 // of the jump table, and jumping to it. Update successor information;
2326 // we will either branch to the default case for the switch, or the jump
2327 // table.
2328 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2329 CurMF->insert(BBI, JumpTableBB);
2331 addSuccessorWithWeight(CR.CaseBB, Default);
2332 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2334 // Build a vector of destination BBs, corresponding to each target
2335 // of the jump table. If the value of the jump table slot corresponds to
2336 // a case statement, push the case's BB onto the vector, otherwise, push
2337 // the default BB.
2338 std::vector<MachineBasicBlock*> DestBBs;
2339 APInt TEI = First;
2340 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2341 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2342 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2344 if (Low.sle(TEI) && TEI.sle(High)) {
2345 DestBBs.push_back(I->BB);
2346 if (TEI==High)
2347 ++I;
2348 } else {
2349 DestBBs.push_back(Default);
2350 }
2351 }
2353 // Calculate weight for each unique destination in CR.
2354 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2355 if (FuncInfo.BPI)
2356 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2357 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2358 DestWeights.find(I->BB);
2359 if (Itr != DestWeights.end())
2360 Itr->second += I->ExtraWeight;
2361 else
2362 DestWeights[I->BB] = I->ExtraWeight;
2363 }
2365 // Update successor info. Add one edge to each unique successor.
2366 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2367 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2368 E = DestBBs.end(); I != E; ++I) {
2369 if (!SuccsHandled[(*I)->getNumber()]) {
2370 SuccsHandled[(*I)->getNumber()] = true;
2371 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2372 DestWeights.find(*I);
2373 addSuccessorWithWeight(JumpTableBB, *I,
2374 Itr != DestWeights.end() ? Itr->second : 0);
2375 }
2376 }
2378 // Create a jump table index for this jump table.
2379 unsigned JTEncoding = TLI.getJumpTableEncoding();
2380 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2381 ->createJumpTableIndex(DestBBs);
2383 // Set the jump table information so that we can codegen it as a second
2384 // MachineBasicBlock
2385 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2386 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2387 if (CR.CaseBB == SwitchBB)
2388 visitJumpTableHeader(JT, JTH, SwitchBB);
2390 JTCases.push_back(JumpTableBlock(JTH, JT));
2391 return true;
2392 }
2394 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2395 /// 2 subtrees.
2396 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2397 CaseRecVector& WorkList,
2398 const Value* SV,
2399 MachineBasicBlock* SwitchBB) {
2400 Case& FrontCase = *CR.Range.first;
2401 Case& BackCase = *(CR.Range.second-1);
2403 // Size is the number of Cases represented by this range.
2404 unsigned Size = CR.Range.second - CR.Range.first;
2406 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2407 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2408 double FMetric = 0;
2409 CaseItr Pivot = CR.Range.first + Size/2;
2411 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2412 // (heuristically) allow us to emit JumpTable's later.
2413 APInt TSize(First.getBitWidth(), 0);
2414 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2415 I!=E; ++I)
2416 TSize += I->size();
2418 APInt LSize = FrontCase.size();
2419 APInt RSize = TSize-LSize;
2420 DEBUG(dbgs() << "Selecting best pivot: \n"
2421 << "First: " << First << ", Last: " << Last <<'\n'
2422 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2423 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2424 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2425 J!=E; ++I, ++J) {
2426 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2427 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2428 APInt Range = ComputeRange(LEnd, RBegin);
2429 assert((Range - 2ULL).isNonNegative() &&
2430 "Invalid case distance");
2431 // Use volatile double here to avoid excess precision issues on some hosts,
2432 // e.g. that use 80-bit X87 registers.
2433 // Only consider the density of sub-ranges that actually have sufficient
2434 // entries to be lowered as a jump table.
2435 volatile double LDensity =
2436 LSize.ult(TLI.getMinimumJumpTableEntries())
2437 ? 0.0
2438 : LSize.roundToDouble() / (LEnd - First + 1ULL).roundToDouble();
2439 volatile double RDensity =
2440 RSize.ult(TLI.getMinimumJumpTableEntries())
2441 ? 0.0
2442 : RSize.roundToDouble() / (Last - RBegin + 1ULL).roundToDouble();
2443 volatile double Metric = Range.logBase2() * (LDensity + RDensity);
2444 // Should always split in some non-trivial place
2445 DEBUG(dbgs() <<"=>Step\n"
2446 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2447 << "LDensity: " << LDensity
2448 << ", RDensity: " << RDensity << '\n'
2449 << "Metric: " << Metric << '\n');
2450 if (FMetric < Metric) {
2451 Pivot = J;
2452 FMetric = Metric;
2453 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2454 }
2456 LSize += J->size();
2457 RSize -= J->size();
2458 }
2460 if (FMetric == 0 || !areJTsAllowed(TLI))
2461 Pivot = CR.Range.first + Size/2;
2462 splitSwitchCase(CR, Pivot, WorkList, SV, SwitchBB);
2463 return true;
2464 }
2466 void SelectionDAGBuilder::splitSwitchCase(CaseRec &CR, CaseItr Pivot,
2467 CaseRecVector &WorkList,
2468 const Value *SV,
2469 MachineBasicBlock *SwitchBB) {
2470 // Get the MachineFunction which holds the current MBB. This is used when
2471 // inserting any additional MBBs necessary to represent the switch.
2472 MachineFunction *CurMF = FuncInfo.MF;
2474 // Figure out which block is immediately after the current one.
2475 MachineFunction::iterator BBI = CR.CaseBB;
2476 ++BBI;
2478 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2480 CaseRange LHSR(CR.Range.first, Pivot);
2481 CaseRange RHSR(Pivot, CR.Range.second);
2482 const Constant *C = Pivot->Low;
2483 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
2485 // We know that we branch to the LHS if the Value being switched on is
2486 // less than the Pivot value, C. We use this to optimize our binary
2487 // tree a bit, by recognizing that if SV is greater than or equal to the
2488 // LHS's Case Value, and that Case Value is exactly one less than the
2489 // Pivot's Value, then we can branch directly to the LHS's Target,
2490 // rather than creating a leaf node for it.
2491 if ((LHSR.second - LHSR.first) == 1 && LHSR.first->High == CR.GE &&
2492 cast<ConstantInt>(C)->getValue() ==
2493 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2494 TrueBB = LHSR.first->BB;
2495 } else {
2496 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2497 CurMF->insert(BBI, TrueBB);
2498 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2500 // Put SV in a virtual register to make it available from the new blocks.
2501 ExportFromCurrentBlock(SV);
2502 }
2504 // Similar to the optimization above, if the Value being switched on is
2505 // known to be less than the Constant CR.LT, and the current Case Value
2506 // is CR.LT - 1, then we can branch directly to the target block for
2507 // the current Case Value, rather than emitting a RHS leaf node for it.
2508 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2509 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2510 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2511 FalseBB = RHSR.first->BB;
2512 } else {
2513 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2514 CurMF->insert(BBI, FalseBB);
2515 WorkList.push_back(CaseRec(FalseBB, CR.LT, C, RHSR));
2517 // Put SV in a virtual register to make it available from the new blocks.
2518 ExportFromCurrentBlock(SV);
2519 }
2521 // Create a CaseBlock record representing a conditional branch to
2522 // the LHS node if the value being switched on SV is less than C.
2523 // Otherwise, branch to LHS.
2524 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
2526 if (CR.CaseBB == SwitchBB)
2527 visitSwitchCase(CB, SwitchBB);
2528 else
2529 SwitchCases.push_back(CB);
2530 }
2532 /// handleBitTestsSwitchCase - if current case range has few destination and
2533 /// range span less, than machine word bitwidth, encode case range into series
2534 /// of masks and emit bit tests with these masks.
2535 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2536 CaseRecVector& WorkList,
2537 const Value* SV,
2538 MachineBasicBlock* Default,
2539 MachineBasicBlock* SwitchBB) {
2540 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2541 EVT PTy = TLI.getPointerTy();
2542 unsigned IntPtrBits = PTy.getSizeInBits();
2544 Case& FrontCase = *CR.Range.first;
2545 Case& BackCase = *(CR.Range.second-1);
2547 // Get the MachineFunction which holds the current MBB. This is used when
2548 // inserting any additional MBBs necessary to represent the switch.
2549 MachineFunction *CurMF = FuncInfo.MF;
2551 // If target does not have legal shift left, do not emit bit tests at all.
2552 if (!TLI.isOperationLegal(ISD::SHL, PTy))
2553 return false;
2555 size_t numCmps = 0;
2556 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2557 // Single case counts one, case range - two.
2558 numCmps += (I->Low == I->High ? 1 : 2);
2559 }
2561 // Count unique destinations
2562 SmallSet<MachineBasicBlock*, 4> Dests;
2563 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2564 Dests.insert(I->BB);
2565 if (Dests.size() > 3)
2566 // Don't bother the code below, if there are too much unique destinations
2567 return false;
2568 }
2569 DEBUG(dbgs() << "Total number of unique destinations: "
2570 << Dests.size() << '\n'
2571 << "Total number of comparisons: " << numCmps << '\n');
2573 // Compute span of values.
2574 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2575 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2576 APInt cmpRange = maxValue - minValue;
2578 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2579 << "Low bound: " << minValue << '\n'
2580 << "High bound: " << maxValue << '\n');
2582 if (cmpRange.uge(IntPtrBits) ||
2583 (!(Dests.size() == 1 && numCmps >= 3) &&
2584 !(Dests.size() == 2 && numCmps >= 5) &&
2585 !(Dests.size() >= 3 && numCmps >= 6)))
2586 return false;
2588 DEBUG(dbgs() << "Emitting bit tests\n");
2589 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2591 // Optimize the case where all the case values fit in a
2592 // word without having to subtract minValue. In this case,
2593 // we can optimize away the subtraction.
2594 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2595 cmpRange = maxValue;
2596 } else {
2597 lowBound = minValue;
2598 }
2600 CaseBitsVector CasesBits;
2601 unsigned i, count = 0;
2603 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2604 MachineBasicBlock* Dest = I->BB;
2605 for (i = 0; i < count; ++i)
2606 if (Dest == CasesBits[i].BB)
2607 break;
2609 if (i == count) {
2610 assert((count < 3) && "Too much destinations to test!");
2611 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2612 count++;
2613 }
2615 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2616 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2618 uint64_t lo = (lowValue - lowBound).getZExtValue();
2619 uint64_t hi = (highValue - lowBound).getZExtValue();
2620 CasesBits[i].ExtraWeight += I->ExtraWeight;
2622 for (uint64_t j = lo; j <= hi; j++) {
2623 CasesBits[i].Mask |= 1ULL << j;
2624 CasesBits[i].Bits++;
2625 }
2627 }
2628 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2630 BitTestInfo BTC;
2632 // Figure out which block is immediately after the current one.
2633 MachineFunction::iterator BBI = CR.CaseBB;
2634 ++BBI;
2636 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2638 DEBUG(dbgs() << "Cases:\n");
2639 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2640 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2641 << ", Bits: " << CasesBits[i].Bits
2642 << ", BB: " << CasesBits[i].BB << '\n');
2644 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2645 CurMF->insert(BBI, CaseBB);
2646 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2647 CaseBB,
2648 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2650 // Put SV in a virtual register to make it available from the new blocks.
2651 ExportFromCurrentBlock(SV);
2652 }
2654 BitTestBlock BTB(lowBound, cmpRange, SV,
2655 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2656 CR.CaseBB, Default, std::move(BTC));
2658 if (CR.CaseBB == SwitchBB)
2659 visitBitTestHeader(BTB, SwitchBB);
2661 BitTestCases.push_back(std::move(BTB));
2663 return true;
2664 }
2666 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2667 void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2668 const SwitchInst& SI) {
2669 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2670 // Start with "simple" cases.
2671 for (SwitchInst::ConstCaseIt i : SI.cases()) {
2672 const BasicBlock *SuccBB = i.getCaseSuccessor();
2673 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2675 uint32_t ExtraWeight =
2676 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2678 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2679 SMBB, ExtraWeight));
2680 }
2681 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2683 // Merge case into clusters
2684 if (Cases.size() >= 2)
2685 // Must recompute end() each iteration because it may be
2686 // invalidated by erase if we hold on to it
2687 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
2688 J != Cases.end(); ) {
2689 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2690 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2691 MachineBasicBlock* nextBB = J->BB;
2692 MachineBasicBlock* currentBB = I->BB;
2694 // If the two neighboring cases go to the same destination, merge them
2695 // into a single case.
2696 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2697 I->High = J->High;
2698 I->ExtraWeight += J->ExtraWeight;
2699 J = Cases.erase(J);
2700 } else {
2701 I = J++;
2702 }
2703 }
2705 DEBUG({
2706 size_t numCmps = 0;
2707 for (auto &I : Cases)
2708 // A range counts double, since it requires two compares.
2709 numCmps += I.Low != I.High ? 2 : 1;
2711 dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2712 << ". Total compares: " << numCmps << '\n';
2713 });
2714 }
2716 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2717 MachineBasicBlock *Last) {
2718 // Update JTCases.
2719 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2720 if (JTCases[i].first.HeaderBB == First)
2721 JTCases[i].first.HeaderBB = Last;
2723 // Update BitTestCases.
2724 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2725 if (BitTestCases[i].Parent == First)
2726 BitTestCases[i].Parent = Last;
2727 }
2729 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2730 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2732 // Figure out which block is immediately after the current one.
2733 MachineBasicBlock *NextBlock = nullptr;
2734 if (SwitchMBB + 1 != FuncInfo.MF->end())
2735 NextBlock = SwitchMBB + 1;
2738 // Create a vector of Cases, sorted so that we can efficiently create a binary
2739 // search tree from them.
2740 CaseVector Cases;
2741 Clusterify(Cases, SI);
2743 // Get the default destination MBB.
2744 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2746 if (isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()) &&
2747 !Cases.empty()) {
2748 // Replace an unreachable default destination with the most popular case
2749 // destination.
2750 DenseMap<const BasicBlock *, unsigned> Popularity;
2751 unsigned MaxPop = 0;
2752 const BasicBlock *MaxBB = nullptr;
2753 for (auto I : SI.cases()) {
2754 const BasicBlock *BB = I.getCaseSuccessor();
2755 if (++Popularity[BB] > MaxPop) {
2756 MaxPop = Popularity[BB];
2757 MaxBB = BB;
2758 }
2759 }
2761 // Set new default.
2762 assert(MaxPop > 0);
2763 assert(MaxBB);
2764 Default = FuncInfo.MBBMap[MaxBB];
2766 // Remove cases that were pointing to the destination that is now the default.
2767 Cases.erase(std::remove_if(Cases.begin(), Cases.end(),
2768 [&](const Case &C) { return C.BB == Default; }),
2769 Cases.end());
2770 }
2772 // If there is only the default destination, go there directly.
2773 if (Cases.empty()) {
2774 // Update machine-CFG edges.
2775 SwitchMBB->addSuccessor(Default);
2777 // If this is not a fall-through branch, emit the branch.
2778 if (Default != NextBlock) {
2779 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2780 getControlRoot(), DAG.getBasicBlock(Default)));
2781 }
2782 return;
2783 }
2785 // Get the Value to be switched on.
2786 const Value *SV = SI.getCondition();
2788 // Push the initial CaseRec onto the worklist
2789 CaseRecVector WorkList;
2790 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
2791 CaseRange(Cases.begin(),Cases.end())));
2793 while (!WorkList.empty()) {
2794 // Grab a record representing a case range to process off the worklist
2795 CaseRec CR = WorkList.back();
2796 WorkList.pop_back();
2798 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2799 continue;
2801 // If the range has few cases (two or less) emit a series of specific
2802 // tests.
2803 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2804 continue;
2806 // If the switch has more than N blocks, and is at least 40% dense, and the
2807 // target supports indirect branches, then emit a jump table rather than
2808 // lowering the switch to a binary tree of conditional branches.
2809 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2810 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2811 continue;
2813 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2814 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2815 handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
2816 }
2817 }
2819 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2820 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2822 // Update machine-CFG edges with unique successors.
2823 SmallSet<BasicBlock*, 32> Done;
2824 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2825 BasicBlock *BB = I.getSuccessor(i);
2826 bool Inserted = Done.insert(BB).second;
2827 if (!Inserted)
2828 continue;
2830 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2831 addSuccessorWithWeight(IndirectBrMBB, Succ);
2832 }
2834 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2835 MVT::Other, getControlRoot(),
2836 getValue(I.getAddress())));
2837 }
2839 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2840 if (DAG.getTarget().Options.TrapUnreachable)
2841 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2842 }
2844 void SelectionDAGBuilder::visitFSub(const User &I) {
2845 // -0.0 - X --> fneg
2846 Type *Ty = I.getType();
2847 if (isa<Constant>(I.getOperand(0)) &&
2848 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2849 SDValue Op2 = getValue(I.getOperand(1));
2850 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2851 Op2.getValueType(), Op2));
2852 return;
2853 }
2855 visitBinary(I, ISD::FSUB);
2856 }
2858 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2859 SDValue Op1 = getValue(I.getOperand(0));
2860 SDValue Op2 = getValue(I.getOperand(1));
2862 bool nuw = false;
2863 bool nsw = false;
2864 bool exact = false;
2865 if (const OverflowingBinaryOperator *OFBinOp =
2866 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2867 nuw = OFBinOp->hasNoUnsignedWrap();
2868 nsw = OFBinOp->hasNoSignedWrap();
2869 }
2870 if (const PossiblyExactOperator *ExactOp =
2871 dyn_cast<const PossiblyExactOperator>(&I))
2872 exact = ExactOp->isExact();
2874 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2875 Op1, Op2, nuw, nsw, exact);
2876 setValue(&I, BinNodeValue);
2877 }
2879 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2880 SDValue Op1 = getValue(I.getOperand(0));
2881 SDValue Op2 = getValue(I.getOperand(1));
2883 EVT ShiftTy =
2884 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2886 // Coerce the shift amount to the right type if we can.
2887 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2888 unsigned ShiftSize = ShiftTy.getSizeInBits();
2889 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2890 SDLoc DL = getCurSDLoc();
2892 // If the operand is smaller than the shift count type, promote it.
2893 if (ShiftSize > Op2Size)
2894 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2896 // If the operand is larger than the shift count type but the shift
2897 // count type has enough bits to represent any shift value, truncate
2898 // it now. This is a common case and it exposes the truncate to
2899 // optimization early.
2900 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2901 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2902 // Otherwise we'll need to temporarily settle for some other convenient
2903 // type. Type legalization will make adjustments once the shiftee is split.
2904 else
2905 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2906 }
2908 bool nuw = false;
2909 bool nsw = false;
2910 bool exact = false;
2912 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2914 if (const OverflowingBinaryOperator *OFBinOp =
2915 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2916 nuw = OFBinOp->hasNoUnsignedWrap();
2917 nsw = OFBinOp->hasNoSignedWrap();
2918 }
2919 if (const PossiblyExactOperator *ExactOp =
2920 dyn_cast<const PossiblyExactOperator>(&I))
2921 exact = ExactOp->isExact();
2922 }
2924 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2925 nuw, nsw, exact);
2926 setValue(&I, Res);
2927 }
2929 void SelectionDAGBuilder::visitSDiv(const User &I) {
2930 SDValue Op1 = getValue(I.getOperand(0));
2931 SDValue Op2 = getValue(I.getOperand(1));
2933 // Turn exact SDivs into multiplications.
2934 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2935 // exact bit.
2936 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2937 !isa<ConstantSDNode>(Op1) &&
2938 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2939 setValue(&I, DAG.getTargetLoweringInfo()
2940 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2941 else
2942 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2943 Op1, Op2));
2944 }
2946 void SelectionDAGBuilder::visitICmp(const User &I) {
2947 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2948 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2949 predicate = IC->getPredicate();
2950 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2951 predicate = ICmpInst::Predicate(IC->getPredicate());
2952 SDValue Op1 = getValue(I.getOperand(0));
2953 SDValue Op2 = getValue(I.getOperand(1));
2954 ISD::CondCode Opcode = getICmpCondCode(predicate);
2956 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2957 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2958 }
2960 void SelectionDAGBuilder::visitFCmp(const User &I) {
2961 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2962 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2963 predicate = FC->getPredicate();
2964 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2965 predicate = FCmpInst::Predicate(FC->getPredicate());
2966 SDValue Op1 = getValue(I.getOperand(0));
2967 SDValue Op2 = getValue(I.getOperand(1));
2968 ISD::CondCode Condition = getFCmpCondCode(predicate);
2969 if (TM.Options.NoNaNsFPMath)
2970 Condition = getFCmpCodeWithoutNaN(Condition);
2971 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2972 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2973 }
2975 void SelectionDAGBuilder::visitSelect(const User &I) {
2976 SmallVector<EVT, 4> ValueVTs;
2977 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2978 unsigned NumValues = ValueVTs.size();
2979 if (NumValues == 0) return;
2981 SmallVector<SDValue, 4> Values(NumValues);
2982 SDValue Cond = getValue(I.getOperand(0));
2983 SDValue TrueVal = getValue(I.getOperand(1));
2984 SDValue FalseVal = getValue(I.getOperand(2));
2985 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2986 ISD::VSELECT : ISD::SELECT;
2988 for (unsigned i = 0; i != NumValues; ++i)
2989 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2990 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2991 Cond,
2992 SDValue(TrueVal.getNode(),
2993 TrueVal.getResNo() + i),
2994 SDValue(FalseVal.getNode(),
2995 FalseVal.getResNo() + i));
2997 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2998 DAG.getVTList(ValueVTs), Values));
2999 }
3001 void SelectionDAGBuilder::visitTrunc(const User &I) {
3002 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3003 SDValue N = getValue(I.getOperand(0));
3004 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3005 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3006 }
3008 void SelectionDAGBuilder::visitZExt(const User &I) {
3009 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3010 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3011 SDValue N = getValue(I.getOperand(0));
3012 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3013 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3014 }
3016 void SelectionDAGBuilder::visitSExt(const User &I) {
3017 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3018 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3019 SDValue N = getValue(I.getOperand(0));
3020 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3021 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3022 }
3024 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3025 // FPTrunc is never a no-op cast, no need to check
3026 SDValue N = getValue(I.getOperand(0));
3027 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3028 EVT DestVT = TLI.getValueType(I.getType());
3029 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
3030 DAG.getTargetConstant(0, TLI.getPointerTy())));
3031 }
3033 void SelectionDAGBuilder::visitFPExt(const User &I) {
3034 // FPExt is never a no-op cast, no need to check
3035 SDValue N = getValue(I.getOperand(0));
3036 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3037 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3038 }
3040 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3041 // FPToUI is never a no-op cast, no need to check
3042 SDValue N = getValue(I.getOperand(0));
3043 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3044 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3045 }
3047 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3048 // FPToSI is never a no-op cast, no need to check
3049 SDValue N = getValue(I.getOperand(0));
3050 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3051 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3052 }
3054 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3055 // UIToFP is never a no-op cast, no need to check
3056 SDValue N = getValue(I.getOperand(0));
3057 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3058 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3059 }
3061 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3062 // SIToFP is never a no-op cast, no need to check
3063 SDValue N = getValue(I.getOperand(0));
3064 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3065 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3066 }
3068 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3069 // What to do depends on the size of the integer and the size of the pointer.
3070 // We can either truncate, zero extend, or no-op, accordingly.
3071 SDValue N = getValue(I.getOperand(0));
3072 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3073 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3074 }
3076 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3077 // What to do depends on the size of the integer and the size of the pointer.
3078 // We can either truncate, zero extend, or no-op, accordingly.
3079 SDValue N = getValue(I.getOperand(0));
3080 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3081 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3082 }
3084 void SelectionDAGBuilder::visitBitCast(const User &I) {
3085 SDValue N = getValue(I.getOperand(0));
3086 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3088 // BitCast assures us that source and destination are the same size so this is
3089 // either a BITCAST or a no-op.
3090 if (DestVT != N.getValueType())
3091 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
3092 DestVT, N)); // convert types.
3093 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3094 // might fold any kind of constant expression to an integer constant and that
3095 // is not what we are looking for. Only regcognize a bitcast of a genuine
3096 // constant integer as an opaque constant.
3097 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3098 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3099 /*isOpaque*/true));
3100 else
3101 setValue(&I, N); // noop cast.
3102 }
3104 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3106 const Value *SV = I.getOperand(0);
3107 SDValue N = getValue(SV);
3108 EVT DestVT = TLI.getValueType(I.getType());
3110 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3111 unsigned DestAS = I.getType()->getPointerAddressSpace();
3113 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3114 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3116 setValue(&I, N);
3117 }
3119 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3120 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3121 SDValue InVec = getValue(I.getOperand(0));
3122 SDValue InVal = getValue(I.getOperand(1));
3123 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3124 getCurSDLoc(), TLI.getVectorIdxTy());
3125 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3126 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
3127 }
3129 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3130 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3131 SDValue InVec = getValue(I.getOperand(0));
3132 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3133 getCurSDLoc(), TLI.getVectorIdxTy());
3134 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3135 TLI.getValueType(I.getType()), InVec, InIdx));
3136 }
3138 // Utility for visitShuffleVector - Return true if every element in Mask,
3139 // beginning from position Pos and ending in Pos+Size, falls within the
3140 // specified sequential range [L, L+Pos). or is undef.
3141 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3142 unsigned Pos, unsigned Size, int Low) {
3143 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3144 if (Mask[i] >= 0 && Mask[i] != Low)
3145 return false;
3146 return true;
3147 }
3149 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3150 SDValue Src1 = getValue(I.getOperand(0));
3151 SDValue Src2 = getValue(I.getOperand(1));
3153 SmallVector<int, 8> Mask;
3154 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3155 unsigned MaskNumElts = Mask.size();
3157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3158 EVT VT = TLI.getValueType(I.getType());