1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SDNodeDbgValue.h"
16 #include "SelectionDAGBuilder.h"
17 #include "FunctionLoweringInfo.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/IntrinsicInst.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/Module.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/FastISel.h"
35 #include "llvm/CodeGen/GCStrategy.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineJumpTableInfo.h"
41 #include "llvm/CodeGen/MachineModuleInfo.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/PseudoSourceValue.h"
44 #include "llvm/CodeGen/SelectionDAG.h"
45 #include "llvm/Analysis/DebugInfo.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Target/TargetFrameInfo.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetIntrinsicInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
62 /// LimitFloatPrecision - Generate low-precision inline sequences for
63 /// some float libcalls (6, 8 or 12 bits).
64 static unsigned LimitFloatPrecision;
66 static cl::opt<unsigned, true>
67 LimitFPPrecision("limit-float-precision",
68 cl::desc("Generate low-precision inline sequences "
69 "for some float libcalls"),
70 cl::location(LimitFloatPrecision),
74 /// RegsForValue - This struct represents the registers (physical or virtual)
75 /// that a particular set of values is assigned, and the type information
76 /// about the value. The most common situation is to represent one value at a
77 /// time, but struct or array values are handled element-wise as multiple
78 /// values. The splitting of aggregates is performed recursively, so that we
79 /// never have aggregate-typed registers. The values at this point do not
80 /// necessarily have legal types, so each value may require one or more
81 /// registers of some legal type.
84 /// TLI - The TargetLowering object.
86 const TargetLowering *TLI;
88 /// ValueVTs - The value types of the values, which may not be legal, and
89 /// may need be promoted or synthesized from one or more registers.
91 SmallVector<EVT, 4> ValueVTs;
93 /// RegVTs - The value types of the registers. This is the same size as
94 /// ValueVTs and it records, for each value, what the type of the assigned
95 /// register or registers are. (Individual values are never synthesized
96 /// from more than one type of register.)
98 /// With virtual registers, the contents of RegVTs is redundant with TLI's
99 /// getRegisterType member function, however when with physical registers
100 /// it is necessary to have a separate record of the types.
102 SmallVector<EVT, 4> RegVTs;
104 /// Regs - This list holds the registers assigned to the values.
105 /// Each legal or promoted value requires one register, and each
106 /// expanded value requires multiple registers.
108 SmallVector<unsigned, 4> Regs;
110 RegsForValue() : TLI(0) {}
112 RegsForValue(const TargetLowering &tli,
113 const SmallVector<unsigned, 4> ®s,
114 EVT regvt, EVT valuevt)
115 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
116 RegsForValue(const TargetLowering &tli,
117 const SmallVector<unsigned, 4> ®s,
118 const SmallVector<EVT, 4> ®vts,
119 const SmallVector<EVT, 4> &valuevts)
120 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
121 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
122 unsigned Reg, const Type *Ty) : TLI(&tli) {
123 ComputeValueVTs(tli, Ty, ValueVTs);
125 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
126 EVT ValueVT = ValueVTs[Value];
127 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
128 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
129 for (unsigned i = 0; i != NumRegs; ++i)
130 Regs.push_back(Reg + i);
131 RegVTs.push_back(RegisterVT);
136 /// areValueTypesLegal - Return true if types of all the values are legal.
137 bool areValueTypesLegal() {
138 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
139 EVT RegisterVT = RegVTs[Value];
140 if (!TLI->isTypeLegal(RegisterVT))
147 /// append - Add the specified values to this one.
148 void append(const RegsForValue &RHS) {
150 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
151 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
152 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
156 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
157 /// this value and returns the result as a ValueVTs value. This uses
158 /// Chain/Flag as the input and updates them for the output Chain/Flag.
159 /// If the Flag pointer is NULL, no flag is used.
160 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
161 SDValue &Chain, SDValue *Flag) const;
163 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
164 /// specified value into the registers specified by this object. This uses
165 /// Chain/Flag as the input and updates them for the output Chain/Flag.
166 /// If the Flag pointer is NULL, no flag is used.
167 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
168 SDValue &Chain, SDValue *Flag) const;
170 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
171 /// operand list. This adds the code marker, matching input operand index
172 /// (if applicable), and includes the number of values added into it.
173 void AddInlineAsmOperands(unsigned Kind,
174 bool HasMatching, unsigned MatchingIdx,
176 std::vector<SDValue> &Ops) const;
180 /// getCopyFromParts - Create a value that contains the specified legal parts
181 /// combined into the value they represent. If the parts combine to a type
182 /// larger then ValueVT then AssertOp can be used to specify whether the extra
183 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
184 /// (ISD::AssertSext).
185 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
186 const SDValue *Parts,
187 unsigned NumParts, EVT PartVT, EVT ValueVT,
188 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
189 assert(NumParts > 0 && "No parts to assemble!");
190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
191 SDValue Val = Parts[0];
194 // Assemble the value from multiple parts.
195 if (!ValueVT.isVector() && ValueVT.isInteger()) {
196 unsigned PartBits = PartVT.getSizeInBits();
197 unsigned ValueBits = ValueVT.getSizeInBits();
199 // Assemble the power of 2 part.
200 unsigned RoundParts = NumParts & (NumParts - 1) ?
201 1 << Log2_32(NumParts) : NumParts;
202 unsigned RoundBits = PartBits * RoundParts;
203 EVT RoundVT = RoundBits == ValueBits ?
204 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
207 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
209 if (RoundParts > 2) {
210 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts / 2,
212 Hi = getCopyFromParts(DAG, dl, Parts + RoundParts / 2,
213 RoundParts / 2, PartVT, HalfVT);
215 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
216 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
219 if (TLI.isBigEndian())
222 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
224 if (RoundParts < NumParts) {
225 // Assemble the trailing non-power-of-2 part.
226 unsigned OddParts = NumParts - RoundParts;
227 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
228 Hi = getCopyFromParts(DAG, dl,
229 Parts + RoundParts, OddParts, PartVT, OddVT);
231 // Combine the round and odd parts.
233 if (TLI.isBigEndian())
235 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
236 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
237 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
238 DAG.getConstant(Lo.getValueType().getSizeInBits(),
239 TLI.getPointerTy()));
240 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
241 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
243 } else if (ValueVT.isVector()) {
244 // Handle a multi-element vector.
245 EVT IntermediateVT, RegisterVT;
246 unsigned NumIntermediates;
248 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
249 NumIntermediates, RegisterVT);
250 assert(NumRegs == NumParts
251 && "Part count doesn't match vector breakdown!");
252 NumParts = NumRegs; // Silence a compiler warning.
253 assert(RegisterVT == PartVT
254 && "Part type doesn't match vector breakdown!");
255 assert(RegisterVT == Parts[0].getValueType() &&
256 "Part type doesn't match part!");
258 // Assemble the parts into intermediate operands.
259 SmallVector<SDValue, 8> Ops(NumIntermediates);
260 if (NumIntermediates == NumParts) {
261 // If the register was not expanded, truncate or copy the value,
263 for (unsigned i = 0; i != NumParts; ++i)
264 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
265 PartVT, IntermediateVT);
266 } else if (NumParts > 0) {
267 // If the intermediate type was expanded, build the intermediate
268 // operands from the parts.
269 assert(NumParts % NumIntermediates == 0 &&
270 "Must expand into a divisible number of parts!");
271 unsigned Factor = NumParts / NumIntermediates;
272 for (unsigned i = 0; i != NumIntermediates; ++i)
273 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
274 PartVT, IntermediateVT);
277 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
278 // intermediate operands.
279 Val = DAG.getNode(IntermediateVT.isVector() ?
280 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
281 ValueVT, &Ops[0], NumIntermediates);
282 } else if (PartVT.isFloatingPoint()) {
283 // FP split into multiple FP parts (for ppcf128)
284 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
287 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
288 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
289 if (TLI.isBigEndian())
291 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
293 // FP split into integer parts (soft fp)
294 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
295 !PartVT.isVector() && "Unexpected split");
296 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
297 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
301 // There is now one part, held in Val. Correct it to match ValueVT.
302 PartVT = Val.getValueType();
304 if (PartVT == ValueVT)
307 if (PartVT.isVector()) {
308 assert(ValueVT.isVector() && "Unknown vector conversion!");
309 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
312 if (ValueVT.isVector()) {
313 assert(ValueVT.getVectorElementType() == PartVT &&
314 ValueVT.getVectorNumElements() == 1 &&
315 "Only trivial scalar-to-vector conversions should get here!");
316 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
319 if (PartVT.isInteger() &&
320 ValueVT.isInteger()) {
321 if (ValueVT.bitsLT(PartVT)) {
322 // For a truncate, see if we have any information to
323 // indicate whether the truncated bits will always be
324 // zero or sign-extension.
325 if (AssertOp != ISD::DELETED_NODE)
326 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
327 DAG.getValueType(ValueVT));
328 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
330 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
334 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
335 if (ValueVT.bitsLT(Val.getValueType())) {
336 // FP_ROUND's are always exact here.
337 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
338 DAG.getIntPtrConstant(1));
341 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
344 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
345 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
347 llvm_unreachable("Unknown mismatch!");
351 /// getCopyToParts - Create a series of nodes that contain the specified value
352 /// split into legal parts. If the parts contain more bits than Val, then, for
353 /// integers, ExtendKind can be used to specify how to generate the extra bits.
354 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl,
355 SDValue Val, SDValue *Parts, unsigned NumParts,
357 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
359 EVT PtrVT = TLI.getPointerTy();
360 EVT ValueVT = Val.getValueType();
361 unsigned PartBits = PartVT.getSizeInBits();
362 unsigned OrigNumParts = NumParts;
363 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
368 if (!ValueVT.isVector()) {
369 if (PartVT == ValueVT) {
370 assert(NumParts == 1 && "No-op copy with multiple parts!");
375 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
376 // If the parts cover more bits than the value has, promote the value.
377 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
378 assert(NumParts == 1 && "Do not know what to promote to!");
379 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
380 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
381 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
382 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
384 llvm_unreachable("Unknown mismatch!");
386 } else if (PartBits == ValueVT.getSizeInBits()) {
387 // Different types of the same size.
388 assert(NumParts == 1 && PartVT != ValueVT);
389 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
390 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
391 // If the parts cover less bits than value has, truncate the value.
392 if (PartVT.isInteger() && ValueVT.isInteger()) {
393 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
394 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
396 llvm_unreachable("Unknown mismatch!");
400 // The value may have changed - recompute ValueVT.
401 ValueVT = Val.getValueType();
402 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
403 "Failed to tile the value with PartVT!");
406 assert(PartVT == ValueVT && "Type conversion failed!");
411 // Expand the value into multiple parts.
412 if (NumParts & (NumParts - 1)) {
413 // The number of parts is not a power of 2. Split off and copy the tail.
414 assert(PartVT.isInteger() && ValueVT.isInteger() &&
415 "Do not know what to expand to!");
416 unsigned RoundParts = 1 << Log2_32(NumParts);
417 unsigned RoundBits = RoundParts * PartBits;
418 unsigned OddParts = NumParts - RoundParts;
419 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
420 DAG.getConstant(RoundBits,
421 TLI.getPointerTy()));
422 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts,
425 if (TLI.isBigEndian())
426 // The odd parts were reversed by getCopyToParts - unreverse them.
427 std::reverse(Parts + RoundParts, Parts + NumParts);
429 NumParts = RoundParts;
430 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
431 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
434 // The number of parts is a power of 2. Repeatedly bisect the value using
436 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
437 EVT::getIntegerVT(*DAG.getContext(),
438 ValueVT.getSizeInBits()),
441 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
442 for (unsigned i = 0; i < NumParts; i += StepSize) {
443 unsigned ThisBits = StepSize * PartBits / 2;
444 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
445 SDValue &Part0 = Parts[i];
446 SDValue &Part1 = Parts[i+StepSize/2];
448 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
450 DAG.getConstant(1, PtrVT));
451 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
453 DAG.getConstant(0, PtrVT));
455 if (ThisBits == PartBits && ThisVT != PartVT) {
456 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
458 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
464 if (TLI.isBigEndian())
465 std::reverse(Parts, Parts + OrigNumParts);
472 if (PartVT != ValueVT) {
473 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
474 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
476 assert(ValueVT.getVectorElementType() == PartVT &&
477 ValueVT.getVectorNumElements() == 1 &&
478 "Only trivial vector-to-scalar conversions should get here!");
479 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
481 DAG.getConstant(0, PtrVT));
489 // Handle a multi-element vector.
490 EVT IntermediateVT, RegisterVT;
491 unsigned NumIntermediates;
492 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
493 IntermediateVT, NumIntermediates, RegisterVT);
494 unsigned NumElements = ValueVT.getVectorNumElements();
496 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
497 NumParts = NumRegs; // Silence a compiler warning.
498 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
500 // Split the vector into intermediate operands.
501 SmallVector<SDValue, 8> Ops(NumIntermediates);
502 for (unsigned i = 0; i != NumIntermediates; ++i) {
503 if (IntermediateVT.isVector())
504 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
506 DAG.getConstant(i * (NumElements / NumIntermediates),
509 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
511 DAG.getConstant(i, PtrVT));
514 // Split the intermediate operands into legal parts.
515 if (NumParts == NumIntermediates) {
516 // If the register was not expanded, promote or copy the value,
518 for (unsigned i = 0; i != NumParts; ++i)
519 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
520 } else if (NumParts > 0) {
521 // If the intermediate type was expanded, split each the value into
523 assert(NumParts % NumIntermediates == 0 &&
524 "Must expand into a divisible number of parts!");
525 unsigned Factor = NumParts / NumIntermediates;
526 for (unsigned i = 0; i != NumIntermediates; ++i)
527 getCopyToParts(DAG, dl, Ops[i], &Parts[i*Factor], Factor, PartVT);
532 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
535 TD = DAG.getTarget().getTargetData();
538 /// clear - Clear out the current SelectionDAG and the associated
539 /// state and prepare this SelectionDAGBuilder object to be used
540 /// for a new block. This doesn't clear out information about
541 /// additional blocks that are needed to complete switch lowering
542 /// or PHI node updating; that information is cleared out as it is
544 void SelectionDAGBuilder::clear() {
546 PendingLoads.clear();
547 PendingExports.clear();
550 CurDebugLoc = DebugLoc();
554 /// getRoot - Return the current virtual root of the Selection DAG,
555 /// flushing any PendingLoad items. This must be done before emitting
556 /// a store or any other node that may need to be ordered after any
557 /// prior load instructions.
559 SDValue SelectionDAGBuilder::getRoot() {
560 if (PendingLoads.empty())
561 return DAG.getRoot();
563 if (PendingLoads.size() == 1) {
564 SDValue Root = PendingLoads[0];
566 PendingLoads.clear();
570 // Otherwise, we have to make a token factor node.
571 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
572 &PendingLoads[0], PendingLoads.size());
573 PendingLoads.clear();
578 /// getControlRoot - Similar to getRoot, but instead of flushing all the
579 /// PendingLoad items, flush all the PendingExports items. It is necessary
580 /// to do this before emitting a terminator instruction.
582 SDValue SelectionDAGBuilder::getControlRoot() {
583 SDValue Root = DAG.getRoot();
585 if (PendingExports.empty())
588 // Turn all of the CopyToReg chains into one factored node.
589 if (Root.getOpcode() != ISD::EntryToken) {
590 unsigned i = 0, e = PendingExports.size();
591 for (; i != e; ++i) {
592 assert(PendingExports[i].getNode()->getNumOperands() > 1);
593 if (PendingExports[i].getNode()->getOperand(0) == Root)
594 break; // Don't add the root if we already indirectly depend on it.
598 PendingExports.push_back(Root);
601 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
603 PendingExports.size());
604 PendingExports.clear();
609 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
610 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
611 DAG.AssignOrdering(Node, SDNodeOrder);
613 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
614 AssignOrderingToNode(Node->getOperand(I).getNode());
617 void SelectionDAGBuilder::visit(const Instruction &I) {
618 CurDebugLoc = I.getDebugLoc();
620 visit(I.getOpcode(), I);
622 if (!isa<TerminatorInst>(&I) && !HasTailCall)
623 CopyToExportRegsIfNeeded(&I);
625 CurDebugLoc = DebugLoc();
628 void SelectionDAGBuilder::visitPHI(const PHINode &) {
629 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
632 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
633 // Note: this doesn't use InstVisitor, because it has to work with
634 // ConstantExpr's in addition to instructions.
636 default: llvm_unreachable("Unknown instruction type encountered!");
637 // Build the switch statement using the Instruction.def file.
638 #define HANDLE_INST(NUM, OPCODE, CLASS) \
639 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
640 #include "llvm/Instruction.def"
643 // Assign the ordering to the freshly created DAG nodes.
644 if (NodeMap.count(&I)) {
646 AssignOrderingToNode(getValue(&I).getNode());
650 SDValue SelectionDAGBuilder::getValue(const Value *V) {
651 SDValue &N = NodeMap[V];
652 if (N.getNode()) return N;
654 if (const Constant *C = dyn_cast<Constant>(V)) {
655 EVT VT = TLI.getValueType(V->getType(), true);
657 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
658 return N = DAG.getConstant(*CI, VT);
660 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
661 return N = DAG.getGlobalAddress(GV, VT);
663 if (isa<ConstantPointerNull>(C))
664 return N = DAG.getConstant(0, TLI.getPointerTy());
666 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
667 return N = DAG.getConstantFP(*CFP, VT);
669 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
670 return N = DAG.getUNDEF(VT);
672 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
673 visit(CE->getOpcode(), *CE);
674 SDValue N1 = NodeMap[V];
675 assert(N1.getNode() && "visit didn't populate the NodeMap!");
679 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
680 SmallVector<SDValue, 4> Constants;
681 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
683 SDNode *Val = getValue(*OI).getNode();
684 // If the operand is an empty aggregate, there are no values.
686 // Add each leaf value from the operand to the Constants list
687 // to form a flattened list of all the values.
688 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
689 Constants.push_back(SDValue(Val, i));
692 return DAG.getMergeValues(&Constants[0], Constants.size(),
696 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
697 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
698 "Unknown struct or array constant!");
700 SmallVector<EVT, 4> ValueVTs;
701 ComputeValueVTs(TLI, C->getType(), ValueVTs);
702 unsigned NumElts = ValueVTs.size();
704 return SDValue(); // empty struct
705 SmallVector<SDValue, 4> Constants(NumElts);
706 for (unsigned i = 0; i != NumElts; ++i) {
707 EVT EltVT = ValueVTs[i];
708 if (isa<UndefValue>(C))
709 Constants[i] = DAG.getUNDEF(EltVT);
710 else if (EltVT.isFloatingPoint())
711 Constants[i] = DAG.getConstantFP(0, EltVT);
713 Constants[i] = DAG.getConstant(0, EltVT);
716 return DAG.getMergeValues(&Constants[0], NumElts,
720 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
721 return DAG.getBlockAddress(BA, VT);
723 const VectorType *VecTy = cast<VectorType>(V->getType());
724 unsigned NumElements = VecTy->getNumElements();
726 // Now that we know the number and type of the elements, get that number of
727 // elements into the Ops array based on what kind of constant it is.
728 SmallVector<SDValue, 16> Ops;
729 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
730 for (unsigned i = 0; i != NumElements; ++i)
731 Ops.push_back(getValue(CP->getOperand(i)));
733 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
734 EVT EltVT = TLI.getValueType(VecTy->getElementType());
737 if (EltVT.isFloatingPoint())
738 Op = DAG.getConstantFP(0, EltVT);
740 Op = DAG.getConstant(0, EltVT);
741 Ops.assign(NumElements, Op);
744 // Create a BUILD_VECTOR node.
745 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
746 VT, &Ops[0], Ops.size());
749 // If this is a static alloca, generate it as the frameindex instead of
751 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
752 DenseMap<const AllocaInst*, int>::iterator SI =
753 FuncInfo.StaticAllocaMap.find(AI);
754 if (SI != FuncInfo.StaticAllocaMap.end())
755 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
758 unsigned InReg = FuncInfo.ValueMap[V];
759 assert(InReg && "Value not in map!");
761 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
762 SDValue Chain = DAG.getEntryNode();
763 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
766 /// Get the EVTs and ArgFlags collections that represent the legalized return
767 /// type of the given function. This does not require a DAG or a return value,
768 /// and is suitable for use before any DAGs for the function are constructed.
769 static void getReturnInfo(const Type* ReturnType,
770 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
771 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
772 const TargetLowering &TLI,
773 SmallVectorImpl<uint64_t> *Offsets = 0) {
774 SmallVector<EVT, 4> ValueVTs;
775 ComputeValueVTs(TLI, ReturnType, ValueVTs);
776 unsigned NumValues = ValueVTs.size();
777 if (NumValues == 0) return;
780 for (unsigned j = 0, f = NumValues; j != f; ++j) {
781 EVT VT = ValueVTs[j];
782 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
784 if (attr & Attribute::SExt)
785 ExtendKind = ISD::SIGN_EXTEND;
786 else if (attr & Attribute::ZExt)
787 ExtendKind = ISD::ZERO_EXTEND;
789 // FIXME: C calling convention requires the return type to be promoted to
790 // at least 32-bit. But this is not necessary for non-C calling
791 // conventions. The frontend should mark functions whose return values
792 // require promoting with signext or zeroext attributes.
793 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
794 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
795 if (VT.bitsLT(MinVT))
799 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
800 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
801 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
802 PartVT.getTypeForEVT(ReturnType->getContext()));
804 // 'inreg' on function refers to return value
805 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
806 if (attr & Attribute::InReg)
809 // Propagate extension type if any
810 if (attr & Attribute::SExt)
812 else if (attr & Attribute::ZExt)
815 for (unsigned i = 0; i < NumParts; ++i) {
816 OutVTs.push_back(PartVT);
817 OutFlags.push_back(Flags);
820 Offsets->push_back(Offset);
827 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
828 SDValue Chain = getControlRoot();
829 SmallVector<ISD::OutputArg, 8> Outs;
830 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
832 if (!FLI.CanLowerReturn) {
833 unsigned DemoteReg = FLI.DemoteRegister;
834 const Function *F = I.getParent()->getParent();
836 // Emit a store of the return value through the virtual register.
837 // Leave Outs empty so that LowerReturn won't try to load return
838 // registers the usual way.
839 SmallVector<EVT, 1> PtrValueVTs;
840 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
843 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
844 SDValue RetOp = getValue(I.getOperand(0));
846 SmallVector<EVT, 4> ValueVTs;
847 SmallVector<uint64_t, 4> Offsets;
848 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
849 unsigned NumValues = ValueVTs.size();
851 SmallVector<SDValue, 4> Chains(NumValues);
852 EVT PtrVT = PtrValueVTs[0];
853 for (unsigned i = 0; i != NumValues; ++i) {
854 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
855 DAG.getConstant(Offsets[i], PtrVT));
857 DAG.getStore(Chain, getCurDebugLoc(),
858 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
859 Add, NULL, Offsets[i], false, false, 0);
862 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
863 MVT::Other, &Chains[0], NumValues);
864 } else if (I.getNumOperands() != 0) {
865 SmallVector<EVT, 4> ValueVTs;
866 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
867 unsigned NumValues = ValueVTs.size();
869 SDValue RetOp = getValue(I.getOperand(0));
870 for (unsigned j = 0, f = NumValues; j != f; ++j) {
871 EVT VT = ValueVTs[j];
873 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
875 const Function *F = I.getParent()->getParent();
876 if (F->paramHasAttr(0, Attribute::SExt))
877 ExtendKind = ISD::SIGN_EXTEND;
878 else if (F->paramHasAttr(0, Attribute::ZExt))
879 ExtendKind = ISD::ZERO_EXTEND;
881 // FIXME: C calling convention requires the return type to be promoted
882 // to at least 32-bit. But this is not necessary for non-C calling
883 // conventions. The frontend should mark functions whose return values
884 // require promoting with signext or zeroext attributes.
885 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
886 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
887 if (VT.bitsLT(MinVT))
891 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
892 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
893 SmallVector<SDValue, 4> Parts(NumParts);
894 getCopyToParts(DAG, getCurDebugLoc(),
895 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
896 &Parts[0], NumParts, PartVT, ExtendKind);
898 // 'inreg' on function refers to return value
899 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
900 if (F->paramHasAttr(0, Attribute::InReg))
903 // Propagate extension type if any
904 if (F->paramHasAttr(0, Attribute::SExt))
906 else if (F->paramHasAttr(0, Attribute::ZExt))
909 for (unsigned i = 0; i < NumParts; ++i)
910 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
915 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
916 CallingConv::ID CallConv =
917 DAG.getMachineFunction().getFunction()->getCallingConv();
918 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
919 Outs, getCurDebugLoc(), DAG);
921 // Verify that the target's LowerReturn behaved as expected.
922 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
923 "LowerReturn didn't return a valid chain!");
925 // Update the DAG with the new chain value resulting from return lowering.
929 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
930 /// created for it, emit nodes to copy the value into the virtual
932 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
933 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
934 if (VMI != FuncInfo.ValueMap.end()) {
935 assert(!V->use_empty() && "Unused value assigned virtual registers!");
936 CopyValueToVirtualRegister(V, VMI->second);
940 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
941 /// the current basic block, add it to ValueMap now so that we'll get a
943 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
944 // No need to export constants.
945 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
948 if (FuncInfo.isExportedInst(V)) return;
950 unsigned Reg = FuncInfo.InitializeRegForValue(V);
951 CopyValueToVirtualRegister(V, Reg);
954 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
955 const BasicBlock *FromBB) {
956 // The operands of the setcc have to be in this block. We don't know
957 // how to export them from some other block.
958 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
959 // Can export from current BB.
960 if (VI->getParent() == FromBB)
963 // Is already exported, noop.
964 return FuncInfo.isExportedInst(V);
967 // If this is an argument, we can export it if the BB is the entry block or
968 // if it is already exported.
969 if (isa<Argument>(V)) {
970 if (FromBB == &FromBB->getParent()->getEntryBlock())
973 // Otherwise, can only export this if it is already exported.
974 return FuncInfo.isExportedInst(V);
977 // Otherwise, constants can always be exported.
981 static bool InBlock(const Value *V, const BasicBlock *BB) {
982 if (const Instruction *I = dyn_cast<Instruction>(V))
983 return I->getParent() == BB;
987 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
988 /// This function emits a branch and is used at the leaves of an OR or an
989 /// AND operator tree.
992 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
993 MachineBasicBlock *TBB,
994 MachineBasicBlock *FBB,
995 MachineBasicBlock *CurBB,
996 MachineBasicBlock *SwitchBB) {
997 const BasicBlock *BB = CurBB->getBasicBlock();
999 // If the leaf of the tree is a comparison, merge the condition into
1001 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1002 // The operands of the cmp have to be in this block. We don't know
1003 // how to export them from some other block. If this is the first block
1004 // of the sequence, no exporting is needed.
1005 if (CurBB == SwitchBB ||
1006 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1007 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1008 ISD::CondCode Condition;
1009 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1010 Condition = getICmpCondCode(IC->getPredicate());
1011 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1012 Condition = getFCmpCondCode(FC->getPredicate());
1014 Condition = ISD::SETEQ; // silence warning.
1015 llvm_unreachable("Unknown compare instruction");
1018 CaseBlock CB(Condition, BOp->getOperand(0),
1019 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1020 SwitchCases.push_back(CB);
1025 // Create a CaseBlock record representing this branch.
1026 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1027 NULL, TBB, FBB, CurBB);
1028 SwitchCases.push_back(CB);
1031 /// FindMergedConditions - If Cond is an expression like
1032 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1033 MachineBasicBlock *TBB,
1034 MachineBasicBlock *FBB,
1035 MachineBasicBlock *CurBB,
1036 MachineBasicBlock *SwitchBB,
1038 // If this node is not part of the or/and tree, emit it as a branch.
1039 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1040 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1041 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1042 BOp->getParent() != CurBB->getBasicBlock() ||
1043 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1044 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1045 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1049 // Create TmpBB after CurBB.
1050 MachineFunction::iterator BBI = CurBB;
1051 MachineFunction &MF = DAG.getMachineFunction();
1052 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1053 CurBB->getParent()->insert(++BBI, TmpBB);
1055 if (Opc == Instruction::Or) {
1056 // Codegen X | Y as:
1064 // Emit the LHS condition.
1065 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1067 // Emit the RHS condition into TmpBB.
1068 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1070 assert(Opc == Instruction::And && "Unknown merge op!");
1071 // Codegen X & Y as:
1078 // This requires creation of TmpBB after CurBB.
1080 // Emit the LHS condition.
1081 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1083 // Emit the RHS condition into TmpBB.
1084 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1088 /// If the set of cases should be emitted as a series of branches, return true.
1089 /// If we should emit this as a bunch of and/or'd together conditions, return
1092 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1093 if (Cases.size() != 2) return true;
1095 // If this is two comparisons of the same values or'd or and'd together, they
1096 // will get folded into a single comparison, so don't emit two blocks.
1097 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1098 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1099 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1100 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1104 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1105 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1106 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1107 Cases[0].CC == Cases[1].CC &&
1108 isa<Constant>(Cases[0].CmpRHS) &&
1109 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1110 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1112 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1119 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1120 MachineBasicBlock *BrMBB = FuncInfo.MBBMap[I.getParent()];
1122 // Update machine-CFG edges.
1123 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1125 // Figure out which block is immediately after the current one.
1126 MachineBasicBlock *NextBlock = 0;
1127 MachineFunction::iterator BBI = BrMBB;
1128 if (++BBI != FuncInfo.MF->end())
1131 if (I.isUnconditional()) {
1132 // Update machine-CFG edges.
1133 BrMBB->addSuccessor(Succ0MBB);
1135 // If this is not a fall-through branch, emit the branch.
1136 if (Succ0MBB != NextBlock)
1137 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1138 MVT::Other, getControlRoot(),
1139 DAG.getBasicBlock(Succ0MBB)));
1144 // If this condition is one of the special cases we handle, do special stuff
1146 const Value *CondVal = I.getCondition();
1147 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1149 // If this is a series of conditions that are or'd or and'd together, emit
1150 // this as a sequence of branches instead of setcc's with and/or operations.
1151 // For example, instead of something like:
1164 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1165 if (BOp->hasOneUse() &&
1166 (BOp->getOpcode() == Instruction::And ||
1167 BOp->getOpcode() == Instruction::Or)) {
1168 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1170 // If the compares in later blocks need to use values not currently
1171 // exported from this block, export them now. This block should always
1172 // be the first entry.
1173 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1175 // Allow some cases to be rejected.
1176 if (ShouldEmitAsBranches(SwitchCases)) {
1177 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1178 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1179 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1182 // Emit the branch for this block.
1183 visitSwitchCase(SwitchCases[0], BrMBB);
1184 SwitchCases.erase(SwitchCases.begin());
1188 // Okay, we decided not to do this, remove any inserted MBB's and clear
1190 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1191 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1193 SwitchCases.clear();
1197 // Create a CaseBlock record representing this branch.
1198 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1199 NULL, Succ0MBB, Succ1MBB, BrMBB);
1201 // Use visitSwitchCase to actually insert the fast branch sequence for this
1203 visitSwitchCase(CB, BrMBB);
1206 /// visitSwitchCase - Emits the necessary code to represent a single node in
1207 /// the binary search tree resulting from lowering a switch instruction.
1208 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1209 MachineBasicBlock *SwitchBB) {
1211 SDValue CondLHS = getValue(CB.CmpLHS);
1212 DebugLoc dl = getCurDebugLoc();
1214 // Build the setcc now.
1215 if (CB.CmpMHS == NULL) {
1216 // Fold "(X == true)" to X and "(X == false)" to !X to
1217 // handle common cases produced by branch lowering.
1218 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1219 CB.CC == ISD::SETEQ)
1221 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1222 CB.CC == ISD::SETEQ) {
1223 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1224 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1226 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1228 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1230 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1231 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1233 SDValue CmpOp = getValue(CB.CmpMHS);
1234 EVT VT = CmpOp.getValueType();
1236 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1237 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1240 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1241 VT, CmpOp, DAG.getConstant(Low, VT));
1242 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1243 DAG.getConstant(High-Low, VT), ISD::SETULE);
1247 // Update successor info
1248 SwitchBB->addSuccessor(CB.TrueBB);
1249 SwitchBB->addSuccessor(CB.FalseBB);
1251 // Set NextBlock to be the MBB immediately after the current one, if any.
1252 // This is used to avoid emitting unnecessary branches to the next block.
1253 MachineBasicBlock *NextBlock = 0;
1254 MachineFunction::iterator BBI = SwitchBB;
1255 if (++BBI != FuncInfo.MF->end())
1258 // If the lhs block is the next block, invert the condition so that we can
1259 // fall through to the lhs instead of the rhs block.
1260 if (CB.TrueBB == NextBlock) {
1261 std::swap(CB.TrueBB, CB.FalseBB);
1262 SDValue True = DAG.getConstant(1, Cond.getValueType());
1263 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1266 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1267 MVT::Other, getControlRoot(), Cond,
1268 DAG.getBasicBlock(CB.TrueBB));
1270 // If the branch was constant folded, fix up the CFG.
1271 if (BrCond.getOpcode() == ISD::BR) {
1272 SwitchBB->removeSuccessor(CB.FalseBB);
1274 // Otherwise, go ahead and insert the false branch.
1275 if (BrCond == getControlRoot())
1276 SwitchBB->removeSuccessor(CB.TrueBB);
1278 if (CB.FalseBB != NextBlock)
1279 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1280 DAG.getBasicBlock(CB.FalseBB));
1283 DAG.setRoot(BrCond);
1286 /// visitJumpTable - Emit JumpTable node in the current MBB
1287 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1288 // Emit the code for the jump table
1289 assert(JT.Reg != -1U && "Should lower JT Header first!");
1290 EVT PTy = TLI.getPointerTy();
1291 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1293 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1294 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1295 MVT::Other, Index.getValue(1),
1297 DAG.setRoot(BrJumpTable);
1300 /// visitJumpTableHeader - This function emits necessary code to produce index
1301 /// in the JumpTable from switch case.
1302 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1303 JumpTableHeader &JTH,
1304 MachineBasicBlock *SwitchBB) {
1305 // Subtract the lowest switch case value from the value being switched on and
1306 // conditional branch to default mbb if the result is greater than the
1307 // difference between smallest and largest cases.
1308 SDValue SwitchOp = getValue(JTH.SValue);
1309 EVT VT = SwitchOp.getValueType();
1310 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1311 DAG.getConstant(JTH.First, VT));
1313 // The SDNode we just created, which holds the value being switched on minus
1314 // the smallest case value, needs to be copied to a virtual register so it
1315 // can be used as an index into the jump table in a subsequent basic block.
1316 // This value may be smaller or larger than the target's pointer type, and
1317 // therefore require extension or truncating.
1318 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1320 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1321 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1322 JumpTableReg, SwitchOp);
1323 JT.Reg = JumpTableReg;
1325 // Emit the range check for the jump table, and branch to the default block
1326 // for the switch statement if the value being switched on exceeds the largest
1327 // case in the switch.
1328 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1329 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1330 DAG.getConstant(JTH.Last-JTH.First,VT),
1333 // Set NextBlock to be the MBB immediately after the current one, if any.
1334 // This is used to avoid emitting unnecessary branches to the next block.
1335 MachineBasicBlock *NextBlock = 0;
1336 MachineFunction::iterator BBI = SwitchBB;
1338 if (++BBI != FuncInfo.MF->end())
1341 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1342 MVT::Other, CopyTo, CMP,
1343 DAG.getBasicBlock(JT.Default));
1345 if (JT.MBB != NextBlock)
1346 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1347 DAG.getBasicBlock(JT.MBB));
1349 DAG.setRoot(BrCond);
1352 /// visitBitTestHeader - This function emits necessary code to produce value
1353 /// suitable for "bit tests"
1354 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1355 MachineBasicBlock *SwitchBB) {
1356 // Subtract the minimum value
1357 SDValue SwitchOp = getValue(B.SValue);
1358 EVT VT = SwitchOp.getValueType();
1359 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1360 DAG.getConstant(B.First, VT));
1363 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1364 TLI.getSetCCResultType(Sub.getValueType()),
1365 Sub, DAG.getConstant(B.Range, VT),
1368 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1369 TLI.getPointerTy());
1371 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1372 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1375 // Set NextBlock to be the MBB immediately after the current one, if any.
1376 // This is used to avoid emitting unnecessary branches to the next block.
1377 MachineBasicBlock *NextBlock = 0;
1378 MachineFunction::iterator BBI = SwitchBB;
1379 if (++BBI != FuncInfo.MF->end())
1382 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1384 SwitchBB->addSuccessor(B.Default);
1385 SwitchBB->addSuccessor(MBB);
1387 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1388 MVT::Other, CopyTo, RangeCmp,
1389 DAG.getBasicBlock(B.Default));
1391 if (MBB != NextBlock)
1392 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1393 DAG.getBasicBlock(MBB));
1395 DAG.setRoot(BrRange);
1398 /// visitBitTestCase - this function produces one "bit test"
1399 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1402 MachineBasicBlock *SwitchBB) {
1403 // Make desired shift
1404 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1405 TLI.getPointerTy());
1406 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1408 DAG.getConstant(1, TLI.getPointerTy()),
1411 // Emit bit tests and jumps
1412 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1413 TLI.getPointerTy(), SwitchVal,
1414 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1415 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1416 TLI.getSetCCResultType(AndOp.getValueType()),
1417 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1420 SwitchBB->addSuccessor(B.TargetBB);
1421 SwitchBB->addSuccessor(NextMBB);
1423 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1424 MVT::Other, getControlRoot(),
1425 AndCmp, DAG.getBasicBlock(B.TargetBB));
1427 // Set NextBlock to be the MBB immediately after the current one, if any.
1428 // This is used to avoid emitting unnecessary branches to the next block.
1429 MachineBasicBlock *NextBlock = 0;
1430 MachineFunction::iterator BBI = SwitchBB;
1431 if (++BBI != FuncInfo.MF->end())
1434 if (NextMBB != NextBlock)
1435 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1436 DAG.getBasicBlock(NextMBB));
1441 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1442 MachineBasicBlock *InvokeMBB = FuncInfo.MBBMap[I.getParent()];
1444 // Retrieve successors.
1445 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1446 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1448 const Value *Callee(I.getCalledValue());
1449 if (isa<InlineAsm>(Callee))
1452 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1454 // If the value of the invoke is used outside of its defining block, make it
1455 // available as a virtual register.
1456 CopyToExportRegsIfNeeded(&I);
1458 // Update successor info
1459 InvokeMBB->addSuccessor(Return);
1460 InvokeMBB->addSuccessor(LandingPad);
1462 // Drop into normal successor.
1463 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1464 MVT::Other, getControlRoot(),
1465 DAG.getBasicBlock(Return)));
1468 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1471 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1472 /// small case ranges).
1473 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1474 CaseRecVector& WorkList,
1476 MachineBasicBlock *Default,
1477 MachineBasicBlock *SwitchBB) {
1478 Case& BackCase = *(CR.Range.second-1);
1480 // Size is the number of Cases represented by this range.
1481 size_t Size = CR.Range.second - CR.Range.first;
1485 // Get the MachineFunction which holds the current MBB. This is used when
1486 // inserting any additional MBBs necessary to represent the switch.
1487 MachineFunction *CurMF = FuncInfo.MF;
1489 // Figure out which block is immediately after the current one.
1490 MachineBasicBlock *NextBlock = 0;
1491 MachineFunction::iterator BBI = CR.CaseBB;
1493 if (++BBI != FuncInfo.MF->end())
1496 // TODO: If any two of the cases has the same destination, and if one value
1497 // is the same as the other, but has one bit unset that the other has set,
1498 // use bit manipulation to do two compares at once. For example:
1499 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1501 // Rearrange the case blocks so that the last one falls through if possible.
1502 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1503 // The last case block won't fall through into 'NextBlock' if we emit the
1504 // branches in this order. See if rearranging a case value would help.
1505 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1506 if (I->BB == NextBlock) {
1507 std::swap(*I, BackCase);
1513 // Create a CaseBlock record representing a conditional branch to
1514 // the Case's target mbb if the value being switched on SV is equal
1516 MachineBasicBlock *CurBlock = CR.CaseBB;
1517 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1518 MachineBasicBlock *FallThrough;
1520 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1521 CurMF->insert(BBI, FallThrough);
1523 // Put SV in a virtual register to make it available from the new blocks.
1524 ExportFromCurrentBlock(SV);
1526 // If the last case doesn't match, go to the default block.
1527 FallThrough = Default;
1530 const Value *RHS, *LHS, *MHS;
1532 if (I->High == I->Low) {
1533 // This is just small small case range :) containing exactly 1 case
1535 LHS = SV; RHS = I->High; MHS = NULL;
1538 LHS = I->Low; MHS = SV; RHS = I->High;
1540 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1542 // If emitting the first comparison, just call visitSwitchCase to emit the
1543 // code into the current block. Otherwise, push the CaseBlock onto the
1544 // vector to be later processed by SDISel, and insert the node's MBB
1545 // before the next MBB.
1546 if (CurBlock == SwitchBB)
1547 visitSwitchCase(CB, SwitchBB);
1549 SwitchCases.push_back(CB);
1551 CurBlock = FallThrough;
1557 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1558 return !DisableJumpTables &&
1559 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1560 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1563 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1564 APInt LastExt(Last), FirstExt(First);
1565 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1566 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1567 return (LastExt - FirstExt + 1ULL);
1570 /// handleJTSwitchCase - Emit jumptable for current switch case range
1571 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1572 CaseRecVector& WorkList,
1574 MachineBasicBlock* Default,
1575 MachineBasicBlock *SwitchBB) {
1576 Case& FrontCase = *CR.Range.first;
1577 Case& BackCase = *(CR.Range.second-1);
1579 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1580 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1582 APInt TSize(First.getBitWidth(), 0);
1583 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1587 if (!areJTsAllowed(TLI) || TSize.ult(4))
1590 APInt Range = ComputeRange(First, Last);
1591 double Density = TSize.roundToDouble() / Range.roundToDouble();
1595 DEBUG(dbgs() << "Lowering jump table\n"
1596 << "First entry: " << First << ". Last entry: " << Last << '\n'
1597 << "Range: " << Range
1598 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1600 // Get the MachineFunction which holds the current MBB. This is used when
1601 // inserting any additional MBBs necessary to represent the switch.
1602 MachineFunction *CurMF = FuncInfo.MF;
1604 // Figure out which block is immediately after the current one.
1605 MachineFunction::iterator BBI = CR.CaseBB;
1608 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1610 // Create a new basic block to hold the code for loading the address
1611 // of the jump table, and jumping to it. Update successor information;
1612 // we will either branch to the default case for the switch, or the jump
1614 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1615 CurMF->insert(BBI, JumpTableBB);
1616 CR.CaseBB->addSuccessor(Default);
1617 CR.CaseBB->addSuccessor(JumpTableBB);
1619 // Build a vector of destination BBs, corresponding to each target
1620 // of the jump table. If the value of the jump table slot corresponds to
1621 // a case statement, push the case's BB onto the vector, otherwise, push
1623 std::vector<MachineBasicBlock*> DestBBs;
1625 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1626 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1627 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1629 if (Low.sle(TEI) && TEI.sle(High)) {
1630 DestBBs.push_back(I->BB);
1634 DestBBs.push_back(Default);
1638 // Update successor info. Add one edge to each unique successor.
1639 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1640 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1641 E = DestBBs.end(); I != E; ++I) {
1642 if (!SuccsHandled[(*I)->getNumber()]) {
1643 SuccsHandled[(*I)->getNumber()] = true;
1644 JumpTableBB->addSuccessor(*I);
1648 // Create a jump table index for this jump table.
1649 unsigned JTEncoding = TLI.getJumpTableEncoding();
1650 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1651 ->createJumpTableIndex(DestBBs);
1653 // Set the jump table information so that we can codegen it as a second
1654 // MachineBasicBlock
1655 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1656 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
1657 if (CR.CaseBB == SwitchBB)
1658 visitJumpTableHeader(JT, JTH, SwitchBB);
1660 JTCases.push_back(JumpTableBlock(JTH, JT));
1665 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1667 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1668 CaseRecVector& WorkList,
1670 MachineBasicBlock *Default,
1671 MachineBasicBlock *SwitchBB) {
1672 // Get the MachineFunction which holds the current MBB. This is used when
1673 // inserting any additional MBBs necessary to represent the switch.
1674 MachineFunction *CurMF = FuncInfo.MF;
1676 // Figure out which block is immediately after the current one.
1677 MachineFunction::iterator BBI = CR.CaseBB;
1680 Case& FrontCase = *CR.Range.first;
1681 Case& BackCase = *(CR.Range.second-1);
1682 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1684 // Size is the number of Cases represented by this range.
1685 unsigned Size = CR.Range.second - CR.Range.first;
1687 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1688 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1690 CaseItr Pivot = CR.Range.first + Size/2;
1692 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1693 // (heuristically) allow us to emit JumpTable's later.
1694 APInt TSize(First.getBitWidth(), 0);
1695 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1699 APInt LSize = FrontCase.size();
1700 APInt RSize = TSize-LSize;
1701 DEBUG(dbgs() << "Selecting best pivot: \n"
1702 << "First: " << First << ", Last: " << Last <<'\n'
1703 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1704 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1706 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1707 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1708 APInt Range = ComputeRange(LEnd, RBegin);
1709 assert((Range - 2ULL).isNonNegative() &&
1710 "Invalid case distance");
1711 double LDensity = (double)LSize.roundToDouble() /
1712 (LEnd - First + 1ULL).roundToDouble();
1713 double RDensity = (double)RSize.roundToDouble() /
1714 (Last - RBegin + 1ULL).roundToDouble();
1715 double Metric = Range.logBase2()*(LDensity+RDensity);
1716 // Should always split in some non-trivial place
1717 DEBUG(dbgs() <<"=>Step\n"
1718 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1719 << "LDensity: " << LDensity
1720 << ", RDensity: " << RDensity << '\n'
1721 << "Metric: " << Metric << '\n');
1722 if (FMetric < Metric) {
1725 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
1731 if (areJTsAllowed(TLI)) {
1732 // If our case is dense we *really* should handle it earlier!
1733 assert((FMetric > 0) && "Should handle dense range earlier!");
1735 Pivot = CR.Range.first + Size/2;
1738 CaseRange LHSR(CR.Range.first, Pivot);
1739 CaseRange RHSR(Pivot, CR.Range.second);
1740 Constant *C = Pivot->Low;
1741 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1743 // We know that we branch to the LHS if the Value being switched on is
1744 // less than the Pivot value, C. We use this to optimize our binary
1745 // tree a bit, by recognizing that if SV is greater than or equal to the
1746 // LHS's Case Value, and that Case Value is exactly one less than the
1747 // Pivot's Value, then we can branch directly to the LHS's Target,
1748 // rather than creating a leaf node for it.
1749 if ((LHSR.second - LHSR.first) == 1 &&
1750 LHSR.first->High == CR.GE &&
1751 cast<ConstantInt>(C)->getValue() ==
1752 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1753 TrueBB = LHSR.first->BB;
1755 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1756 CurMF->insert(BBI, TrueBB);
1757 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1759 // Put SV in a virtual register to make it available from the new blocks.
1760 ExportFromCurrentBlock(SV);
1763 // Similar to the optimization above, if the Value being switched on is
1764 // known to be less than the Constant CR.LT, and the current Case Value
1765 // is CR.LT - 1, then we can branch directly to the target block for
1766 // the current Case Value, rather than emitting a RHS leaf node for it.
1767 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1768 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1769 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1770 FalseBB = RHSR.first->BB;
1772 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1773 CurMF->insert(BBI, FalseBB);
1774 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1776 // Put SV in a virtual register to make it available from the new blocks.
1777 ExportFromCurrentBlock(SV);
1780 // Create a CaseBlock record representing a conditional branch to
1781 // the LHS node if the value being switched on SV is less than C.
1782 // Otherwise, branch to LHS.
1783 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1785 if (CR.CaseBB == SwitchBB)
1786 visitSwitchCase(CB, SwitchBB);
1788 SwitchCases.push_back(CB);
1793 /// handleBitTestsSwitchCase - if current case range has few destination and
1794 /// range span less, than machine word bitwidth, encode case range into series
1795 /// of masks and emit bit tests with these masks.
1796 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1797 CaseRecVector& WorkList,
1799 MachineBasicBlock* Default,
1800 MachineBasicBlock *SwitchBB){
1801 EVT PTy = TLI.getPointerTy();
1802 unsigned IntPtrBits = PTy.getSizeInBits();
1804 Case& FrontCase = *CR.Range.first;
1805 Case& BackCase = *(CR.Range.second-1);
1807 // Get the MachineFunction which holds the current MBB. This is used when
1808 // inserting any additional MBBs necessary to represent the switch.
1809 MachineFunction *CurMF = FuncInfo.MF;
1811 // If target does not have legal shift left, do not emit bit tests at all.
1812 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1816 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1818 // Single case counts one, case range - two.
1819 numCmps += (I->Low == I->High ? 1 : 2);
1822 // Count unique destinations
1823 SmallSet<MachineBasicBlock*, 4> Dests;
1824 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1825 Dests.insert(I->BB);
1826 if (Dests.size() > 3)
1827 // Don't bother the code below, if there are too much unique destinations
1830 DEBUG(dbgs() << "Total number of unique destinations: "
1831 << Dests.size() << '\n'
1832 << "Total number of comparisons: " << numCmps << '\n');
1834 // Compute span of values.
1835 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1836 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1837 APInt cmpRange = maxValue - minValue;
1839 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
1840 << "Low bound: " << minValue << '\n'
1841 << "High bound: " << maxValue << '\n');
1843 if (cmpRange.uge(IntPtrBits) ||
1844 (!(Dests.size() == 1 && numCmps >= 3) &&
1845 !(Dests.size() == 2 && numCmps >= 5) &&
1846 !(Dests.size() >= 3 && numCmps >= 6)))
1849 DEBUG(dbgs() << "Emitting bit tests\n");
1850 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1852 // Optimize the case where all the case values fit in a
1853 // word without having to subtract minValue. In this case,
1854 // we can optimize away the subtraction.
1855 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
1856 cmpRange = maxValue;
1858 lowBound = minValue;
1861 CaseBitsVector CasesBits;
1862 unsigned i, count = 0;
1864 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1865 MachineBasicBlock* Dest = I->BB;
1866 for (i = 0; i < count; ++i)
1867 if (Dest == CasesBits[i].BB)
1871 assert((count < 3) && "Too much destinations to test!");
1872 CasesBits.push_back(CaseBits(0, Dest, 0));
1876 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1877 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1879 uint64_t lo = (lowValue - lowBound).getZExtValue();
1880 uint64_t hi = (highValue - lowBound).getZExtValue();
1882 for (uint64_t j = lo; j <= hi; j++) {
1883 CasesBits[i].Mask |= 1ULL << j;
1884 CasesBits[i].Bits++;
1888 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1892 // Figure out which block is immediately after the current one.
1893 MachineFunction::iterator BBI = CR.CaseBB;
1896 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1898 DEBUG(dbgs() << "Cases:\n");
1899 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1900 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
1901 << ", Bits: " << CasesBits[i].Bits
1902 << ", BB: " << CasesBits[i].BB << '\n');
1904 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1905 CurMF->insert(BBI, CaseBB);
1906 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1910 // Put SV in a virtual register to make it available from the new blocks.
1911 ExportFromCurrentBlock(SV);
1914 BitTestBlock BTB(lowBound, cmpRange, SV,
1915 -1U, (CR.CaseBB == SwitchBB),
1916 CR.CaseBB, Default, BTC);
1918 if (CR.CaseBB == SwitchBB)
1919 visitBitTestHeader(BTB, SwitchBB);
1921 BitTestCases.push_back(BTB);
1926 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1927 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1928 const SwitchInst& SI) {
1931 // Start with "simple" cases
1932 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1933 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1934 Cases.push_back(Case(SI.getSuccessorValue(i),
1935 SI.getSuccessorValue(i),
1938 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1940 // Merge case into clusters
1941 if (Cases.size() >= 2)
1942 // Must recompute end() each iteration because it may be
1943 // invalidated by erase if we hold on to it
1944 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1945 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1946 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1947 MachineBasicBlock* nextBB = J->BB;
1948 MachineBasicBlock* currentBB = I->BB;
1950 // If the two neighboring cases go to the same destination, merge them
1951 // into a single case.
1952 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1960 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1961 if (I->Low != I->High)
1962 // A range counts double, since it requires two compares.
1969 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
1970 MachineBasicBlock *SwitchMBB = FuncInfo.MBBMap[SI.getParent()];
1972 // Figure out which block is immediately after the current one.
1973 MachineBasicBlock *NextBlock = 0;
1974 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1976 // If there is only the default destination, branch to it if it is not the
1977 // next basic block. Otherwise, just fall through.
1978 if (SI.getNumOperands() == 2) {
1979 // Update machine-CFG edges.
1981 // If this is not a fall-through branch, emit the branch.
1982 SwitchMBB->addSuccessor(Default);
1983 if (Default != NextBlock)
1984 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1985 MVT::Other, getControlRoot(),
1986 DAG.getBasicBlock(Default)));
1991 // If there are any non-default case statements, create a vector of Cases
1992 // representing each one, and sort the vector so that we can efficiently
1993 // create a binary search tree from them.
1995 size_t numCmps = Clusterify(Cases, SI);
1996 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
1997 << ". Total compares: " << numCmps << '\n');
2000 // Get the Value to be switched on and default basic blocks, which will be
2001 // inserted into CaseBlock records, representing basic blocks in the binary
2003 const Value *SV = SI.getOperand(0);
2005 // Push the initial CaseRec onto the worklist
2006 CaseRecVector WorkList;
2007 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2008 CaseRange(Cases.begin(),Cases.end())));
2010 while (!WorkList.empty()) {
2011 // Grab a record representing a case range to process off the worklist
2012 CaseRec CR = WorkList.back();
2013 WorkList.pop_back();
2015 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2018 // If the range has few cases (two or less) emit a series of specific
2020 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2023 // If the switch has more than 5 blocks, and at least 40% dense, and the
2024 // target supports indirect branches, then emit a jump table rather than
2025 // lowering the switch to a binary tree of conditional branches.
2026 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2029 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2030 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2031 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2035 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2036 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBBMap[I.getParent()];
2038 // Update machine-CFG edges with unique successors.
2039 SmallVector<BasicBlock*, 32> succs;
2040 succs.reserve(I.getNumSuccessors());
2041 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2042 succs.push_back(I.getSuccessor(i));
2043 array_pod_sort(succs.begin(), succs.end());
2044 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2045 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2046 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2048 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2049 MVT::Other, getControlRoot(),
2050 getValue(I.getAddress())));
2053 void SelectionDAGBuilder::visitFSub(const User &I) {
2054 // -0.0 - X --> fneg
2055 const Type *Ty = I.getType();
2056 if (Ty->isVectorTy()) {
2057 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2058 const VectorType *DestTy = cast<VectorType>(I.getType());
2059 const Type *ElTy = DestTy->getElementType();
2060 unsigned VL = DestTy->getNumElements();
2061 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2062 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2064 SDValue Op2 = getValue(I.getOperand(1));
2065 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2066 Op2.getValueType(), Op2));
2072 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2073 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2074 SDValue Op2 = getValue(I.getOperand(1));
2075 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2076 Op2.getValueType(), Op2));
2080 visitBinary(I, ISD::FSUB);
2083 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2084 SDValue Op1 = getValue(I.getOperand(0));
2085 SDValue Op2 = getValue(I.getOperand(1));
2086 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2087 Op1.getValueType(), Op1, Op2));
2090 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2091 SDValue Op1 = getValue(I.getOperand(0));
2092 SDValue Op2 = getValue(I.getOperand(1));
2093 if (!I.getType()->isVectorTy() &&
2094 Op2.getValueType() != TLI.getShiftAmountTy()) {
2095 // If the operand is smaller than the shift count type, promote it.
2096 EVT PTy = TLI.getPointerTy();
2097 EVT STy = TLI.getShiftAmountTy();
2098 if (STy.bitsGT(Op2.getValueType()))
2099 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2100 TLI.getShiftAmountTy(), Op2);
2101 // If the operand is larger than the shift count type but the shift
2102 // count type has enough bits to represent any shift value, truncate
2103 // it now. This is a common case and it exposes the truncate to
2104 // optimization early.
2105 else if (STy.getSizeInBits() >=
2106 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2107 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2108 TLI.getShiftAmountTy(), Op2);
2109 // Otherwise we'll need to temporarily settle for some other
2110 // convenient type; type legalization will make adjustments as
2112 else if (PTy.bitsLT(Op2.getValueType()))
2113 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2114 TLI.getPointerTy(), Op2);
2115 else if (PTy.bitsGT(Op2.getValueType()))
2116 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2117 TLI.getPointerTy(), Op2);
2120 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2121 Op1.getValueType(), Op1, Op2));
2124 void SelectionDAGBuilder::visitICmp(const User &I) {
2125 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2126 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2127 predicate = IC->getPredicate();
2128 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2129 predicate = ICmpInst::Predicate(IC->getPredicate());
2130 SDValue Op1 = getValue(I.getOperand(0));
2131 SDValue Op2 = getValue(I.getOperand(1));
2132 ISD::CondCode Opcode = getICmpCondCode(predicate);
2134 EVT DestVT = TLI.getValueType(I.getType());
2135 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2138 void SelectionDAGBuilder::visitFCmp(const User &I) {
2139 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2140 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2141 predicate = FC->getPredicate();
2142 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2143 predicate = FCmpInst::Predicate(FC->getPredicate());
2144 SDValue Op1 = getValue(I.getOperand(0));
2145 SDValue Op2 = getValue(I.getOperand(1));
2146 ISD::CondCode Condition = getFCmpCondCode(predicate);
2147 EVT DestVT = TLI.getValueType(I.getType());
2148 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2151 void SelectionDAGBuilder::visitSelect(const User &I) {
2152 SmallVector<EVT, 4> ValueVTs;
2153 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2154 unsigned NumValues = ValueVTs.size();
2155 if (NumValues == 0) return;
2157 SmallVector<SDValue, 4> Values(NumValues);
2158 SDValue Cond = getValue(I.getOperand(0));
2159 SDValue TrueVal = getValue(I.getOperand(1));
2160 SDValue FalseVal = getValue(I.getOperand(2));
2162 for (unsigned i = 0; i != NumValues; ++i)
2163 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2164 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2166 SDValue(TrueVal.getNode(),
2167 TrueVal.getResNo() + i),
2168 SDValue(FalseVal.getNode(),
2169 FalseVal.getResNo() + i));
2171 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2172 DAG.getVTList(&ValueVTs[0], NumValues),
2173 &Values[0], NumValues));
2176 void SelectionDAGBuilder::visitTrunc(const User &I) {
2177 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2178 SDValue N = getValue(I.getOperand(0));
2179 EVT DestVT = TLI.getValueType(I.getType());
2180 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2183 void SelectionDAGBuilder::visitZExt(const User &I) {
2184 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2185 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2186 SDValue N = getValue(I.getOperand(0));
2187 EVT DestVT = TLI.getValueType(I.getType());
2188 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2191 void SelectionDAGBuilder::visitSExt(const User &I) {
2192 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2193 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2194 SDValue N = getValue(I.getOperand(0));
2195 EVT DestVT = TLI.getValueType(I.getType());
2196 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2199 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2200 // FPTrunc is never a no-op cast, no need to check
2201 SDValue N = getValue(I.getOperand(0));
2202 EVT DestVT = TLI.getValueType(I.getType());
2203 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2204 DestVT, N, DAG.getIntPtrConstant(0)));
2207 void SelectionDAGBuilder::visitFPExt(const User &I){
2208 // FPTrunc is never a no-op cast, no need to check
2209 SDValue N = getValue(I.getOperand(0));
2210 EVT DestVT = TLI.getValueType(I.getType());
2211 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2214 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2215 // FPToUI is never a no-op cast, no need to check
2216 SDValue N = getValue(I.getOperand(0));
2217 EVT DestVT = TLI.getValueType(I.getType());
2218 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2221 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2222 // FPToSI is never a no-op cast, no need to check
2223 SDValue N = getValue(I.getOperand(0));
2224 EVT DestVT = TLI.getValueType(I.getType());
2225 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2228 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2229 // UIToFP is never a no-op cast, no need to check
2230 SDValue N = getValue(I.getOperand(0));
2231 EVT DestVT = TLI.getValueType(I.getType());
2232 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2235 void SelectionDAGBuilder::visitSIToFP(const User &I){
2236 // SIToFP is never a no-op cast, no need to check
2237 SDValue N = getValue(I.getOperand(0));
2238 EVT DestVT = TLI.getValueType(I.getType());
2239 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2242 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2243 // What to do depends on the size of the integer and the size of the pointer.
2244 // We can either truncate, zero extend, or no-op, accordingly.
2245 SDValue N = getValue(I.getOperand(0));
2246 EVT SrcVT = N.getValueType();
2247 EVT DestVT = TLI.getValueType(I.getType());
2248 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2251 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2252 // What to do depends on the size of the integer and the size of the pointer.
2253 // We can either truncate, zero extend, or no-op, accordingly.
2254 SDValue N = getValue(I.getOperand(0));
2255 EVT SrcVT = N.getValueType();
2256 EVT DestVT = TLI.getValueType(I.getType());
2257 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2260 void SelectionDAGBuilder::visitBitCast(const User &I) {
2261 SDValue N = getValue(I.getOperand(0));
2262 EVT DestVT = TLI.getValueType(I.getType());
2264 // BitCast assures us that source and destination are the same size so this is
2265 // either a BIT_CONVERT or a no-op.
2266 if (DestVT != N.getValueType())
2267 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2268 DestVT, N)); // convert types.
2270 setValue(&I, N); // noop cast.
2273 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2274 SDValue InVec = getValue(I.getOperand(0));
2275 SDValue InVal = getValue(I.getOperand(1));
2276 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2278 getValue(I.getOperand(2)));
2279 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2280 TLI.getValueType(I.getType()),
2281 InVec, InVal, InIdx));
2284 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2285 SDValue InVec = getValue(I.getOperand(0));
2286 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2288 getValue(I.getOperand(1)));
2289 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2290 TLI.getValueType(I.getType()), InVec, InIdx));
2293 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2294 // from SIndx and increasing to the element length (undefs are allowed).
2295 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2296 unsigned MaskNumElts = Mask.size();
2297 for (unsigned i = 0; i != MaskNumElts; ++i)
2298 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2303 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2304 SmallVector<int, 8> Mask;
2305 SDValue Src1 = getValue(I.getOperand(0));
2306 SDValue Src2 = getValue(I.getOperand(1));
2308 // Convert the ConstantVector mask operand into an array of ints, with -1
2309 // representing undef values.
2310 SmallVector<Constant*, 8> MaskElts;
2311 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2312 unsigned MaskNumElts = MaskElts.size();
2313 for (unsigned i = 0; i != MaskNumElts; ++i) {
2314 if (isa<UndefValue>(MaskElts[i]))
2317 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2320 EVT VT = TLI.getValueType(I.getType());
2321 EVT SrcVT = Src1.getValueType();
2322 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2324 if (SrcNumElts == MaskNumElts) {
2325 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2330 // Normalize the shuffle vector since mask and vector length don't match.
2331 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2332 // Mask is longer than the source vectors and is a multiple of the source
2333 // vectors. We can use concatenate vector to make the mask and vectors
2335 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2336 // The shuffle is concatenating two vectors together.
2337 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2342 // Pad both vectors with undefs to make them the same length as the mask.
2343 unsigned NumConcat = MaskNumElts / SrcNumElts;
2344 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2345 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2346 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2348 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2349 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2353 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2354 getCurDebugLoc(), VT,
2355 &MOps1[0], NumConcat);
2356 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2357 getCurDebugLoc(), VT,
2358 &MOps2[0], NumConcat);
2360 // Readjust mask for new input vector length.
2361 SmallVector<int, 8> MappedOps;
2362 for (unsigned i = 0; i != MaskNumElts; ++i) {
2364 if (Idx < (int)SrcNumElts)
2365 MappedOps.push_back(Idx);
2367 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2370 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2375 if (SrcNumElts > MaskNumElts) {
2376 // Analyze the access pattern of the vector to see if we can extract
2377 // two subvectors and do the shuffle. The analysis is done by calculating
2378 // the range of elements the mask access on both vectors.
2379 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2380 int MaxRange[2] = {-1, -1};
2382 for (unsigned i = 0; i != MaskNumElts; ++i) {
2388 if (Idx >= (int)SrcNumElts) {
2392 if (Idx > MaxRange[Input])
2393 MaxRange[Input] = Idx;
2394 if (Idx < MinRange[Input])
2395 MinRange[Input] = Idx;
2398 // Check if the access is smaller than the vector size and can we find
2399 // a reasonable extract index.
2400 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2402 int StartIdx[2]; // StartIdx to extract from
2403 for (int Input=0; Input < 2; ++Input) {
2404 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2405 RangeUse[Input] = 0; // Unused
2406 StartIdx[Input] = 0;
2407 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2408 // Fits within range but we should see if we can find a good
2409 // start index that is a multiple of the mask length.
2410 if (MaxRange[Input] < (int)MaskNumElts) {
2411 RangeUse[Input] = 1; // Extract from beginning of the vector
2412 StartIdx[Input] = 0;
2414 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2415 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2416 StartIdx[Input] + MaskNumElts < SrcNumElts)
2417 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2422 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2423 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2426 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2427 // Extract appropriate subvector and generate a vector shuffle
2428 for (int Input=0; Input < 2; ++Input) {
2429 SDValue &Src = Input == 0 ? Src1 : Src2;
2430 if (RangeUse[Input] == 0)
2431 Src = DAG.getUNDEF(VT);
2433 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2434 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2437 // Calculate new mask.
2438 SmallVector<int, 8> MappedOps;
2439 for (unsigned i = 0; i != MaskNumElts; ++i) {
2442 MappedOps.push_back(Idx);
2443 else if (Idx < (int)SrcNumElts)
2444 MappedOps.push_back(Idx - StartIdx[0]);
2446 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2449 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2455 // We can't use either concat vectors or extract subvectors so fall back to
2456 // replacing the shuffle with extract and build vector.
2457 // to insert and build vector.
2458 EVT EltVT = VT.getVectorElementType();
2459 EVT PtrVT = TLI.getPointerTy();
2460 SmallVector<SDValue,8> Ops;
2461 for (unsigned i = 0; i != MaskNumElts; ++i) {
2463 Ops.push_back(DAG.getUNDEF(EltVT));
2468 if (Idx < (int)SrcNumElts)
2469 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2470 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2472 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2474 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2480 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2481 VT, &Ops[0], Ops.size()));
2484 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2485 const Value *Op0 = I.getOperand(0);
2486 const Value *Op1 = I.getOperand(1);
2487 const Type *AggTy = I.getType();
2488 const Type *ValTy = Op1->getType();
2489 bool IntoUndef = isa<UndefValue>(Op0);
2490 bool FromUndef = isa<UndefValue>(Op1);
2492 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2493 I.idx_begin(), I.idx_end());
2495 SmallVector<EVT, 4> AggValueVTs;
2496 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2497 SmallVector<EVT, 4> ValValueVTs;
2498 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2500 unsigned NumAggValues = AggValueVTs.size();
2501 unsigned NumValValues = ValValueVTs.size();
2502 SmallVector<SDValue, 4> Values(NumAggValues);
2504 SDValue Agg = getValue(Op0);
2505 SDValue Val = getValue(Op1);
2507 // Copy the beginning value(s) from the original aggregate.
2508 for (; i != LinearIndex; ++i)
2509 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2510 SDValue(Agg.getNode(), Agg.getResNo() + i);
2511 // Copy values from the inserted value(s).
2512 for (; i != LinearIndex + NumValValues; ++i)
2513 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2514 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2515 // Copy remaining value(s) from the original aggregate.
2516 for (; i != NumAggValues; ++i)
2517 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2518 SDValue(Agg.getNode(), Agg.getResNo() + i);
2520 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2521 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2522 &Values[0], NumAggValues));
2525 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2526 const Value *Op0 = I.getOperand(0);
2527 const Type *AggTy = Op0->getType();
2528 const Type *ValTy = I.getType();
2529 bool OutOfUndef = isa<UndefValue>(Op0);
2531 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2532 I.idx_begin(), I.idx_end());
2534 SmallVector<EVT, 4> ValValueVTs;
2535 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2537 unsigned NumValValues = ValValueVTs.size();
2538 SmallVector<SDValue, 4> Values(NumValValues);
2540 SDValue Agg = getValue(Op0);
2541 // Copy out the selected value(s).
2542 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2543 Values[i - LinearIndex] =
2545 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2546 SDValue(Agg.getNode(), Agg.getResNo() + i);
2548 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2549 DAG.getVTList(&ValValueVTs[0], NumValValues),
2550 &Values[0], NumValValues));
2553 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2554 SDValue N = getValue(I.getOperand(0));
2555 const Type *Ty = I.getOperand(0)->getType();
2557 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2559 const Value *Idx = *OI;
2560 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2561 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2564 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2565 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2566 DAG.getIntPtrConstant(Offset));
2569 Ty = StTy->getElementType(Field);
2570 } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) {
2571 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2573 // Offset canonically 0 for unions, but type changes
2574 Ty = UnTy->getElementType(Field);
2576 Ty = cast<SequentialType>(Ty)->getElementType();
2578 // If this is a constant subscript, handle it quickly.
2579 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2580 if (CI->getZExtValue() == 0) continue;
2582 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2584 EVT PTy = TLI.getPointerTy();
2585 unsigned PtrBits = PTy.getSizeInBits();
2587 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2589 DAG.getConstant(Offs, MVT::i64));
2591 OffsVal = DAG.getIntPtrConstant(Offs);
2593 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2598 // N = N + Idx * ElementSize;
2599 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2600 TD->getTypeAllocSize(Ty));
2601 SDValue IdxN = getValue(Idx);
2603 // If the index is smaller or larger than intptr_t, truncate or extend
2605 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2607 // If this is a multiply by a power of two, turn it into a shl
2608 // immediately. This is a very common case.
2609 if (ElementSize != 1) {
2610 if (ElementSize.isPowerOf2()) {
2611 unsigned Amt = ElementSize.logBase2();
2612 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2613 N.getValueType(), IdxN,
2614 DAG.getConstant(Amt, TLI.getPointerTy()));
2616 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2617 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2618 N.getValueType(), IdxN, Scale);
2622 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2623 N.getValueType(), N, IdxN);
2630 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2631 // If this is a fixed sized alloca in the entry block of the function,
2632 // allocate it statically on the stack.
2633 if (FuncInfo.StaticAllocaMap.count(&I))
2634 return; // getValue will auto-populate this.
2636 const Type *Ty = I.getAllocatedType();
2637 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2639 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2642 SDValue AllocSize = getValue(I.getArraySize());
2644 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2646 DAG.getConstant(TySize, AllocSize.getValueType()));
2648 EVT IntPtr = TLI.getPointerTy();
2649 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2651 // Handle alignment. If the requested alignment is less than or equal to
2652 // the stack alignment, ignore it. If the size is greater than or equal to
2653 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2654 unsigned StackAlign = TM.getFrameInfo()->getStackAlignment();
2655 if (Align <= StackAlign)
2658 // Round the size of the allocation up to the stack alignment size
2659 // by add SA-1 to the size.
2660 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2661 AllocSize.getValueType(), AllocSize,
2662 DAG.getIntPtrConstant(StackAlign-1));
2664 // Mask out the low bits for alignment purposes.
2665 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2666 AllocSize.getValueType(), AllocSize,
2667 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2669 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2670 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2671 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2674 DAG.setRoot(DSA.getValue(1));
2676 // Inform the Frame Information that we have just allocated a variable-sized
2678 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2681 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
2682 const Value *SV = I.getOperand(0);
2683 SDValue Ptr = getValue(SV);
2685 const Type *Ty = I.getType();
2687 bool isVolatile = I.isVolatile();
2688 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2689 unsigned Alignment = I.getAlignment();
2691 SmallVector<EVT, 4> ValueVTs;
2692 SmallVector<uint64_t, 4> Offsets;
2693 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2694 unsigned NumValues = ValueVTs.size();
2699 bool ConstantMemory = false;
2701 // Serialize volatile loads with other side effects.
2703 else if (AA->pointsToConstantMemory(SV)) {
2704 // Do not serialize (non-volatile) loads of constant memory with anything.
2705 Root = DAG.getEntryNode();
2706 ConstantMemory = true;
2708 // Do not serialize non-volatile loads against each other.
2709 Root = DAG.getRoot();
2712 SmallVector<SDValue, 4> Values(NumValues);
2713 SmallVector<SDValue, 4> Chains(NumValues);
2714 EVT PtrVT = Ptr.getValueType();
2715 for (unsigned i = 0; i != NumValues; ++i) {
2716 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2718 DAG.getConstant(Offsets[i], PtrVT));
2719 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2720 A, SV, Offsets[i], isVolatile,
2721 isNonTemporal, Alignment);
2724 Chains[i] = L.getValue(1);
2727 if (!ConstantMemory) {
2728 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2729 MVT::Other, &Chains[0], NumValues);
2733 PendingLoads.push_back(Chain);
2736 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2737 DAG.getVTList(&ValueVTs[0], NumValues),
2738 &Values[0], NumValues));
2741 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
2742 const Value *SrcV = I.getOperand(0);
2743 const Value *PtrV = I.getOperand(1);
2745 SmallVector<EVT, 4> ValueVTs;
2746 SmallVector<uint64_t, 4> Offsets;
2747 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2748 unsigned NumValues = ValueVTs.size();
2752 // Get the lowered operands. Note that we do this after
2753 // checking if NumResults is zero, because with zero results
2754 // the operands won't have values in the map.
2755 SDValue Src = getValue(SrcV);
2756 SDValue Ptr = getValue(PtrV);
2758 SDValue Root = getRoot();
2759 SmallVector<SDValue, 4> Chains(NumValues);
2760 EVT PtrVT = Ptr.getValueType();
2761 bool isVolatile = I.isVolatile();
2762 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2763 unsigned Alignment = I.getAlignment();
2765 for (unsigned i = 0; i != NumValues; ++i) {
2766 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2767 DAG.getConstant(Offsets[i], PtrVT));
2768 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2769 SDValue(Src.getNode(), Src.getResNo() + i),
2770 Add, PtrV, Offsets[i], isVolatile,
2771 isNonTemporal, Alignment);
2774 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2775 MVT::Other, &Chains[0], NumValues));
2778 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2780 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
2781 unsigned Intrinsic) {
2782 bool HasChain = !I.doesNotAccessMemory();
2783 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2785 // Build the operand list.
2786 SmallVector<SDValue, 8> Ops;
2787 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2789 // We don't need to serialize loads against other loads.
2790 Ops.push_back(DAG.getRoot());
2792 Ops.push_back(getRoot());
2796 // Info is set by getTgtMemInstrinsic
2797 TargetLowering::IntrinsicInfo Info;
2798 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2800 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2801 if (!IsTgtIntrinsic)
2802 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2804 // Add all operands of the call to the operand list.
2805 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2806 SDValue Op = getValue(I.getOperand(i));
2807 assert(TLI.isTypeLegal(Op.getValueType()) &&
2808 "Intrinsic uses a non-legal type?");
2812 SmallVector<EVT, 4> ValueVTs;
2813 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2815 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2816 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2817 "Intrinsic uses a non-legal type?");
2822 ValueVTs.push_back(MVT::Other);
2824 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2828 if (IsTgtIntrinsic) {
2829 // This is target intrinsic that touches memory
2830 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2831 VTs, &Ops[0], Ops.size(),
2832 Info.memVT, Info.ptrVal, Info.offset,
2833 Info.align, Info.vol,
2834 Info.readMem, Info.writeMem);
2835 } else if (!HasChain) {
2836 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2837 VTs, &Ops[0], Ops.size());
2838 } else if (!I.getType()->isVoidTy()) {
2839 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2840 VTs, &Ops[0], Ops.size());
2842 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2843 VTs, &Ops[0], Ops.size());
2847 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2849 PendingLoads.push_back(Chain);
2854 if (!I.getType()->isVoidTy()) {
2855 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2856 EVT VT = TLI.getValueType(PTy);
2857 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2860 setValue(&I, Result);
2864 /// GetSignificand - Get the significand and build it into a floating-point
2865 /// number with exponent of 1:
2867 /// Op = (Op & 0x007fffff) | 0x3f800000;
2869 /// where Op is the hexidecimal representation of floating point value.
2871 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
2872 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2873 DAG.getConstant(0x007fffff, MVT::i32));
2874 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2875 DAG.getConstant(0x3f800000, MVT::i32));
2876 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
2879 /// GetExponent - Get the exponent:
2881 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
2883 /// where Op is the hexidecimal representation of floating point value.
2885 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
2887 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2888 DAG.getConstant(0x7f800000, MVT::i32));
2889 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
2890 DAG.getConstant(23, TLI.getPointerTy()));
2891 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2892 DAG.getConstant(127, MVT::i32));
2893 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
2896 /// getF32Constant - Get 32-bit floating point constant.
2898 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2899 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2902 /// Inlined utility function to implement binary input atomic intrinsics for
2903 /// visitIntrinsicCall: I is a call instruction
2904 /// Op is the associated NodeType for I
2906 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
2908 SDValue Root = getRoot();
2910 DAG.getAtomic(Op, getCurDebugLoc(),
2911 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2913 getValue(I.getOperand(1)),
2914 getValue(I.getOperand(2)),
2917 DAG.setRoot(L.getValue(1));
2921 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2923 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
2924 SDValue Op1 = getValue(I.getOperand(1));
2925 SDValue Op2 = getValue(I.getOperand(2));
2927 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
2928 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
2932 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2933 /// limited-precision mode.
2935 SelectionDAGBuilder::visitExp(const CallInst &I) {
2937 DebugLoc dl = getCurDebugLoc();
2939 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2940 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2941 SDValue Op = getValue(I.getOperand(1));
2943 // Put the exponent in the right bit position for later addition to the
2946 // #define LOG2OFe 1.4426950f
2947 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2948 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
2949 getF32Constant(DAG, 0x3fb8aa3b));
2950 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
2952 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2953 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2954 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
2956 // IntegerPartOfX <<= 23;
2957 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
2958 DAG.getConstant(23, TLI.getPointerTy()));
2960 if (LimitFloatPrecision <= 6) {
2961 // For floating-point precision of 6:
2963 // TwoToFractionalPartOfX =
2965 // (0.735607626f + 0.252464424f * x) * x;
2967 // error 0.0144103317, which is 6 bits
2968 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2969 getF32Constant(DAG, 0x3e814304));
2970 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2971 getF32Constant(DAG, 0x3f3c50c8));
2972 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2973 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2974 getF32Constant(DAG, 0x3f7f5e7e));
2975 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
2977 // Add the exponent into the result in integer domain.
2978 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2979 TwoToFracPartOfX, IntegerPartOfX);
2981 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
2982 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2983 // For floating-point precision of 12:
2985 // TwoToFractionalPartOfX =
2988 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2990 // 0.000107046256 error, which is 13 to 14 bits
2991 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2992 getF32Constant(DAG, 0x3da235e3));
2993 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2994 getF32Constant(DAG, 0x3e65b8f3));
2995 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2996 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2997 getF32Constant(DAG, 0x3f324b07));
2998 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
2999 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3000 getF32Constant(DAG, 0x3f7ff8fd));
3001 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3003 // Add the exponent into the result in integer domain.
3004 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3005 TwoToFracPartOfX, IntegerPartOfX);
3007 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3008 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3009 // For floating-point precision of 18:
3011 // TwoToFractionalPartOfX =
3015 // (0.554906021e-1f +
3016 // (0.961591928e-2f +
3017 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3019 // error 2.47208000*10^(-7), which is better than 18 bits
3020 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3021 getF32Constant(DAG, 0x3924b03e));
3022 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3023 getF32Constant(DAG, 0x3ab24b87));
3024 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3025 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3026 getF32Constant(DAG, 0x3c1d8c17));
3027 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3028 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3029 getF32Constant(DAG, 0x3d634a1d));
3030 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3031 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3032 getF32Constant(DAG, 0x3e75fe14));
3033 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3034 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3035 getF32Constant(DAG, 0x3f317234));
3036 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3037 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3038 getF32Constant(DAG, 0x3f800000));
3039 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3042 // Add the exponent into the result in integer domain.
3043 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3044 TwoToFracPartOfX, IntegerPartOfX);
3046 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3049 // No special expansion.
3050 result = DAG.getNode(ISD::FEXP, dl,
3051 getValue(I.getOperand(1)).getValueType(),
3052 getValue(I.getOperand(1)));
3055 setValue(&I, result);
3058 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3059 /// limited-precision mode.
3061 SelectionDAGBuilder::visitLog(const CallInst &I) {
3063 DebugLoc dl = getCurDebugLoc();
3065 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3066 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3067 SDValue Op = getValue(I.getOperand(1));
3068 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3070 // Scale the exponent by log(2) [0.69314718f].
3071 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3072 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3073 getF32Constant(DAG, 0x3f317218));
3075 // Get the significand and build it into a floating-point number with
3077 SDValue X = GetSignificand(DAG, Op1, dl);
3079 if (LimitFloatPrecision <= 6) {
3080 // For floating-point precision of 6:
3084 // (1.4034025f - 0.23903021f * x) * x;
3086 // error 0.0034276066, which is better than 8 bits
3087 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3088 getF32Constant(DAG, 0xbe74c456));
3089 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3090 getF32Constant(DAG, 0x3fb3a2b1));
3091 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3092 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3093 getF32Constant(DAG, 0x3f949a29));
3095 result = DAG.getNode(ISD::FADD, dl,
3096 MVT::f32, LogOfExponent, LogOfMantissa);
3097 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3098 // For floating-point precision of 12:
3104 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3106 // error 0.000061011436, which is 14 bits
3107 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3108 getF32Constant(DAG, 0xbd67b6d6));
3109 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3110 getF32Constant(DAG, 0x3ee4f4b8));
3111 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3112 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3113 getF32Constant(DAG, 0x3fbc278b));
3114 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3115 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3116 getF32Constant(DAG, 0x40348e95));
3117 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3118 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3119 getF32Constant(DAG, 0x3fdef31a));
3121 result = DAG.getNode(ISD::FADD, dl,
3122 MVT::f32, LogOfExponent, LogOfMantissa);
3123 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3124 // For floating-point precision of 18:
3132 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3134 // error 0.0000023660568, which is better than 18 bits
3135 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3136 getF32Constant(DAG, 0xbc91e5ac));
3137 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3138 getF32Constant(DAG, 0x3e4350aa));
3139 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3140 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3141 getF32Constant(DAG, 0x3f60d3e3));
3142 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3143 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3144 getF32Constant(DAG, 0x4011cdf0));
3145 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3146 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3147 getF32Constant(DAG, 0x406cfd1c));
3148 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3149 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3150 getF32Constant(DAG, 0x408797cb));
3151 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3152 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3153 getF32Constant(DAG, 0x4006dcab));
3155 result = DAG.getNode(ISD::FADD, dl,
3156 MVT::f32, LogOfExponent, LogOfMantissa);
3159 // No special expansion.
3160 result = DAG.getNode(ISD::FLOG, dl,
3161 getValue(I.getOperand(1)).getValueType(),
3162 getValue(I.getOperand(1)));
3165 setValue(&I, result);
3168 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3169 /// limited-precision mode.
3171 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3173 DebugLoc dl = getCurDebugLoc();
3175 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3176 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3177 SDValue Op = getValue(I.getOperand(1));
3178 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3180 // Get the exponent.
3181 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3183 // Get the significand and build it into a floating-point number with
3185 SDValue X = GetSignificand(DAG, Op1, dl);
3187 // Different possible minimax approximations of significand in
3188 // floating-point for various degrees of accuracy over [1,2].
3189 if (LimitFloatPrecision <= 6) {
3190 // For floating-point precision of 6:
3192 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3194 // error 0.0049451742, which is more than 7 bits
3195 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3196 getF32Constant(DAG, 0xbeb08fe0));
3197 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3198 getF32Constant(DAG, 0x40019463));
3199 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3200 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3201 getF32Constant(DAG, 0x3fd6633d));
3203 result = DAG.getNode(ISD::FADD, dl,
3204 MVT::f32, LogOfExponent, Log2ofMantissa);
3205 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3206 // For floating-point precision of 12:
3212 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3214 // error 0.0000876136000, which is better than 13 bits
3215 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3216 getF32Constant(DAG, 0xbda7262e));
3217 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3218 getF32Constant(DAG, 0x3f25280b));
3219 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3220 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3221 getF32Constant(DAG, 0x4007b923));
3222 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3223 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3224 getF32Constant(DAG, 0x40823e2f));
3225 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3226 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3227 getF32Constant(DAG, 0x4020d29c));
3229 result = DAG.getNode(ISD::FADD, dl,
3230 MVT::f32, LogOfExponent, Log2ofMantissa);
3231 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3232 // For floating-point precision of 18:
3241 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3243 // error 0.0000018516, which is better than 18 bits
3244 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3245 getF32Constant(DAG, 0xbcd2769e));
3246 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3247 getF32Constant(DAG, 0x3e8ce0b9));
3248 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3249 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3250 getF32Constant(DAG, 0x3fa22ae7));
3251 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3252 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3253 getF32Constant(DAG, 0x40525723));
3254 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3255 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3256 getF32Constant(DAG, 0x40aaf200));
3257 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3258 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3259 getF32Constant(DAG, 0x40c39dad));
3260 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3261 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3262 getF32Constant(DAG, 0x4042902c));
3264 result = DAG.getNode(ISD::FADD, dl,
3265 MVT::f32, LogOfExponent, Log2ofMantissa);
3268 // No special expansion.
3269 result = DAG.getNode(ISD::FLOG2, dl,
3270 getValue(I.getOperand(1)).getValueType(),
3271 getValue(I.getOperand(1)));
3274 setValue(&I, result);
3277 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3278 /// limited-precision mode.
3280 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3282 DebugLoc dl = getCurDebugLoc();
3284 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3285 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3286 SDValue Op = getValue(I.getOperand(1));
3287 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3289 // Scale the exponent by log10(2) [0.30102999f].
3290 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3291 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3292 getF32Constant(DAG, 0x3e9a209a));
3294 // Get the significand and build it into a floating-point number with
3296 SDValue X = GetSignificand(DAG, Op1, dl);
3298 if (LimitFloatPrecision <= 6) {
3299 // For floating-point precision of 6:
3301 // Log10ofMantissa =
3303 // (0.60948995f - 0.10380950f * x) * x;
3305 // error 0.0014886165, which is 6 bits
3306 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3307 getF32Constant(DAG, 0xbdd49a13));
3308 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3309 getF32Constant(DAG, 0x3f1c0789));
3310 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3311 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3312 getF32Constant(DAG, 0x3f011300));
3314 result = DAG.getNode(ISD::FADD, dl,
3315 MVT::f32, LogOfExponent, Log10ofMantissa);
3316 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3317 // For floating-point precision of 12:
3319 // Log10ofMantissa =
3322 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3324 // error 0.00019228036, which is better than 12 bits
3325 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3326 getF32Constant(DAG, 0x3d431f31));
3327 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3328 getF32Constant(DAG, 0x3ea21fb2));
3329 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3330 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3331 getF32Constant(DAG, 0x3f6ae232));
3332 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3333 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3334 getF32Constant(DAG, 0x3f25f7c3));
3336 result = DAG.getNode(ISD::FADD, dl,
3337 MVT::f32, LogOfExponent, Log10ofMantissa);
3338 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3339 // For floating-point precision of 18:
3341 // Log10ofMantissa =
3346 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3348 // error 0.0000037995730, which is better than 18 bits
3349 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3350 getF32Constant(DAG, 0x3c5d51ce));
3351 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3352 getF32Constant(DAG, 0x3e00685a));
3353 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3354 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3355 getF32Constant(DAG, 0x3efb6798));
3356 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3357 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3358 getF32Constant(DAG, 0x3f88d192));
3359 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3360 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3361 getF32Constant(DAG, 0x3fc4316c));
3362 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3363 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3364 getF32Constant(DAG, 0x3f57ce70));
3366 result = DAG.getNode(ISD::FADD, dl,
3367 MVT::f32, LogOfExponent, Log10ofMantissa);
3370 // No special expansion.
3371 result = DAG.getNode(ISD::FLOG10, dl,
3372 getValue(I.getOperand(1)).getValueType(),
3373 getValue(I.getOperand(1)));
3376 setValue(&I, result);
3379 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3380 /// limited-precision mode.
3382 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3384 DebugLoc dl = getCurDebugLoc();
3386 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3387 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3388 SDValue Op = getValue(I.getOperand(1));
3390 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3392 // FractionalPartOfX = x - (float)IntegerPartOfX;
3393 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3394 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3396 // IntegerPartOfX <<= 23;
3397 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3398 DAG.getConstant(23, TLI.getPointerTy()));
3400 if (LimitFloatPrecision <= 6) {
3401 // For floating-point precision of 6:
3403 // TwoToFractionalPartOfX =
3405 // (0.735607626f + 0.252464424f * x) * x;
3407 // error 0.0144103317, which is 6 bits
3408 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3409 getF32Constant(DAG, 0x3e814304));
3410 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3411 getF32Constant(DAG, 0x3f3c50c8));
3412 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3413 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3414 getF32Constant(DAG, 0x3f7f5e7e));
3415 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3416 SDValue TwoToFractionalPartOfX =
3417 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3419 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3420 MVT::f32, TwoToFractionalPartOfX);
3421 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3422 // For floating-point precision of 12:
3424 // TwoToFractionalPartOfX =
3427 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3429 // error 0.000107046256, which is 13 to 14 bits
3430 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3431 getF32Constant(DAG, 0x3da235e3));
3432 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3433 getF32Constant(DAG, 0x3e65b8f3));
3434 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3435 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3436 getF32Constant(DAG, 0x3f324b07));
3437 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3438 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3439 getF32Constant(DAG, 0x3f7ff8fd));
3440 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3441 SDValue TwoToFractionalPartOfX =
3442 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3444 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3445 MVT::f32, TwoToFractionalPartOfX);
3446 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3447 // For floating-point precision of 18:
3449 // TwoToFractionalPartOfX =
3453 // (0.554906021e-1f +
3454 // (0.961591928e-2f +
3455 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3456 // error 2.47208000*10^(-7), which is better than 18 bits
3457 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3458 getF32Constant(DAG, 0x3924b03e));
3459 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3460 getF32Constant(DAG, 0x3ab24b87));
3461 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3462 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3463 getF32Constant(DAG, 0x3c1d8c17));
3464 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3465 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3466 getF32Constant(DAG, 0x3d634a1d));
3467 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3468 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3469 getF32Constant(DAG, 0x3e75fe14));
3470 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3471 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3472 getF32Constant(DAG, 0x3f317234));
3473 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3474 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3475 getF32Constant(DAG, 0x3f800000));
3476 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3477 SDValue TwoToFractionalPartOfX =
3478 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3480 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3481 MVT::f32, TwoToFractionalPartOfX);
3484 // No special expansion.
3485 result = DAG.getNode(ISD::FEXP2, dl,
3486 getValue(I.getOperand(1)).getValueType(),
3487 getValue(I.getOperand(1)));
3490 setValue(&I, result);
3493 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3494 /// limited-precision mode with x == 10.0f.
3496 SelectionDAGBuilder::visitPow(const CallInst &I) {
3498 const Value *Val = I.getOperand(1);
3499 DebugLoc dl = getCurDebugLoc();
3500 bool IsExp10 = false;
3502 if (getValue(Val).getValueType() == MVT::f32 &&
3503 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3504 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3505 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3506 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3508 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3513 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3514 SDValue Op = getValue(I.getOperand(2));
3516 // Put the exponent in the right bit position for later addition to the
3519 // #define LOG2OF10 3.3219281f
3520 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3521 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3522 getF32Constant(DAG, 0x40549a78));
3523 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3525 // FractionalPartOfX = x - (float)IntegerPartOfX;
3526 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3527 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3529 // IntegerPartOfX <<= 23;
3530 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3531 DAG.getConstant(23, TLI.getPointerTy()));
3533 if (LimitFloatPrecision <= 6) {
3534 // For floating-point precision of 6:
3536 // twoToFractionalPartOfX =
3538 // (0.735607626f + 0.252464424f * x) * x;
3540 // error 0.0144103317, which is 6 bits
3541 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3542 getF32Constant(DAG, 0x3e814304));
3543 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3544 getF32Constant(DAG, 0x3f3c50c8));
3545 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3546 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3547 getF32Constant(DAG, 0x3f7f5e7e));
3548 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3549 SDValue TwoToFractionalPartOfX =
3550 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3552 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3553 MVT::f32, TwoToFractionalPartOfX);
3554 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3555 // For floating-point precision of 12:
3557 // TwoToFractionalPartOfX =
3560 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3562 // error 0.000107046256, which is 13 to 14 bits
3563 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3564 getF32Constant(DAG, 0x3da235e3));
3565 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3566 getF32Constant(DAG, 0x3e65b8f3));
3567 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3568 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3569 getF32Constant(DAG, 0x3f324b07));
3570 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3571 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3572 getF32Constant(DAG, 0x3f7ff8fd));
3573 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3574 SDValue TwoToFractionalPartOfX =
3575 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3577 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3578 MVT::f32, TwoToFractionalPartOfX);
3579 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3580 // For floating-point precision of 18:
3582 // TwoToFractionalPartOfX =
3586 // (0.554906021e-1f +
3587 // (0.961591928e-2f +
3588 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3589 // error 2.47208000*10^(-7), which is better than 18 bits
3590 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3591 getF32Constant(DAG, 0x3924b03e));
3592 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3593 getF32Constant(DAG, 0x3ab24b87));
3594 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3595 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3596 getF32Constant(DAG, 0x3c1d8c17));
3597 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3598 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3599 getF32Constant(DAG, 0x3d634a1d));
3600 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3601 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3602 getF32Constant(DAG, 0x3e75fe14));
3603 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3604 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3605 getF32Constant(DAG, 0x3f317234));
3606 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3607 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3608 getF32Constant(DAG, 0x3f800000));
3609 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3610 SDValue TwoToFractionalPartOfX =
3611 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3613 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3614 MVT::f32, TwoToFractionalPartOfX);
3617 // No special expansion.
3618 result = DAG.getNode(ISD::FPOW, dl,
3619 getValue(I.getOperand(1)).getValueType(),
3620 getValue(I.getOperand(1)),
3621 getValue(I.getOperand(2)));
3624 setValue(&I, result);
3628 /// ExpandPowI - Expand a llvm.powi intrinsic.
3629 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3630 SelectionDAG &DAG) {
3631 // If RHS is a constant, we can expand this out to a multiplication tree,
3632 // otherwise we end up lowering to a call to __powidf2 (for example). When
3633 // optimizing for size, we only want to do this if the expansion would produce
3634 // a small number of multiplies, otherwise we do the full expansion.
3635 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3636 // Get the exponent as a positive value.
3637 unsigned Val = RHSC->getSExtValue();
3638 if ((int)Val < 0) Val = -Val;
3640 // powi(x, 0) -> 1.0
3642 return DAG.getConstantFP(1.0, LHS.getValueType());
3644 const Function *F = DAG.getMachineFunction().getFunction();
3645 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3646 // If optimizing for size, don't insert too many multiplies. This
3647 // inserts up to 5 multiplies.
3648 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3649 // We use the simple binary decomposition method to generate the multiply
3650 // sequence. There are more optimal ways to do this (for example,
3651 // powi(x,15) generates one more multiply than it should), but this has
3652 // the benefit of being both really simple and much better than a libcall.
3653 SDValue Res; // Logically starts equal to 1.0
3654 SDValue CurSquare = LHS;
3658 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3660 Res = CurSquare; // 1.0*CurSquare.
3663 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3664 CurSquare, CurSquare);
3668 // If the original was negative, invert the result, producing 1/(x*x*x).
3669 if (RHSC->getSExtValue() < 0)
3670 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3671 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3676 // Otherwise, expand to a libcall.
3677 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3681 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3682 /// we want to emit this as a call to a named external function, return the name
3683 /// otherwise lower it and return null.
3685 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
3686 DebugLoc dl = getCurDebugLoc();
3689 switch (Intrinsic) {
3691 // By default, turn this into a target intrinsic node.
3692 visitTargetIntrinsic(I, Intrinsic);
3694 case Intrinsic::vastart: visitVAStart(I); return 0;
3695 case Intrinsic::vaend: visitVAEnd(I); return 0;
3696 case Intrinsic::vacopy: visitVACopy(I); return 0;
3697 case Intrinsic::returnaddress:
3698 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3699 getValue(I.getOperand(1))));
3701 case Intrinsic::frameaddress:
3702 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3703 getValue(I.getOperand(1))));
3705 case Intrinsic::setjmp:
3706 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3707 case Intrinsic::longjmp:
3708 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3709 case Intrinsic::memcpy: {
3710 // Assert for address < 256 since we support only user defined address
3712 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3714 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3716 "Unknown address space");
3717 SDValue Op1 = getValue(I.getOperand(1));
3718 SDValue Op2 = getValue(I.getOperand(2));
3719 SDValue Op3 = getValue(I.getOperand(3));
3720 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3721 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3722 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
3723 I.getOperand(1), 0, I.getOperand(2), 0));
3726 case Intrinsic::memset: {
3727 // Assert for address < 256 since we support only user defined address
3729 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3731 "Unknown address space");
3732 SDValue Op1 = getValue(I.getOperand(1));
3733 SDValue Op2 = getValue(I.getOperand(2));
3734 SDValue Op3 = getValue(I.getOperand(3));
3735 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3736 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3737 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3738 I.getOperand(1), 0));
3741 case Intrinsic::memmove: {
3742 // Assert for address < 256 since we support only user defined address
3744 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3746 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3748 "Unknown address space");
3749 SDValue Op1 = getValue(I.getOperand(1));
3750 SDValue Op2 = getValue(I.getOperand(2));
3751 SDValue Op3 = getValue(I.getOperand(3));
3752 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3753 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3755 // If the source and destination are known to not be aliases, we can
3756 // lower memmove as memcpy.
3757 uint64_t Size = -1ULL;
3758 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3759 Size = C->getZExtValue();
3760 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3761 AliasAnalysis::NoAlias) {
3762 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3763 false, I.getOperand(1), 0, I.getOperand(2), 0));
3767 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3768 I.getOperand(1), 0, I.getOperand(2), 0));
3771 case Intrinsic::dbg_declare: {
3772 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3773 // The real handling of this intrinsic is in FastISel.
3774 if (OptLevel != CodeGenOpt::None)
3775 // FIXME: Variable debug info is not supported here.
3777 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3778 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3781 MDNode *Variable = DI.getVariable();
3782 const Value *Address = DI.getAddress();
3785 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3786 Address = BCI->getOperand(0);
3787 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3788 // Don't handle byval struct arguments or VLAs, for example.
3791 DenseMap<const AllocaInst*, int>::iterator SI =
3792 FuncInfo.StaticAllocaMap.find(AI);
3793 if (SI == FuncInfo.StaticAllocaMap.end())
3795 int FI = SI->second;
3797 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3798 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
3799 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
3802 case Intrinsic::dbg_value: {
3803 const DbgValueInst &DI = cast<DbgValueInst>(I);
3804 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3807 MDNode *Variable = DI.getVariable();
3808 uint64_t Offset = DI.getOffset();
3809 const Value *V = DI.getValue();
3813 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
3814 // but do not always have a corresponding SDNode built. The SDNodeOrder
3815 // absolute, but not relative, values are different depending on whether
3816 // debug info exists.
3818 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
3819 DAG.AddDbgValue(DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder));
3821 SDValue &N = NodeMap[V];
3823 DAG.AddDbgValue(DAG.getDbgValue(Variable, N.getNode(),
3824 N.getResNo(), Offset, dl, SDNodeOrder),
3827 // We may expand this to cover more cases. One case where we have no
3828 // data available is an unreferenced parameter; we need this fallback.
3829 DAG.AddDbgValue(DAG.getDbgValue(Variable,
3830 UndefValue::get(V->getType()),
3831 Offset, dl, SDNodeOrder));
3834 // Build a debug info table entry.
3835 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3836 V = BCI->getOperand(0);
3837 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
3838 // Don't handle byval struct arguments or VLAs, for example.
3841 DenseMap<const AllocaInst*, int>::iterator SI =
3842 FuncInfo.StaticAllocaMap.find(AI);
3843 if (SI == FuncInfo.StaticAllocaMap.end())
3845 int FI = SI->second;
3847 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3848 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
3849 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
3852 case Intrinsic::eh_exception: {
3853 // Insert the EXCEPTIONADDR instruction.
3854 assert(FuncInfo.MBBMap[I.getParent()]->isLandingPad() &&
3855 "Call to eh.exception not in landing pad!");
3856 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3858 Ops[0] = DAG.getRoot();
3859 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3861 DAG.setRoot(Op.getValue(1));
3865 case Intrinsic::eh_selector: {
3866 MachineBasicBlock *CallMBB = FuncInfo.MBBMap[I.getParent()];
3867 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3868 if (CallMBB->isLandingPad())
3869 AddCatchInfo(I, &MMI, CallMBB);
3872 FuncInfo.CatchInfoLost.insert(&I);
3874 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3875 unsigned Reg = TLI.getExceptionSelectorRegister();
3876 if (Reg) FuncInfo.MBBMap[I.getParent()]->addLiveIn(Reg);
3879 // Insert the EHSELECTION instruction.
3880 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3882 Ops[0] = getValue(I.getOperand(1));
3884 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3885 DAG.setRoot(Op.getValue(1));
3886 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
3890 case Intrinsic::eh_typeid_for: {
3891 // Find the type id for the given typeinfo.
3892 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3893 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
3894 Res = DAG.getConstant(TypeID, MVT::i32);
3899 case Intrinsic::eh_return_i32:
3900 case Intrinsic::eh_return_i64:
3901 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
3902 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3905 getValue(I.getOperand(1)),
3906 getValue(I.getOperand(2))));
3908 case Intrinsic::eh_unwind_init:
3909 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
3911 case Intrinsic::eh_dwarf_cfa: {
3912 EVT VT = getValue(I.getOperand(1)).getValueType();
3913 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3914 TLI.getPointerTy());
3915 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3917 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
3918 TLI.getPointerTy()),
3920 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
3922 DAG.getConstant(0, TLI.getPointerTy()));
3923 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3927 case Intrinsic::eh_sjlj_callsite: {
3928 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3929 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3930 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3931 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
3933 MMI.setCurrentCallSite(CI->getZExtValue());
3937 case Intrinsic::convertff:
3938 case Intrinsic::convertfsi:
3939 case Intrinsic::convertfui:
3940 case Intrinsic::convertsif:
3941 case Intrinsic::convertuif:
3942 case Intrinsic::convertss:
3943 case Intrinsic::convertsu:
3944 case Intrinsic::convertus:
3945 case Intrinsic::convertuu: {
3946 ISD::CvtCode Code = ISD::CVT_INVALID;
3947 switch (Intrinsic) {
3948 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3949 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3950 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3951 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3952 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3953 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3954 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3955 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3956 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3958 EVT DestVT = TLI.getValueType(I.getType());
3959 const Value *Op1 = I.getOperand(1);
3960 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3961 DAG.getValueType(DestVT),
3962 DAG.getValueType(getValue(Op1).getValueType()),
3963 getValue(I.getOperand(2)),
3964 getValue(I.getOperand(3)),
3969 case Intrinsic::sqrt:
3970 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3971 getValue(I.getOperand(1)).getValueType(),
3972 getValue(I.getOperand(1))));
3974 case Intrinsic::powi:
3975 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3976 getValue(I.getOperand(2)), DAG));
3978 case Intrinsic::sin:
3979 setValue(&I, DAG.getNode(ISD::FSIN, dl,
3980 getValue(I.getOperand(1)).getValueType(),
3981 getValue(I.getOperand(1))));
3983 case Intrinsic::cos:
3984 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3985 getValue(I.getOperand(1)).getValueType(),
3986 getValue(I.getOperand(1))));
3988 case Intrinsic::log:
3991 case Intrinsic::log2:
3994 case Intrinsic::log10:
3997 case Intrinsic::exp:
4000 case Intrinsic::exp2:
4003 case Intrinsic::pow:
4006 case Intrinsic::convert_to_fp16:
4007 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4008 MVT::i16, getValue(I.getOperand(1))));
4010 case Intrinsic::convert_from_fp16:
4011 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4012 MVT::f32, getValue(I.getOperand(1))));
4014 case Intrinsic::pcmarker: {
4015 SDValue Tmp = getValue(I.getOperand(1));
4016 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4019 case Intrinsic::readcyclecounter: {
4020 SDValue Op = getRoot();
4021 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4022 DAG.getVTList(MVT::i64, MVT::Other),
4025 DAG.setRoot(Res.getValue(1));
4028 case Intrinsic::bswap:
4029 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4030 getValue(I.getOperand(1)).getValueType(),
4031 getValue(I.getOperand(1))));
4033 case Intrinsic::cttz: {
4034 SDValue Arg = getValue(I.getOperand(1));
4035 EVT Ty = Arg.getValueType();
4036 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4039 case Intrinsic::ctlz: {
4040 SDValue Arg = getValue(I.getOperand(1));
4041 EVT Ty = Arg.getValueType();
4042 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4045 case Intrinsic::ctpop: {
4046 SDValue Arg = getValue(I.getOperand(1));
4047 EVT Ty = Arg.getValueType();
4048 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4051 case Intrinsic::stacksave: {
4052 SDValue Op = getRoot();
4053 Res = DAG.getNode(ISD::STACKSAVE, dl,
4054 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4056 DAG.setRoot(Res.getValue(1));
4059 case Intrinsic::stackrestore: {
4060 Res = getValue(I.getOperand(1));
4061 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4064 case Intrinsic::stackprotector: {
4065 // Emit code into the DAG to store the stack guard onto the stack.
4066 MachineFunction &MF = DAG.getMachineFunction();
4067 MachineFrameInfo *MFI = MF.getFrameInfo();
4068 EVT PtrTy = TLI.getPointerTy();
4070 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4071 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4073 int FI = FuncInfo.StaticAllocaMap[Slot];
4074 MFI->setStackProtectorIndex(FI);
4076 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4078 // Store the stack protector onto the stack.
4079 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4080 PseudoSourceValue::getFixedStack(FI),
4086 case Intrinsic::objectsize: {
4087 // If we don't know by now, we're never going to know.
4088 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4090 assert(CI && "Non-constant type in __builtin_object_size?");
4092 SDValue Arg = getValue(I.getOperand(0));
4093 EVT Ty = Arg.getValueType();
4095 if (CI->getZExtValue() == 0)
4096 Res = DAG.getConstant(-1ULL, Ty);
4098 Res = DAG.getConstant(0, Ty);
4103 case Intrinsic::var_annotation:
4104 // Discard annotate attributes
4107 case Intrinsic::init_trampoline: {
4108 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4112 Ops[1] = getValue(I.getOperand(1));
4113 Ops[2] = getValue(I.getOperand(2));
4114 Ops[3] = getValue(I.getOperand(3));
4115 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4116 Ops[5] = DAG.getSrcValue(F);
4118 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4119 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4123 DAG.setRoot(Res.getValue(1));
4126 case Intrinsic::gcroot:
4128 const Value *Alloca = I.getOperand(1);
4129 const Constant *TypeMap = cast<Constant>(I.getOperand(2));
4131 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4132 GFI->addStackRoot(FI->getIndex(), TypeMap);
4135 case Intrinsic::gcread:
4136 case Intrinsic::gcwrite:
4137 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4139 case Intrinsic::flt_rounds:
4140 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4142 case Intrinsic::trap:
4143 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4145 case Intrinsic::uadd_with_overflow:
4146 return implVisitAluOverflow(I, ISD::UADDO);
4147 case Intrinsic::sadd_with_overflow:
4148 return implVisitAluOverflow(I, ISD::SADDO);
4149 case Intrinsic::usub_with_overflow:
4150 return implVisitAluOverflow(I, ISD::USUBO);
4151 case Intrinsic::ssub_with_overflow:
4152 return implVisitAluOverflow(I, ISD::SSUBO);
4153 case Intrinsic::umul_with_overflow:
4154 return implVisitAluOverflow(I, ISD::UMULO);
4155 case Intrinsic::smul_with_overflow:
4156 return implVisitAluOverflow(I, ISD::SMULO);
4158 case Intrinsic::prefetch: {
4161 Ops[1] = getValue(I.getOperand(1));
4162 Ops[2] = getValue(I.getOperand(2));
4163 Ops[3] = getValue(I.getOperand(3));
4164 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4168 case Intrinsic::memory_barrier: {
4171 for (int x = 1; x < 6; ++x)
4172 Ops[x] = getValue(I.getOperand(x));
4174 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4177 case Intrinsic::atomic_cmp_swap: {
4178 SDValue Root = getRoot();
4180 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4181 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4183 getValue(I.getOperand(1)),
4184 getValue(I.getOperand(2)),
4185 getValue(I.getOperand(3)),
4188 DAG.setRoot(L.getValue(1));
4191 case Intrinsic::atomic_load_add:
4192 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4193 case Intrinsic::atomic_load_sub:
4194 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4195 case Intrinsic::atomic_load_or:
4196 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4197 case Intrinsic::atomic_load_xor:
4198 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4199 case Intrinsic::atomic_load_and:
4200 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4201 case Intrinsic::atomic_load_nand:
4202 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4203 case Intrinsic::atomic_load_max:
4204 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4205 case Intrinsic::atomic_load_min:
4206 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4207 case Intrinsic::atomic_load_umin:
4208 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4209 case Intrinsic::atomic_load_umax:
4210 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4211 case Intrinsic::atomic_swap:
4212 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4214 case Intrinsic::invariant_start:
4215 case Intrinsic::lifetime_start:
4216 // Discard region information.
4217 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4219 case Intrinsic::invariant_end:
4220 case Intrinsic::lifetime_end:
4221 // Discard region information.
4226 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4228 MachineBasicBlock *LandingPad) {
4229 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4230 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4231 const Type *RetTy = FTy->getReturnType();
4232 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4233 MCSymbol *BeginLabel = 0;
4235 TargetLowering::ArgListTy Args;
4236 TargetLowering::ArgListEntry Entry;
4237 Args.reserve(CS.arg_size());
4239 // Check whether the function can return without sret-demotion.
4240 SmallVector<EVT, 4> OutVTs;
4241 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4242 SmallVector<uint64_t, 4> Offsets;
4243 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4244 OutVTs, OutsFlags, TLI, &Offsets);
4246 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4247 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4249 SDValue DemoteStackSlot;
4251 if (!CanLowerReturn) {
4252 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4253 FTy->getReturnType());
4254 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4255 FTy->getReturnType());
4256 MachineFunction &MF = DAG.getMachineFunction();
4257 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4258 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4260 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4261 Entry.Node = DemoteStackSlot;
4262 Entry.Ty = StackSlotPtrType;
4263 Entry.isSExt = false;
4264 Entry.isZExt = false;
4265 Entry.isInReg = false;
4266 Entry.isSRet = true;
4267 Entry.isNest = false;
4268 Entry.isByVal = false;
4269 Entry.Alignment = Align;
4270 Args.push_back(Entry);
4271 RetTy = Type::getVoidTy(FTy->getContext());
4274 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4276 SDValue ArgNode = getValue(*i);
4277 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4279 unsigned attrInd = i - CS.arg_begin() + 1;
4280 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4281 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4282 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4283 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4284 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4285 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4286 Entry.Alignment = CS.getParamAlignment(attrInd);
4287 Args.push_back(Entry);
4291 // Insert a label before the invoke call to mark the try range. This can be
4292 // used to detect deletion of the invoke via the MachineModuleInfo.
4293 BeginLabel = MMI.getContext().CreateTempSymbol();
4295 // For SjLj, keep track of which landing pads go with which invokes
4296 // so as to maintain the ordering of pads in the LSDA.
4297 unsigned CallSiteIndex = MMI.getCurrentCallSite();
4298 if (CallSiteIndex) {
4299 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4300 // Now that the call site is handled, stop tracking it.
4301 MMI.setCurrentCallSite(0);
4304 // Both PendingLoads and PendingExports must be flushed here;
4305 // this call might not return.
4307 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4310 // Check if target-independent constraints permit a tail call here.
4311 // Target-dependent constraints are checked within TLI.LowerCallTo.
4313 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4316 std::pair<SDValue,SDValue> Result =
4317 TLI.LowerCallTo(getRoot(), RetTy,
4318 CS.paramHasAttr(0, Attribute::SExt),
4319 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4320 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4321 CS.getCallingConv(),
4323 !CS.getInstruction()->use_empty(),
4324 Callee, Args, DAG, getCurDebugLoc());
4325 assert((isTailCall || Result.second.getNode()) &&
4326 "Non-null chain expected with non-tail call!");
4327 assert((Result.second.getNode() || !Result.first.getNode()) &&
4328 "Null value expected with tail call!");
4329 if (Result.first.getNode()) {
4330 setValue(CS.getInstruction(), Result.first);
4331 } else if (!CanLowerReturn && Result.second.getNode()) {
4332 // The instruction result is the result of loading from the
4333 // hidden sret parameter.
4334 SmallVector<EVT, 1> PVTs;
4335 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4337 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4338 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4339 EVT PtrVT = PVTs[0];
4340 unsigned NumValues = OutVTs.size();
4341 SmallVector<SDValue, 4> Values(NumValues);
4342 SmallVector<SDValue, 4> Chains(NumValues);
4344 for (unsigned i = 0; i < NumValues; ++i) {
4345 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4347 DAG.getConstant(Offsets[i], PtrVT));
4348 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4349 Add, NULL, Offsets[i], false, false, 1);
4351 Chains[i] = L.getValue(1);
4354 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4355 MVT::Other, &Chains[0], NumValues);
4356 PendingLoads.push_back(Chain);
4358 // Collect the legal value parts into potentially illegal values
4359 // that correspond to the original function's return values.
4360 SmallVector<EVT, 4> RetTys;
4361 RetTy = FTy->getReturnType();
4362 ComputeValueVTs(TLI, RetTy, RetTys);
4363 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4364 SmallVector<SDValue, 4> ReturnValues;
4365 unsigned CurReg = 0;
4366 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4368 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4369 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4371 SDValue ReturnValue =
4372 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
4373 RegisterVT, VT, AssertOp);
4374 ReturnValues.push_back(ReturnValue);
4378 setValue(CS.getInstruction(),
4379 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4380 DAG.getVTList(&RetTys[0], RetTys.size()),
4381 &ReturnValues[0], ReturnValues.size()));
4385 // As a special case, a null chain means that a tail call has been emitted and
4386 // the DAG root is already updated.
4387 if (Result.second.getNode())
4388 DAG.setRoot(Result.second);
4393 // Insert a label at the end of the invoke call to mark the try range. This
4394 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4395 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
4396 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
4398 // Inform MachineModuleInfo of range.
4399 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
4403 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4404 /// value is equal or not-equal to zero.
4405 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
4406 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
4408 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4409 if (IC->isEquality())
4410 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4411 if (C->isNullValue())
4413 // Unknown instruction.
4419 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
4421 SelectionDAGBuilder &Builder) {
4423 // Check to see if this load can be trivially constant folded, e.g. if the
4424 // input is from a string literal.
4425 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4426 // Cast pointer to the type we really want to load.
4427 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
4428 PointerType::getUnqual(LoadTy));
4430 if (const Constant *LoadCst =
4431 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
4433 return Builder.getValue(LoadCst);
4436 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4437 // still constant memory, the input chain can be the entry node.
4439 bool ConstantMemory = false;
4441 // Do not serialize (non-volatile) loads of constant memory with anything.
4442 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4443 Root = Builder.DAG.getEntryNode();
4444 ConstantMemory = true;
4446 // Do not serialize non-volatile loads against each other.
4447 Root = Builder.DAG.getRoot();
4450 SDValue Ptr = Builder.getValue(PtrVal);
4451 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4452 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4454 false /*nontemporal*/, 1 /* align=1 */);
4456 if (!ConstantMemory)
4457 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4462 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4463 /// If so, return true and lower it, otherwise return false and it will be
4464 /// lowered like a normal call.
4465 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
4466 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4467 if (I.getNumOperands() != 4)
4470 const Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
4471 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
4472 !I.getOperand(3)->getType()->isIntegerTy() ||
4473 !I.getType()->isIntegerTy())
4476 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
4478 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4479 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
4480 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4481 bool ActuallyDoIt = true;
4484 switch (Size->getZExtValue()) {
4486 LoadVT = MVT::Other;
4488 ActuallyDoIt = false;
4492 LoadTy = Type::getInt16Ty(Size->getContext());
4496 LoadTy = Type::getInt32Ty(Size->getContext());
4500 LoadTy = Type::getInt64Ty(Size->getContext());
4504 LoadVT = MVT::v4i32;
4505 LoadTy = Type::getInt32Ty(Size->getContext());
4506 LoadTy = VectorType::get(LoadTy, 4);
4511 // This turns into unaligned loads. We only do this if the target natively
4512 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4513 // we'll only produce a small number of byte loads.
4515 // Require that we can find a legal MVT, and only do this if the target
4516 // supports unaligned loads of that type. Expanding into byte loads would
4518 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4519 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4520 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4521 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4522 ActuallyDoIt = false;
4526 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4527 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
4529 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4531 EVT CallVT = TLI.getValueType(I.getType(), true);
4532 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4542 void SelectionDAGBuilder::visitCall(const CallInst &I) {
4543 const char *RenameFn = 0;
4544 if (Function *F = I.getCalledFunction()) {
4545 if (F->isDeclaration()) {
4546 const TargetIntrinsicInfo *II = TM.getIntrinsicInfo();
4548 if (unsigned IID = II->getIntrinsicID(F)) {
4549 RenameFn = visitIntrinsicCall(I, IID);
4554 if (unsigned IID = F->getIntrinsicID()) {
4555 RenameFn = visitIntrinsicCall(I, IID);
4561 // Check for well-known libc/libm calls. If the function is internal, it
4562 // can't be a library call.
4563 if (!F->hasLocalLinkage() && F->hasName()) {
4564 StringRef Name = F->getName();
4565 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
4566 if (I.getNumOperands() == 3 && // Basic sanity checks.
4567 I.getOperand(1)->getType()->isFloatingPointTy() &&
4568 I.getType() == I.getOperand(1)->getType() &&
4569 I.getType() == I.getOperand(2)->getType()) {
4570 SDValue LHS = getValue(I.getOperand(1));
4571 SDValue RHS = getValue(I.getOperand(2));
4572 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4573 LHS.getValueType(), LHS, RHS));
4576 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4577 if (I.getNumOperands() == 2 && // Basic sanity checks.
4578 I.getOperand(1)->getType()->isFloatingPointTy() &&
4579 I.getType() == I.getOperand(1)->getType()) {
4580 SDValue Tmp = getValue(I.getOperand(1));
4581 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4582 Tmp.getValueType(), Tmp));
4585 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4586 if (I.getNumOperands() == 2 && // Basic sanity checks.
4587 I.getOperand(1)->getType()->isFloatingPointTy() &&
4588 I.getType() == I.getOperand(1)->getType() &&
4589 I.onlyReadsMemory()) {
4590 SDValue Tmp = getValue(I.getOperand(1));
4591 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4592 Tmp.getValueType(), Tmp));
4595 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4596 if (I.getNumOperands() == 2 && // Basic sanity checks.
4597 I.getOperand(1)->getType()->isFloatingPointTy() &&
4598 I.getType() == I.getOperand(1)->getType() &&
4599 I.onlyReadsMemory()) {
4600 SDValue Tmp = getValue(I.getOperand(1));
4601 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4602 Tmp.getValueType(), Tmp));
4605 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4606 if (I.getNumOperands() == 2 && // Basic sanity checks.
4607 I.getOperand(1)->getType()->isFloatingPointTy() &&
4608 I.getType() == I.getOperand(1)->getType() &&
4609 I.onlyReadsMemory()) {
4610 SDValue Tmp = getValue(I.getOperand(1));
4611 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4612 Tmp.getValueType(), Tmp));
4615 } else if (Name == "memcmp") {
4616 if (visitMemCmpCall(I))
4620 } else if (isa<InlineAsm>(I.getOperand(0))) {
4627 Callee = getValue(I.getOperand(0));
4629 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4631 // Check if we can potentially perform a tail call. More detailed checking is
4632 // be done within LowerCallTo, after more information about the call is known.
4633 LowerCallTo(&I, Callee, I.isTailCall());
4636 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4637 /// this value and returns the result as a ValueVT value. This uses
4638 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4639 /// If the Flag pointer is NULL, no flag is used.
4640 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4641 SDValue &Chain, SDValue *Flag) const {
4642 // Assemble the legal parts into the final values.
4643 SmallVector<SDValue, 4> Values(ValueVTs.size());
4644 SmallVector<SDValue, 8> Parts;
4645 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4646 // Copy the legal parts from the registers.
4647 EVT ValueVT = ValueVTs[Value];
4648 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4649 EVT RegisterVT = RegVTs[Value];
4651 Parts.resize(NumRegs);
4652 for (unsigned i = 0; i != NumRegs; ++i) {
4655 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4657 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4658 *Flag = P.getValue(2);
4661 Chain = P.getValue(1);
4663 // If the source register was virtual and if we know something about it,
4664 // add an assert node.
4665 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4666 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4667 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4668 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4669 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4670 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4672 unsigned RegSize = RegisterVT.getSizeInBits();
4673 unsigned NumSignBits = LOI.NumSignBits;
4674 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4676 // FIXME: We capture more information than the dag can represent. For
4677 // now, just use the tightest assertzext/assertsext possible.
4679 EVT FromVT(MVT::Other);
4680 if (NumSignBits == RegSize)
4681 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4682 else if (NumZeroBits >= RegSize-1)
4683 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4684 else if (NumSignBits > RegSize-8)
4685 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4686 else if (NumZeroBits >= RegSize-8)
4687 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4688 else if (NumSignBits > RegSize-16)
4689 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4690 else if (NumZeroBits >= RegSize-16)
4691 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4692 else if (NumSignBits > RegSize-32)
4693 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4694 else if (NumZeroBits >= RegSize-32)
4695 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4697 if (FromVT != MVT::Other)
4698 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4699 RegisterVT, P, DAG.getValueType(FromVT));
4706 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4707 NumRegs, RegisterVT, ValueVT);
4712 return DAG.getNode(ISD::MERGE_VALUES, dl,
4713 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4714 &Values[0], ValueVTs.size());
4717 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4718 /// specified value into the registers specified by this object. This uses
4719 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4720 /// If the Flag pointer is NULL, no flag is used.
4721 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4722 SDValue &Chain, SDValue *Flag) const {
4723 // Get the list of the values's legal parts.
4724 unsigned NumRegs = Regs.size();
4725 SmallVector<SDValue, 8> Parts(NumRegs);
4726 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4727 EVT ValueVT = ValueVTs[Value];
4728 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4729 EVT RegisterVT = RegVTs[Value];
4731 getCopyToParts(DAG, dl,
4732 Val.getValue(Val.getResNo() + Value),
4733 &Parts[Part], NumParts, RegisterVT);
4737 // Copy the parts into the registers.
4738 SmallVector<SDValue, 8> Chains(NumRegs);
4739 for (unsigned i = 0; i != NumRegs; ++i) {
4742 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4744 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4745 *Flag = Part.getValue(1);
4748 Chains[i] = Part.getValue(0);
4751 if (NumRegs == 1 || Flag)
4752 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4753 // flagged to it. That is the CopyToReg nodes and the user are considered
4754 // a single scheduling unit. If we create a TokenFactor and return it as
4755 // chain, then the TokenFactor is both a predecessor (operand) of the
4756 // user as well as a successor (the TF operands are flagged to the user).
4757 // c1, f1 = CopyToReg
4758 // c2, f2 = CopyToReg
4759 // c3 = TokenFactor c1, c2
4762 Chain = Chains[NumRegs-1];
4764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4767 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4768 /// operand list. This adds the code marker and includes the number of
4769 /// values added into it.
4770 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
4771 unsigned MatchingIdx,
4773 std::vector<SDValue> &Ops) const {
4774 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
4776 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
4777 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
4780 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4781 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4782 EVT RegisterVT = RegVTs[Value];
4783 for (unsigned i = 0; i != NumRegs; ++i) {
4784 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4785 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4790 /// isAllocatableRegister - If the specified register is safe to allocate,
4791 /// i.e. it isn't a stack pointer or some other special register, return the
4792 /// register class for the register. Otherwise, return null.
4793 static const TargetRegisterClass *
4794 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4795 const TargetLowering &TLI,
4796 const TargetRegisterInfo *TRI) {
4797 EVT FoundVT = MVT::Other;
4798 const TargetRegisterClass *FoundRC = 0;
4799 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4800 E = TRI->regclass_end(); RCI != E; ++RCI) {
4801 EVT ThisVT = MVT::Other;
4803 const TargetRegisterClass *RC = *RCI;
4804 // If none of the value types for this register class are valid, we
4805 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4806 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4808 if (TLI.isTypeLegal(*I)) {
4809 // If we have already found this register in a different register class,
4810 // choose the one with the largest VT specified. For example, on
4811 // PowerPC, we favor f64 register classes over f32.
4812 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4819 if (ThisVT == MVT::Other) continue;
4821 // NOTE: This isn't ideal. In particular, this might allocate the
4822 // frame pointer in functions that need it (due to them not being taken
4823 // out of allocation, because a variable sized allocation hasn't been seen
4824 // yet). This is a slight code pessimization, but should still work.
4825 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4826 E = RC->allocation_order_end(MF); I != E; ++I)
4828 // We found a matching register class. Keep looking at others in case
4829 // we find one with larger registers that this physreg is also in.
4840 /// AsmOperandInfo - This contains information for each constraint that we are
4842 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4843 public TargetLowering::AsmOperandInfo {
4845 /// CallOperand - If this is the result output operand or a clobber
4846 /// this is null, otherwise it is the incoming operand to the CallInst.
4847 /// This gets modified as the asm is processed.
4848 SDValue CallOperand;
4850 /// AssignedRegs - If this is a register or register class operand, this
4851 /// contains the set of register corresponding to the operand.
4852 RegsForValue AssignedRegs;
4854 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4855 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4858 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4859 /// busy in OutputRegs/InputRegs.
4860 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4861 std::set<unsigned> &OutputRegs,
4862 std::set<unsigned> &InputRegs,
4863 const TargetRegisterInfo &TRI) const {
4865 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4866 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4869 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4870 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4874 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4875 /// corresponds to. If there is no Value* for this operand, it returns
4877 EVT getCallOperandValEVT(LLVMContext &Context,
4878 const TargetLowering &TLI,
4879 const TargetData *TD) const {
4880 if (CallOperandVal == 0) return MVT::Other;
4882 if (isa<BasicBlock>(CallOperandVal))
4883 return TLI.getPointerTy();
4885 const llvm::Type *OpTy = CallOperandVal->getType();
4887 // If this is an indirect operand, the operand is a pointer to the
4890 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4892 report_fatal_error("Indirect operand for inline asm not a pointer!");
4893 OpTy = PtrTy->getElementType();
4896 // If OpTy is not a single value, it may be a struct/union that we
4897 // can tile with integers.
4898 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4899 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4908 OpTy = IntegerType::get(Context, BitSize);
4913 return TLI.getValueType(OpTy, true);
4917 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4919 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4920 const TargetRegisterInfo &TRI) {
4921 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4923 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4924 for (; *Aliases; ++Aliases)
4925 Regs.insert(*Aliases);
4928 } // end llvm namespace.
4931 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4932 /// specified operand. We prefer to assign virtual registers, to allow the
4933 /// register allocator to handle the assignment process. However, if the asm
4934 /// uses features that we can't model on machineinstrs, we have SDISel do the
4935 /// allocation. This produces generally horrible, but correct, code.
4937 /// OpInfo describes the operand.
4938 /// Input and OutputRegs are the set of already allocated physical registers.
4940 void SelectionDAGBuilder::
4941 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4942 std::set<unsigned> &OutputRegs,
4943 std::set<unsigned> &InputRegs) {
4944 LLVMContext &Context = FuncInfo.Fn->getContext();
4946 // Compute whether this value requires an input register, an output register,
4948 bool isOutReg = false;
4949 bool isInReg = false;
4950 switch (OpInfo.Type) {
4951 case InlineAsm::isOutput:
4954 // If there is an input constraint that matches this, we need to reserve
4955 // the input register so no other inputs allocate to it.
4956 isInReg = OpInfo.hasMatchingInput();
4958 case InlineAsm::isInput:
4962 case InlineAsm::isClobber:
4969 MachineFunction &MF = DAG.getMachineFunction();
4970 SmallVector<unsigned, 4> Regs;
4972 // If this is a constraint for a single physreg, or a constraint for a
4973 // register class, find it.
4974 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4975 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4976 OpInfo.ConstraintVT);
4978 unsigned NumRegs = 1;
4979 if (OpInfo.ConstraintVT != MVT::Other) {
4980 // If this is a FP input in an integer register (or visa versa) insert a bit
4981 // cast of the input value. More generally, handle any case where the input
4982 // value disagrees with the register class we plan to stick this in.
4983 if (OpInfo.Type == InlineAsm::isInput &&
4984 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4985 // Try to convert to the first EVT that the reg class contains. If the
4986 // types are identical size, use a bitcast to convert (e.g. two differing
4988 EVT RegVT = *PhysReg.second->vt_begin();
4989 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4990 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4991 RegVT, OpInfo.CallOperand);
4992 OpInfo.ConstraintVT = RegVT;
4993 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4994 // If the input is a FP value and we want it in FP registers, do a
4995 // bitcast to the corresponding integer type. This turns an f64 value
4996 // into i64, which can be passed with two i32 values on a 32-bit
4998 RegVT = EVT::getIntegerVT(Context,
4999 OpInfo.ConstraintVT.getSizeInBits());
5000 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5001 RegVT, OpInfo.CallOperand);
5002 OpInfo.ConstraintVT = RegVT;
5006 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5010 EVT ValueVT = OpInfo.ConstraintVT;
5012 // If this is a constraint for a specific physical register, like {r17},
5014 if (unsigned AssignedReg = PhysReg.first) {
5015 const TargetRegisterClass *RC = PhysReg.second;
5016 if (OpInfo.ConstraintVT == MVT::Other)
5017 ValueVT = *RC->vt_begin();
5019 // Get the actual register value type. This is important, because the user
5020 // may have asked for (e.g.) the AX register in i32 type. We need to
5021 // remember that AX is actually i16 to get the right extension.
5022 RegVT = *RC->vt_begin();
5024 // This is a explicit reference to a physical register.
5025 Regs.push_back(AssignedReg);
5027 // If this is an expanded reference, add the rest of the regs to Regs.
5029 TargetRegisterClass::iterator I = RC->begin();
5030 for (; *I != AssignedReg; ++I)
5031 assert(I != RC->end() && "Didn't find reg!");
5033 // Already added the first reg.
5035 for (; NumRegs; --NumRegs, ++I) {
5036 assert(I != RC->end() && "Ran out of registers to allocate!");
5041 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5042 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5043 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5047 // Otherwise, if this was a reference to an LLVM register class, create vregs
5048 // for this reference.
5049 if (const TargetRegisterClass *RC = PhysReg.second) {
5050 RegVT = *RC->vt_begin();
5051 if (OpInfo.ConstraintVT == MVT::Other)
5054 // Create the appropriate number of virtual registers.
5055 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5056 for (; NumRegs; --NumRegs)
5057 Regs.push_back(RegInfo.createVirtualRegister(RC));
5059 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5063 // This is a reference to a register class that doesn't directly correspond
5064 // to an LLVM register class. Allocate NumRegs consecutive, available,
5065 // registers from the class.
5066 std::vector<unsigned> RegClassRegs
5067 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5068 OpInfo.ConstraintVT);
5070 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5071 unsigned NumAllocated = 0;
5072 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5073 unsigned Reg = RegClassRegs[i];
5074 // See if this register is available.
5075 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5076 (isInReg && InputRegs.count(Reg))) { // Already used.
5077 // Make sure we find consecutive registers.
5082 // Check to see if this register is allocatable (i.e. don't give out the
5084 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5085 if (!RC) { // Couldn't allocate this register.
5086 // Reset NumAllocated to make sure we return consecutive registers.
5091 // Okay, this register is good, we can use it.
5094 // If we allocated enough consecutive registers, succeed.
5095 if (NumAllocated == NumRegs) {
5096 unsigned RegStart = (i-NumAllocated)+1;
5097 unsigned RegEnd = i+1;
5098 // Mark all of the allocated registers used.
5099 for (unsigned i = RegStart; i != RegEnd; ++i)
5100 Regs.push_back(RegClassRegs[i]);
5102 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5103 OpInfo.ConstraintVT);
5104 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5109 // Otherwise, we couldn't allocate enough registers for this.
5112 /// visitInlineAsm - Handle a call to an InlineAsm object.
5114 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5115 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5117 /// ConstraintOperands - Information about all of the constraints.
5118 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5120 std::set<unsigned> OutputRegs, InputRegs;
5122 // Do a prepass over the constraints, canonicalizing them, and building up the
5123 // ConstraintOperands list.
5124 std::vector<InlineAsm::ConstraintInfo>
5125 ConstraintInfos = IA->ParseConstraints();
5127 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5129 SDValue Chain, Flag;
5131 // We won't need to flush pending loads if this asm doesn't touch
5132 // memory and is nonvolatile.
5133 if (hasMemory || IA->hasSideEffects())
5136 Chain = DAG.getRoot();
5138 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5139 unsigned ResNo = 0; // ResNo - The result number of the next output.
5140 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5141 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5142 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5144 EVT OpVT = MVT::Other;
5146 // Compute the value type for each operand.
5147 switch (OpInfo.Type) {
5148 case InlineAsm::isOutput:
5149 // Indirect outputs just consume an argument.
5150 if (OpInfo.isIndirect) {
5151 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5155 // The return value of the call is this value. As such, there is no
5156 // corresponding argument.
5157 assert(!CS.getType()->isVoidTy() &&
5159 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5160 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5162 assert(ResNo == 0 && "Asm only has one result!");
5163 OpVT = TLI.getValueType(CS.getType());
5167 case InlineAsm::isInput:
5168 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5170 case InlineAsm::isClobber:
5175 // If this is an input or an indirect output, process the call argument.
5176 // BasicBlocks are labels, currently appearing only in asm's.
5177 if (OpInfo.CallOperandVal) {
5178 // Strip bitcasts, if any. This mostly comes up for functions.
5179 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5181 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5182 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5184 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5187 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5190 OpInfo.ConstraintVT = OpVT;
5193 // Second pass over the constraints: compute which constraint option to use
5194 // and assign registers to constraints that want a specific physreg.
5195 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5196 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5198 // If this is an output operand with a matching input operand, look up the
5199 // matching input. If their types mismatch, e.g. one is an integer, the
5200 // other is floating point, or their sizes are different, flag it as an
5202 if (OpInfo.hasMatchingInput()) {
5203 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5205 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5206 if ((OpInfo.ConstraintVT.isInteger() !=
5207 Input.ConstraintVT.isInteger()) ||
5208 (OpInfo.ConstraintVT.getSizeInBits() !=
5209 Input.ConstraintVT.getSizeInBits())) {
5210 report_fatal_error("Unsupported asm: input constraint"
5211 " with a matching output constraint of"
5212 " incompatible type!");
5214 Input.ConstraintVT = OpInfo.ConstraintVT;
5218 // Compute the constraint code and ConstraintType to use.
5219 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5221 // If this is a memory input, and if the operand is not indirect, do what we
5222 // need to to provide an address for the memory input.
5223 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5224 !OpInfo.isIndirect) {
5225 assert(OpInfo.Type == InlineAsm::isInput &&
5226 "Can only indirectify direct input operands!");
5228 // Memory operands really want the address of the value. If we don't have
5229 // an indirect input, put it in the constpool if we can, otherwise spill
5230 // it to a stack slot.
5232 // If the operand is a float, integer, or vector constant, spill to a
5233 // constant pool entry to get its address.
5234 const Value *OpVal = OpInfo.CallOperandVal;
5235 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5236 isa<ConstantVector>(OpVal)) {
5237 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5238 TLI.getPointerTy());
5240 // Otherwise, create a stack slot and emit a store to it before the
5242 const Type *Ty = OpVal->getType();
5243 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5244 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5245 MachineFunction &MF = DAG.getMachineFunction();
5246 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5247 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5248 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5249 OpInfo.CallOperand, StackSlot, NULL, 0,
5251 OpInfo.CallOperand = StackSlot;
5254 // There is no longer a Value* corresponding to this operand.
5255 OpInfo.CallOperandVal = 0;
5257 // It is now an indirect operand.
5258 OpInfo.isIndirect = true;
5261 // If this constraint is for a specific register, allocate it before
5263 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5264 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5267 ConstraintInfos.clear();
5269 // Second pass - Loop over all of the operands, assigning virtual or physregs
5270 // to register class operands.
5271 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5272 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5274 // C_Register operands have already been allocated, Other/Memory don't need
5276 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5277 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5280 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5281 std::vector<SDValue> AsmNodeOperands;
5282 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5283 AsmNodeOperands.push_back(
5284 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5285 TLI.getPointerTy()));
5287 // If we have a !srcloc metadata node associated with it, we want to attach
5288 // this to the ultimately generated inline asm machineinstr. To do this, we
5289 // pass in the third operand as this (potentially null) inline asm MDNode.
5290 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5291 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5293 // Loop over all of the inputs, copying the operand values into the
5294 // appropriate registers and processing the output regs.
5295 RegsForValue RetValRegs;
5297 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5298 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5300 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5301 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5303 switch (OpInfo.Type) {
5304 case InlineAsm::isOutput: {
5305 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5306 OpInfo.ConstraintType != TargetLowering::C_Register) {
5307 // Memory output, or 'other' output (e.g. 'X' constraint).
5308 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5310 // Add information to the INLINEASM node to know about this output.
5311 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5312 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5313 TLI.getPointerTy()));
5314 AsmNodeOperands.push_back(OpInfo.CallOperand);
5318 // Otherwise, this is a register or register class output.
5320 // Copy the output from the appropriate register. Find a register that
5322 if (OpInfo.AssignedRegs.Regs.empty())
5323 report_fatal_error("Couldn't allocate output reg for constraint '" +
5324 Twine(OpInfo.ConstraintCode) + "'!");
5326 // If this is an indirect operand, store through the pointer after the
5328 if (OpInfo.isIndirect) {
5329 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5330 OpInfo.CallOperandVal));
5332 // This is the result value of the call.
5333 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5334 // Concatenate this output onto the outputs list.
5335 RetValRegs.append(OpInfo.AssignedRegs);
5338 // Add information to the INLINEASM node to know that this register is
5340 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5341 InlineAsm::Kind_RegDefEarlyClobber :
5342 InlineAsm::Kind_RegDef,
5349 case InlineAsm::isInput: {
5350 SDValue InOperandVal = OpInfo.CallOperand;
5352 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5353 // If this is required to match an output register we have already set,
5354 // just use its register.
5355 unsigned OperandNo = OpInfo.getMatchedOperand();
5357 // Scan until we find the definition we already emitted of this operand.
5358 // When we find it, create a RegsForValue operand.
5359 unsigned CurOp = InlineAsm::Op_FirstOperand;
5360 for (; OperandNo; --OperandNo) {
5361 // Advance to the next operand.
5363 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5364 assert((InlineAsm::isRegDefKind(OpFlag) ||
5365 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5366 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5367 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5371 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5372 if (InlineAsm::isRegDefKind(OpFlag) ||
5373 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5374 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5375 if (OpInfo.isIndirect) {
5376 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5377 LLVMContext &Ctx = *DAG.getContext();
5378 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5379 " don't know how to handle tied "
5380 "indirect register inputs");
5383 RegsForValue MatchedRegs;
5384 MatchedRegs.TLI = &TLI;
5385 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5386 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5387 MatchedRegs.RegVTs.push_back(RegVT);
5388 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5389 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5391 MatchedRegs.Regs.push_back
5392 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5394 // Use the produced MatchedRegs object to
5395 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5397 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5398 true, OpInfo.getMatchedOperand(),
5399 DAG, AsmNodeOperands);
5403 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5404 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5405 "Unexpected number of operands");
5406 // Add information to the INLINEASM node to know about this input.
5407 // See InlineAsm.h isUseOperandTiedToDef.
5408 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5409 OpInfo.getMatchedOperand());
5410 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5411 TLI.getPointerTy()));
5412 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5416 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5417 assert(!OpInfo.isIndirect &&
5418 "Don't know how to handle indirect other inputs yet!");
5420 std::vector<SDValue> Ops;
5421 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5422 hasMemory, Ops, DAG);
5424 report_fatal_error("Invalid operand for inline asm constraint '" +
5425 Twine(OpInfo.ConstraintCode) + "'!");
5427 // Add information to the INLINEASM node to know about this input.
5428 unsigned ResOpType =
5429 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5430 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5431 TLI.getPointerTy()));
5432 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5436 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5437 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5438 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5439 "Memory operands expect pointer values");
5441 // Add information to the INLINEASM node to know about this input.
5442 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5443 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5444 TLI.getPointerTy()));
5445 AsmNodeOperands.push_back(InOperandVal);
5449 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5450 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5451 "Unknown constraint type!");
5452 assert(!OpInfo.isIndirect &&
5453 "Don't know how to handle indirect register inputs yet!");
5455 // Copy the input into the appropriate registers.
5456 if (OpInfo.AssignedRegs.Regs.empty() ||
5457 !OpInfo.AssignedRegs.areValueTypesLegal())
5458 report_fatal_error("Couldn't allocate input reg for constraint '" +
5459 Twine(OpInfo.ConstraintCode) + "'!");
5461 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5464 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
5465 DAG, AsmNodeOperands);
5468 case InlineAsm::isClobber: {
5469 // Add the clobbered value to the operand list, so that the register
5470 // allocator is aware that the physreg got clobbered.
5471 if (!OpInfo.AssignedRegs.Regs.empty())
5472 OpInfo.AssignedRegs.AddInlineAsmOperands(
5473 InlineAsm::Kind_RegDefEarlyClobber,
5481 // Finish up input operands. Set the input chain and add the flag last.
5482 AsmNodeOperands[0] = Chain;
5483 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5485 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5486 DAG.getVTList(MVT::Other, MVT::Flag),
5487 &AsmNodeOperands[0], AsmNodeOperands.size());
5488 Flag = Chain.getValue(1);
5490 // If this asm returns a register value, copy the result from that register
5491 // and set it as the value of the call.
5492 if (!RetValRegs.Regs.empty()) {
5493 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5496 // FIXME: Why don't we do this for inline asms with MRVs?
5497 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5498 EVT ResultType = TLI.getValueType(CS.getType());
5500 // If any of the results of the inline asm is a vector, it may have the
5501 // wrong width/num elts. This can happen for register classes that can
5502 // contain multiple different value types. The preg or vreg allocated may
5503 // not have the same VT as was expected. Convert it to the right type
5504 // with bit_convert.
5505 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5506 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5509 } else if (ResultType != Val.getValueType() &&
5510 ResultType.isInteger() && Val.getValueType().isInteger()) {
5511 // If a result value was tied to an input value, the computed result may
5512 // have a wider width than the expected result. Extract the relevant
5514 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5517 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5520 setValue(CS.getInstruction(), Val);
5521 // Don't need to use this as a chain in this case.
5522 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5526 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
5528 // Process indirect outputs, first output all of the flagged copies out of
5530 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5531 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5532 const Value *Ptr = IndirectStoresToEmit[i].second;
5533 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5535 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5538 // Emit the non-flagged stores from the physregs.
5539 SmallVector<SDValue, 8> OutChains;
5540 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5541 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5542 StoresToEmit[i].first,
5543 getValue(StoresToEmit[i].second),
5544 StoresToEmit[i].second, 0,
5546 OutChains.push_back(Val);
5549 if (!OutChains.empty())
5550 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5551 &OutChains[0], OutChains.size());
5556 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
5557 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5558 MVT::Other, getRoot(),
5559 getValue(I.getOperand(1)),
5560 DAG.getSrcValue(I.getOperand(1))));
5563 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
5564 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5565 getRoot(), getValue(I.getOperand(0)),
5566 DAG.getSrcValue(I.getOperand(0)));
5568 DAG.setRoot(V.getValue(1));
5571 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
5572 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5573 MVT::Other, getRoot(),
5574 getValue(I.getOperand(1)),
5575 DAG.getSrcValue(I.getOperand(1))));
5578 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
5579 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5580 MVT::Other, getRoot(),
5581 getValue(I.getOperand(1)),
5582 getValue(I.getOperand(2)),
5583 DAG.getSrcValue(I.getOperand(1)),
5584 DAG.getSrcValue(I.getOperand(2))));
5587 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5588 /// implementation, which just calls LowerCall.
5589 /// FIXME: When all targets are
5590 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5591 std::pair<SDValue, SDValue>
5592 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5593 bool RetSExt, bool RetZExt, bool isVarArg,
5594 bool isInreg, unsigned NumFixedArgs,
5595 CallingConv::ID CallConv, bool isTailCall,
5596 bool isReturnValueUsed,
5598 ArgListTy &Args, SelectionDAG &DAG,
5599 DebugLoc dl) const {
5600 // Handle all of the outgoing arguments.
5601 SmallVector<ISD::OutputArg, 32> Outs;
5602 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5603 SmallVector<EVT, 4> ValueVTs;
5604 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5605 for (unsigned Value = 0, NumValues = ValueVTs.size();
5606 Value != NumValues; ++Value) {
5607 EVT VT = ValueVTs[Value];
5608 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5609 SDValue Op = SDValue(Args[i].Node.getNode(),
5610 Args[i].Node.getResNo() + Value);
5611 ISD::ArgFlagsTy Flags;
5612 unsigned OriginalAlignment =
5613 getTargetData()->getABITypeAlignment(ArgTy);
5619 if (Args[i].isInReg)
5623 if (Args[i].isByVal) {
5625 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5626 const Type *ElementTy = Ty->getElementType();
5627 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5628 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5629 // For ByVal, alignment should come from FE. BE will guess if this
5630 // info is not there but there are cases it cannot get right.
5631 if (Args[i].Alignment)
5632 FrameAlign = Args[i].Alignment;
5633 Flags.setByValAlign(FrameAlign);
5634 Flags.setByValSize(FrameSize);
5638 Flags.setOrigAlign(OriginalAlignment);
5640 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5641 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5642 SmallVector<SDValue, 4> Parts(NumParts);
5643 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5646 ExtendKind = ISD::SIGN_EXTEND;
5647 else if (Args[i].isZExt)
5648 ExtendKind = ISD::ZERO_EXTEND;
5650 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
5651 PartVT, ExtendKind);
5653 for (unsigned j = 0; j != NumParts; ++j) {
5654 // if it isn't first piece, alignment must be 1
5655 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5656 if (NumParts > 1 && j == 0)
5657 MyFlags.Flags.setSplit();
5659 MyFlags.Flags.setOrigAlign(1);
5661 Outs.push_back(MyFlags);
5666 // Handle the incoming return values from the call.
5667 SmallVector<ISD::InputArg, 32> Ins;
5668 SmallVector<EVT, 4> RetTys;
5669 ComputeValueVTs(*this, RetTy, RetTys);
5670 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5672 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5673 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5674 for (unsigned i = 0; i != NumRegs; ++i) {
5675 ISD::InputArg MyFlags;
5676 MyFlags.VT = RegisterVT;
5677 MyFlags.Used = isReturnValueUsed;
5679 MyFlags.Flags.setSExt();
5681 MyFlags.Flags.setZExt();
5683 MyFlags.Flags.setInReg();
5684 Ins.push_back(MyFlags);
5688 SmallVector<SDValue, 4> InVals;
5689 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5690 Outs, Ins, dl, DAG, InVals);
5692 // Verify that the target's LowerCall behaved as expected.
5693 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5694 "LowerCall didn't return a valid chain!");
5695 assert((!isTailCall || InVals.empty()) &&
5696 "LowerCall emitted a return value for a tail call!");
5697 assert((isTailCall || InVals.size() == Ins.size()) &&
5698 "LowerCall didn't emit the correct number of values!");
5700 // For a tail call, the return value is merely live-out and there aren't
5701 // any nodes in the DAG representing it. Return a special value to
5702 // indicate that a tail call has been emitted and no more Instructions
5703 // should be processed in the current block.
5706 return std::make_pair(SDValue(), SDValue());
5709 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5710 assert(InVals[i].getNode() &&
5711 "LowerCall emitted a null value!");
5712 assert(Ins[i].VT == InVals[i].getValueType() &&
5713 "LowerCall emitted a value with the wrong type!");
5716 // Collect the legal value parts into potentially illegal values
5717 // that correspond to the original function's return values.
5718 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5720 AssertOp = ISD::AssertSext;
5722 AssertOp = ISD::AssertZext;
5723 SmallVector<SDValue, 4> ReturnValues;
5724 unsigned CurReg = 0;
5725 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5727 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5728 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5730 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
5731 NumRegs, RegisterVT, VT,
5736 // For a function returning void, there is no return value. We can't create
5737 // such a node, so we just return a null return value in that case. In
5738 // that case, nothing will actualy look at the value.
5739 if (ReturnValues.empty())
5740 return std::make_pair(SDValue(), Chain);
5742 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5743 DAG.getVTList(&RetTys[0], RetTys.size()),
5744 &ReturnValues[0], ReturnValues.size());
5745 return std::make_pair(Res, Chain);
5748 void TargetLowering::LowerOperationWrapper(SDNode *N,
5749 SmallVectorImpl<SDValue> &Results,
5750 SelectionDAG &DAG) const {
5751 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5753 Results.push_back(Res);
5756 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5757 llvm_unreachable("LowerOperation not implemented for this target!");
5762 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
5763 SDValue Op = getValue(V);
5764 assert((Op.getOpcode() != ISD::CopyFromReg ||
5765 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5766 "Copy from a reg to the same reg!");
5767 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5769 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5770 SDValue Chain = DAG.getEntryNode();
5771 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5772 PendingExports.push_back(Chain);
5775 #include "llvm/CodeGen/SelectionDAGISel.h"
5777 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
5778 // If this is the entry block, emit arguments.
5779 const Function &F = *LLVMBB->getParent();
5780 SelectionDAG &DAG = SDB->DAG;
5781 SDValue OldRoot = DAG.getRoot();
5782 DebugLoc dl = SDB->getCurDebugLoc();
5783 const TargetData *TD = TLI.getTargetData();
5784 SmallVector<ISD::InputArg, 16> Ins;
5786 // Check whether the function can return without sret-demotion.
5787 SmallVector<EVT, 4> OutVTs;
5788 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5789 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5790 OutVTs, OutsFlags, TLI);
5791 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5793 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5794 OutVTs, OutsFlags, DAG);
5795 if (!FLI.CanLowerReturn) {
5796 // Put in an sret pointer parameter before all the other parameters.
5797 SmallVector<EVT, 1> ValueVTs;
5798 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5800 // NOTE: Assuming that a pointer will never break down to more than one VT
5802 ISD::ArgFlagsTy Flags;
5804 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
5805 ISD::InputArg RetArg(Flags, RegisterVT, true);
5806 Ins.push_back(RetArg);
5809 // Set up the incoming argument description vector.
5811 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
5812 I != E; ++I, ++Idx) {
5813 SmallVector<EVT, 4> ValueVTs;
5814 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5815 bool isArgValueUsed = !I->use_empty();
5816 for (unsigned Value = 0, NumValues = ValueVTs.size();
5817 Value != NumValues; ++Value) {
5818 EVT VT = ValueVTs[Value];
5819 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5820 ISD::ArgFlagsTy Flags;
5821 unsigned OriginalAlignment =
5822 TD->getABITypeAlignment(ArgTy);
5824 if (F.paramHasAttr(Idx, Attribute::ZExt))
5826 if (F.paramHasAttr(Idx, Attribute::SExt))
5828 if (F.paramHasAttr(Idx, Attribute::InReg))
5830 if (F.paramHasAttr(Idx, Attribute::StructRet))
5832 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5834 const PointerType *Ty = cast<PointerType>(I->getType());
5835 const Type *ElementTy = Ty->getElementType();
5836 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5837 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5838 // For ByVal, alignment should be passed from FE. BE will guess if
5839 // this info is not there but there are cases it cannot get right.
5840 if (F.getParamAlignment(Idx))
5841 FrameAlign = F.getParamAlignment(Idx);
5842 Flags.setByValAlign(FrameAlign);
5843 Flags.setByValSize(FrameSize);
5845 if (F.paramHasAttr(Idx, Attribute::Nest))
5847 Flags.setOrigAlign(OriginalAlignment);
5849 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5850 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5851 for (unsigned i = 0; i != NumRegs; ++i) {
5852 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5853 if (NumRegs > 1 && i == 0)
5854 MyFlags.Flags.setSplit();
5855 // if it isn't first piece, alignment must be 1
5857 MyFlags.Flags.setOrigAlign(1);
5858 Ins.push_back(MyFlags);
5863 // Call the target to set up the argument values.
5864 SmallVector<SDValue, 8> InVals;
5865 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5869 // Verify that the target's LowerFormalArguments behaved as expected.
5870 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5871 "LowerFormalArguments didn't return a valid chain!");
5872 assert(InVals.size() == Ins.size() &&
5873 "LowerFormalArguments didn't emit the correct number of values!");
5875 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5876 assert(InVals[i].getNode() &&
5877 "LowerFormalArguments emitted a null value!");
5878 assert(Ins[i].VT == InVals[i].getValueType() &&
5879 "LowerFormalArguments emitted a value with the wrong type!");
5883 // Update the DAG with the new chain value resulting from argument lowering.
5884 DAG.setRoot(NewRoot);
5886 // Set up the argument values.
5889 if (!FLI.CanLowerReturn) {
5890 // Create a virtual register for the sret pointer, and put in a copy
5891 // from the sret argument into it.
5892 SmallVector<EVT, 1> ValueVTs;
5893 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5894 EVT VT = ValueVTs[0];
5895 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5896 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5897 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
5898 RegVT, VT, AssertOp);
5900 MachineFunction& MF = SDB->DAG.getMachineFunction();
5901 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5902 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5903 FLI.DemoteRegister = SRetReg;
5904 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
5906 DAG.setRoot(NewRoot);
5908 // i indexes lowered arguments. Bump it past the hidden sret argument.
5909 // Idx indexes LLVM arguments. Don't touch it.
5913 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5915 SmallVector<SDValue, 4> ArgValues;
5916 SmallVector<EVT, 4> ValueVTs;
5917 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5918 unsigned NumValues = ValueVTs.size();
5919 for (unsigned Value = 0; Value != NumValues; ++Value) {
5920 EVT VT = ValueVTs[Value];
5921 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5922 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5924 if (!I->use_empty()) {
5925 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5926 if (F.paramHasAttr(Idx, Attribute::SExt))
5927 AssertOp = ISD::AssertSext;
5928 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5929 AssertOp = ISD::AssertZext;
5931 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
5932 NumParts, PartVT, VT,
5939 if (!I->use_empty()) {
5941 if (!ArgValues.empty())
5942 Res = DAG.getMergeValues(&ArgValues[0], NumValues,
5943 SDB->getCurDebugLoc());
5944 SDB->setValue(I, Res);
5946 // If this argument is live outside of the entry block, insert a copy from
5947 // whereever we got it to the vreg that other BB's will reference it as.
5948 SDB->CopyToExportRegsIfNeeded(I);
5952 assert(i == InVals.size() && "Argument register count mismatch!");
5954 // Finally, if the target has anything special to do, allow it to do so.
5955 // FIXME: this should insert code into the DAG!
5956 EmitFunctionEntryCode();
5959 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5960 /// ensure constants are generated when needed. Remember the virtual registers
5961 /// that need to be added to the Machine PHI nodes as input. We cannot just
5962 /// directly add them, because expansion might result in multiple MBB's for one
5963 /// BB. As such, the start of the BB might correspond to a different MBB than
5967 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
5968 const TerminatorInst *TI = LLVMBB->getTerminator();
5970 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5972 // Check successor nodes' PHI nodes that expect a constant to be available
5974 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5975 const BasicBlock *SuccBB = TI->getSuccessor(succ);
5976 if (!isa<PHINode>(SuccBB->begin())) continue;
5977 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
5979 // If this terminator has multiple identical successors (common for
5980 // switches), only handle each succ once.
5981 if (!SuccsHandled.insert(SuccMBB)) continue;
5983 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5985 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5986 // nodes and Machine PHI nodes, but the incoming operands have not been
5988 for (BasicBlock::const_iterator I = SuccBB->begin();
5989 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
5990 // Ignore dead phi's.
5991 if (PN->use_empty()) continue;
5994 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5996 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
5997 unsigned &RegOut = ConstantsOut[C];
5999 RegOut = FuncInfo.CreateRegForValue(C);
6000 CopyValueToVirtualRegister(C, RegOut);
6004 Reg = FuncInfo.ValueMap[PHIOp];
6006 assert(isa<AllocaInst>(PHIOp) &&
6007 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6008 "Didn't codegen value into a register!??");
6009 Reg = FuncInfo.CreateRegForValue(PHIOp);
6010 CopyValueToVirtualRegister(PHIOp, Reg);
6014 // Remember that this register needs to added to the machine PHI node as
6015 // the input for this MBB.
6016 SmallVector<EVT, 4> ValueVTs;
6017 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6018 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6019 EVT VT = ValueVTs[vti];
6020 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6021 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6022 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6023 Reg += NumRegisters;
6027 ConstantsOut.clear();