1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuilder.h"
16 #include "FunctionLoweringInfo.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/ConstantFolding.h"
21 #include "llvm/Constants.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/IntrinsicInst.h"
30 #include "llvm/Module.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/GCStrategy.h"
33 #include "llvm/CodeGen/GCMetadata.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/PseudoSourceValue.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/DwarfWriter.h"
43 #include "llvm/Analysis/DebugInfo.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetFrameInfo.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetIntrinsicInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
60 /// LimitFloatPrecision - Generate low-precision inline sequences for
61 /// some float libcalls (6, 8 or 12 bits).
62 static unsigned LimitFloatPrecision;
64 static cl::opt<unsigned, true>
65 LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
72 /// RegsForValue - This struct represents the registers (physical or virtual)
73 /// that a particular set of values is assigned, and the type information
74 /// about the value. The most common situation is to represent one value at a
75 /// time, but struct or array values are handled element-wise as multiple
76 /// values. The splitting of aggregates is performed recursively, so that we
77 /// never have aggregate-typed registers. The values at this point do not
78 /// necessarily have legal types, so each value may require one or more
79 /// registers of some legal type.
82 /// TLI - The TargetLowering object.
84 const TargetLowering *TLI;
86 /// ValueVTs - The value types of the values, which may not be legal, and
87 /// may need be promoted or synthesized from one or more registers.
89 SmallVector<EVT, 4> ValueVTs;
91 /// RegVTs - The value types of the registers. This is the same size as
92 /// ValueVTs and it records, for each value, what the type of the assigned
93 /// register or registers are. (Individual values are never synthesized
94 /// from more than one type of register.)
96 /// With virtual registers, the contents of RegVTs is redundant with TLI's
97 /// getRegisterType member function, however when with physical registers
98 /// it is necessary to have a separate record of the types.
100 SmallVector<EVT, 4> RegVTs;
102 /// Regs - This list holds the registers assigned to the values.
103 /// Each legal or promoted value requires one register, and each
104 /// expanded value requires multiple registers.
106 SmallVector<unsigned, 4> Regs;
108 RegsForValue() : TLI(0) {}
110 RegsForValue(const TargetLowering &tli,
111 const SmallVector<unsigned, 4> ®s,
112 EVT regvt, EVT valuevt)
113 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
114 RegsForValue(const TargetLowering &tli,
115 const SmallVector<unsigned, 4> ®s,
116 const SmallVector<EVT, 4> ®vts,
117 const SmallVector<EVT, 4> &valuevts)
118 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
119 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
120 unsigned Reg, const Type *Ty) : TLI(&tli) {
121 ComputeValueVTs(tli, Ty, ValueVTs);
123 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
124 EVT ValueVT = ValueVTs[Value];
125 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
126 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
127 for (unsigned i = 0; i != NumRegs; ++i)
128 Regs.push_back(Reg + i);
129 RegVTs.push_back(RegisterVT);
134 /// areValueTypesLegal - Return true if types of all the values are legal.
135 bool areValueTypesLegal() {
136 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
137 EVT RegisterVT = RegVTs[Value];
138 if (!TLI->isTypeLegal(RegisterVT))
145 /// append - Add the specified values to this one.
146 void append(const RegsForValue &RHS) {
148 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
149 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
150 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
154 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
155 /// this value and returns the result as a ValueVTs value. This uses
156 /// Chain/Flag as the input and updates them for the output Chain/Flag.
157 /// If the Flag pointer is NULL, no flag is used.
158 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
159 SDValue &Chain, SDValue *Flag) const;
161 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
162 /// specified value into the registers specified by this object. This uses
163 /// Chain/Flag as the input and updates them for the output Chain/Flag.
164 /// If the Flag pointer is NULL, no flag is used.
165 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
166 unsigned Order, SDValue &Chain, SDValue *Flag) const;
168 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
169 /// operand list. This adds the code marker, matching input operand index
170 /// (if applicable), and includes the number of values added into it.
171 void AddInlineAsmOperands(unsigned Code,
172 bool HasMatching, unsigned MatchingIdx,
173 SelectionDAG &DAG, unsigned Order,
174 std::vector<SDValue> &Ops) const;
178 /// getCopyFromParts - Create a value that contains the specified legal parts
179 /// combined into the value they represent. If the parts combine to a type
180 /// larger then ValueVT then AssertOp can be used to specify whether the extra
181 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
182 /// (ISD::AssertSext).
183 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
184 const SDValue *Parts,
185 unsigned NumParts, EVT PartVT, EVT ValueVT,
186 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
187 assert(NumParts > 0 && "No parts to assemble!");
188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
189 SDValue Val = Parts[0];
192 // Assemble the value from multiple parts.
193 if (!ValueVT.isVector() && ValueVT.isInteger()) {
194 unsigned PartBits = PartVT.getSizeInBits();
195 unsigned ValueBits = ValueVT.getSizeInBits();
197 // Assemble the power of 2 part.
198 unsigned RoundParts = NumParts & (NumParts - 1) ?
199 1 << Log2_32(NumParts) : NumParts;
200 unsigned RoundBits = PartBits * RoundParts;
201 EVT RoundVT = RoundBits == ValueBits ?
202 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
205 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
207 if (RoundParts > 2) {
208 Lo = getCopyFromParts(DAG, dl, Order, Parts, RoundParts / 2,
210 Hi = getCopyFromParts(DAG, dl, Order, Parts + RoundParts / 2,
211 RoundParts / 2, PartVT, HalfVT);
213 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
214 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
217 if (TLI.isBigEndian())
220 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
222 if (RoundParts < NumParts) {
223 // Assemble the trailing non-power-of-2 part.
224 unsigned OddParts = NumParts - RoundParts;
225 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
226 Hi = getCopyFromParts(DAG, dl, Order,
227 Parts + RoundParts, OddParts, PartVT, OddVT);
229 // Combine the round and odd parts.
231 if (TLI.isBigEndian())
233 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
234 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
235 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
236 DAG.getConstant(Lo.getValueType().getSizeInBits(),
237 TLI.getPointerTy()));
238 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
239 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
241 } else if (ValueVT.isVector()) {
242 // Handle a multi-element vector.
243 EVT IntermediateVT, RegisterVT;
244 unsigned NumIntermediates;
246 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
247 NumIntermediates, RegisterVT);
248 assert(NumRegs == NumParts
249 && "Part count doesn't match vector breakdown!");
250 NumParts = NumRegs; // Silence a compiler warning.
251 assert(RegisterVT == PartVT
252 && "Part type doesn't match vector breakdown!");
253 assert(RegisterVT == Parts[0].getValueType() &&
254 "Part type doesn't match part!");
256 // Assemble the parts into intermediate operands.
257 SmallVector<SDValue, 8> Ops(NumIntermediates);
258 if (NumIntermediates == NumParts) {
259 // If the register was not expanded, truncate or copy the value,
261 for (unsigned i = 0; i != NumParts; ++i)
262 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i], 1,
263 PartVT, IntermediateVT);
264 } else if (NumParts > 0) {
265 // If the intermediate type was expanded, build the intermediate
266 // operands from the parts.
267 assert(NumParts % NumIntermediates == 0 &&
268 "Must expand into a divisible number of parts!");
269 unsigned Factor = NumParts / NumIntermediates;
270 for (unsigned i = 0; i != NumIntermediates; ++i)
271 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i * Factor], Factor,
272 PartVT, IntermediateVT);
275 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
276 // intermediate operands.
277 Val = DAG.getNode(IntermediateVT.isVector() ?
278 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
279 ValueVT, &Ops[0], NumIntermediates);
280 } else if (PartVT.isFloatingPoint()) {
281 // FP split into multiple FP parts (for ppcf128)
282 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
285 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
286 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
287 if (TLI.isBigEndian())
289 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
291 // FP split into integer parts (soft fp)
292 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
293 !PartVT.isVector() && "Unexpected split");
294 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
295 Val = getCopyFromParts(DAG, dl, Order, Parts, NumParts, PartVT, IntVT);
299 // There is now one part, held in Val. Correct it to match ValueVT.
300 PartVT = Val.getValueType();
302 if (PartVT == ValueVT)
305 if (PartVT.isVector()) {
306 assert(ValueVT.isVector() && "Unknown vector conversion!");
307 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
310 if (ValueVT.isVector()) {
311 assert(ValueVT.getVectorElementType() == PartVT &&
312 ValueVT.getVectorNumElements() == 1 &&
313 "Only trivial scalar-to-vector conversions should get here!");
314 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
317 if (PartVT.isInteger() &&
318 ValueVT.isInteger()) {
319 if (ValueVT.bitsLT(PartVT)) {
320 // For a truncate, see if we have any information to
321 // indicate whether the truncated bits will always be
322 // zero or sign-extension.
323 if (AssertOp != ISD::DELETED_NODE)
324 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
325 DAG.getValueType(ValueVT));
326 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
328 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
332 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
333 if (ValueVT.bitsLT(Val.getValueType())) {
334 // FP_ROUND's are always exact here.
335 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
336 DAG.getIntPtrConstant(1));
339 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
342 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
343 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
345 llvm_unreachable("Unknown mismatch!");
349 /// getCopyToParts - Create a series of nodes that contain the specified value
350 /// split into legal parts. If the parts contain more bits than Val, then, for
351 /// integers, ExtendKind can be used to specify how to generate the extra bits.
352 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
353 SDValue Val, SDValue *Parts, unsigned NumParts,
355 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
357 EVT PtrVT = TLI.getPointerTy();
358 EVT ValueVT = Val.getValueType();
359 unsigned PartBits = PartVT.getSizeInBits();
360 unsigned OrigNumParts = NumParts;
361 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
366 if (!ValueVT.isVector()) {
367 if (PartVT == ValueVT) {
368 assert(NumParts == 1 && "No-op copy with multiple parts!");
373 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
374 // If the parts cover more bits than the value has, promote the value.
375 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
376 assert(NumParts == 1 && "Do not know what to promote to!");
377 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
378 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
379 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
380 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
382 llvm_unreachable("Unknown mismatch!");
384 } else if (PartBits == ValueVT.getSizeInBits()) {
385 // Different types of the same size.
386 assert(NumParts == 1 && PartVT != ValueVT);
387 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
388 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
389 // If the parts cover less bits than value has, truncate the value.
390 if (PartVT.isInteger() && ValueVT.isInteger()) {
391 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
392 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
394 llvm_unreachable("Unknown mismatch!");
398 // The value may have changed - recompute ValueVT.
399 ValueVT = Val.getValueType();
400 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
401 "Failed to tile the value with PartVT!");
404 assert(PartVT == ValueVT && "Type conversion failed!");
409 // Expand the value into multiple parts.
410 if (NumParts & (NumParts - 1)) {
411 // The number of parts is not a power of 2. Split off and copy the tail.
412 assert(PartVT.isInteger() && ValueVT.isInteger() &&
413 "Do not know what to expand to!");
414 unsigned RoundParts = 1 << Log2_32(NumParts);
415 unsigned RoundBits = RoundParts * PartBits;
416 unsigned OddParts = NumParts - RoundParts;
417 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
418 DAG.getConstant(RoundBits,
419 TLI.getPointerTy()));
420 getCopyToParts(DAG, dl, Order, OddVal, Parts + RoundParts,
423 if (TLI.isBigEndian())
424 // The odd parts were reversed by getCopyToParts - unreverse them.
425 std::reverse(Parts + RoundParts, Parts + NumParts);
427 NumParts = RoundParts;
428 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
429 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
432 // The number of parts is a power of 2. Repeatedly bisect the value using
434 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
435 EVT::getIntegerVT(*DAG.getContext(),
436 ValueVT.getSizeInBits()),
439 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
440 for (unsigned i = 0; i < NumParts; i += StepSize) {
441 unsigned ThisBits = StepSize * PartBits / 2;
442 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
443 SDValue &Part0 = Parts[i];
444 SDValue &Part1 = Parts[i+StepSize/2];
446 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
448 DAG.getConstant(1, PtrVT));
449 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
451 DAG.getConstant(0, PtrVT));
453 if (ThisBits == PartBits && ThisVT != PartVT) {
454 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
456 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
462 if (TLI.isBigEndian())
463 std::reverse(Parts, Parts + OrigNumParts);
470 if (PartVT != ValueVT) {
471 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
472 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
474 assert(ValueVT.getVectorElementType() == PartVT &&
475 ValueVT.getVectorNumElements() == 1 &&
476 "Only trivial vector-to-scalar conversions should get here!");
477 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
479 DAG.getConstant(0, PtrVT));
487 // Handle a multi-element vector.
488 EVT IntermediateVT, RegisterVT;
489 unsigned NumIntermediates;
490 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
491 IntermediateVT, NumIntermediates, RegisterVT);
492 unsigned NumElements = ValueVT.getVectorNumElements();
494 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
495 NumParts = NumRegs; // Silence a compiler warning.
496 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
498 // Split the vector into intermediate operands.
499 SmallVector<SDValue, 8> Ops(NumIntermediates);
500 for (unsigned i = 0; i != NumIntermediates; ++i) {
501 if (IntermediateVT.isVector())
502 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
504 DAG.getConstant(i * (NumElements / NumIntermediates),
507 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
509 DAG.getConstant(i, PtrVT));
512 // Split the intermediate operands into legal parts.
513 if (NumParts == NumIntermediates) {
514 // If the register was not expanded, promote or copy the value,
516 for (unsigned i = 0; i != NumParts; ++i)
517 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i], 1, PartVT);
518 } else if (NumParts > 0) {
519 // If the intermediate type was expanded, split each the value into
521 assert(NumParts % NumIntermediates == 0 &&
522 "Must expand into a divisible number of parts!");
523 unsigned Factor = NumParts / NumIntermediates;
524 for (unsigned i = 0; i != NumIntermediates; ++i)
525 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i*Factor], Factor, PartVT);
530 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
533 TD = DAG.getTarget().getTargetData();
536 /// clear - Clear out the curret SelectionDAG and the associated
537 /// state and prepare this SelectionDAGBuilder object to be used
538 /// for a new block. This doesn't clear out information about
539 /// additional blocks that are needed to complete switch lowering
540 /// or PHI node updating; that information is cleared out as it is
542 void SelectionDAGBuilder::clear() {
544 PendingLoads.clear();
545 PendingExports.clear();
548 CurDebugLoc = DebugLoc::getUnknownLoc();
552 /// getRoot - Return the current virtual root of the Selection DAG,
553 /// flushing any PendingLoad items. This must be done before emitting
554 /// a store or any other node that may need to be ordered after any
555 /// prior load instructions.
557 SDValue SelectionDAGBuilder::getRoot() {
558 if (PendingLoads.empty())
559 return DAG.getRoot();
561 if (PendingLoads.size() == 1) {
562 SDValue Root = PendingLoads[0];
564 PendingLoads.clear();
568 // Otherwise, we have to make a token factor node.
569 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
570 &PendingLoads[0], PendingLoads.size());
571 PendingLoads.clear();
576 /// getControlRoot - Similar to getRoot, but instead of flushing all the
577 /// PendingLoad items, flush all the PendingExports items. It is necessary
578 /// to do this before emitting a terminator instruction.
580 SDValue SelectionDAGBuilder::getControlRoot() {
581 SDValue Root = DAG.getRoot();
583 if (PendingExports.empty())
586 // Turn all of the CopyToReg chains into one factored node.
587 if (Root.getOpcode() != ISD::EntryToken) {
588 unsigned i = 0, e = PendingExports.size();
589 for (; i != e; ++i) {
590 assert(PendingExports[i].getNode()->getNumOperands() > 1);
591 if (PendingExports[i].getNode()->getOperand(0) == Root)
592 break; // Don't add the root if we already indirectly depend on it.
596 PendingExports.push_back(Root);
599 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
601 PendingExports.size());
602 PendingExports.clear();
607 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
608 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
609 DAG.AssignOrdering(Node, SDNodeOrder);
611 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
612 AssignOrderingToNode(Node->getOperand(I).getNode());
615 void SelectionDAGBuilder::visit(Instruction &I) {
616 visit(I.getOpcode(), I);
619 void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
620 // Note: this doesn't use InstVisitor, because it has to work with
621 // ConstantExpr's in addition to instructions.
623 default: llvm_unreachable("Unknown instruction type encountered!");
624 // Build the switch statement using the Instruction.def file.
625 #define HANDLE_INST(NUM, OPCODE, CLASS) \
626 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
627 #include "llvm/Instruction.def"
630 // Assign the ordering to the freshly created DAG nodes.
631 if (NodeMap.count(&I)) {
633 AssignOrderingToNode(getValue(&I).getNode());
637 SDValue SelectionDAGBuilder::getValue(const Value *V) {
638 SDValue &N = NodeMap[V];
639 if (N.getNode()) return N;
641 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
642 EVT VT = TLI.getValueType(V->getType(), true);
644 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
645 return N = DAG.getConstant(*CI, VT);
647 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
648 return N = DAG.getGlobalAddress(GV, VT);
650 if (isa<ConstantPointerNull>(C))
651 return N = DAG.getConstant(0, TLI.getPointerTy());
653 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
654 return N = DAG.getConstantFP(*CFP, VT);
656 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
657 return N = DAG.getUNDEF(VT);
659 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
660 visit(CE->getOpcode(), *CE);
661 SDValue N1 = NodeMap[V];
662 assert(N1.getNode() && "visit didn't populate the ValueMap!");
666 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
667 SmallVector<SDValue, 4> Constants;
668 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
670 SDNode *Val = getValue(*OI).getNode();
671 // If the operand is an empty aggregate, there are no values.
673 // Add each leaf value from the operand to the Constants list
674 // to form a flattened list of all the values.
675 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
676 Constants.push_back(SDValue(Val, i));
679 return DAG.getMergeValues(&Constants[0], Constants.size(),
683 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
684 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
685 "Unknown struct or array constant!");
687 SmallVector<EVT, 4> ValueVTs;
688 ComputeValueVTs(TLI, C->getType(), ValueVTs);
689 unsigned NumElts = ValueVTs.size();
691 return SDValue(); // empty struct
692 SmallVector<SDValue, 4> Constants(NumElts);
693 for (unsigned i = 0; i != NumElts; ++i) {
694 EVT EltVT = ValueVTs[i];
695 if (isa<UndefValue>(C))
696 Constants[i] = DAG.getUNDEF(EltVT);
697 else if (EltVT.isFloatingPoint())
698 Constants[i] = DAG.getConstantFP(0, EltVT);
700 Constants[i] = DAG.getConstant(0, EltVT);
703 return DAG.getMergeValues(&Constants[0], NumElts,
707 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
708 return DAG.getBlockAddress(BA, VT);
710 const VectorType *VecTy = cast<VectorType>(V->getType());
711 unsigned NumElements = VecTy->getNumElements();
713 // Now that we know the number and type of the elements, get that number of
714 // elements into the Ops array based on what kind of constant it is.
715 SmallVector<SDValue, 16> Ops;
716 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
717 for (unsigned i = 0; i != NumElements; ++i)
718 Ops.push_back(getValue(CP->getOperand(i)));
720 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
721 EVT EltVT = TLI.getValueType(VecTy->getElementType());
724 if (EltVT.isFloatingPoint())
725 Op = DAG.getConstantFP(0, EltVT);
727 Op = DAG.getConstant(0, EltVT);
728 Ops.assign(NumElements, Op);
731 // Create a BUILD_VECTOR node.
732 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
733 VT, &Ops[0], Ops.size());
736 // If this is a static alloca, generate it as the frameindex instead of
738 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
739 DenseMap<const AllocaInst*, int>::iterator SI =
740 FuncInfo.StaticAllocaMap.find(AI);
741 if (SI != FuncInfo.StaticAllocaMap.end())
742 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
745 unsigned InReg = FuncInfo.ValueMap[V];
746 assert(InReg && "Value not in map!");
748 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
749 SDValue Chain = DAG.getEntryNode();
750 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(),
751 SDNodeOrder, Chain, NULL);
754 /// Get the EVTs and ArgFlags collections that represent the legalized return
755 /// type of the given function. This does not require a DAG or a return value,
756 /// and is suitable for use before any DAGs for the function are constructed.
757 static void getReturnInfo(const Type* ReturnType,
758 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
759 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
761 SmallVectorImpl<uint64_t> *Offsets = 0) {
762 SmallVector<EVT, 4> ValueVTs;
763 ComputeValueVTs(TLI, ReturnType, ValueVTs);
764 unsigned NumValues = ValueVTs.size();
765 if (NumValues == 0) return;
768 for (unsigned j = 0, f = NumValues; j != f; ++j) {
769 EVT VT = ValueVTs[j];
770 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
772 if (attr & Attribute::SExt)
773 ExtendKind = ISD::SIGN_EXTEND;
774 else if (attr & Attribute::ZExt)
775 ExtendKind = ISD::ZERO_EXTEND;
777 // FIXME: C calling convention requires the return type to be promoted to
778 // at least 32-bit. But this is not necessary for non-C calling
779 // conventions. The frontend should mark functions whose return values
780 // require promoting with signext or zeroext attributes.
781 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
782 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
783 if (VT.bitsLT(MinVT))
787 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
788 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
789 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
790 PartVT.getTypeForEVT(ReturnType->getContext()));
792 // 'inreg' on function refers to return value
793 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
794 if (attr & Attribute::InReg)
797 // Propagate extension type if any
798 if (attr & Attribute::SExt)
800 else if (attr & Attribute::ZExt)
803 for (unsigned i = 0; i < NumParts; ++i) {
804 OutVTs.push_back(PartVT);
805 OutFlags.push_back(Flags);
808 Offsets->push_back(Offset);
815 void SelectionDAGBuilder::visitRet(ReturnInst &I) {
816 SDValue Chain = getControlRoot();
817 SmallVector<ISD::OutputArg, 8> Outs;
818 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
820 if (!FLI.CanLowerReturn) {
821 unsigned DemoteReg = FLI.DemoteRegister;
822 const Function *F = I.getParent()->getParent();
824 // Emit a store of the return value through the virtual register.
825 // Leave Outs empty so that LowerReturn won't try to load return
826 // registers the usual way.
827 SmallVector<EVT, 1> PtrValueVTs;
828 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
831 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
832 SDValue RetOp = getValue(I.getOperand(0));
834 SmallVector<EVT, 4> ValueVTs;
835 SmallVector<uint64_t, 4> Offsets;
836 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
837 unsigned NumValues = ValueVTs.size();
839 SmallVector<SDValue, 4> Chains(NumValues);
840 EVT PtrVT = PtrValueVTs[0];
841 for (unsigned i = 0; i != NumValues; ++i) {
842 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
843 DAG.getConstant(Offsets[i], PtrVT));
845 DAG.getStore(Chain, getCurDebugLoc(),
846 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
847 Add, NULL, Offsets[i], false, 0);
850 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
851 MVT::Other, &Chains[0], NumValues);
853 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
854 SmallVector<EVT, 4> ValueVTs;
855 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
856 unsigned NumValues = ValueVTs.size();
857 if (NumValues == 0) continue;
859 SDValue RetOp = getValue(I.getOperand(i));
860 for (unsigned j = 0, f = NumValues; j != f; ++j) {
861 EVT VT = ValueVTs[j];
863 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
865 const Function *F = I.getParent()->getParent();
866 if (F->paramHasAttr(0, Attribute::SExt))
867 ExtendKind = ISD::SIGN_EXTEND;
868 else if (F->paramHasAttr(0, Attribute::ZExt))
869 ExtendKind = ISD::ZERO_EXTEND;
871 // FIXME: C calling convention requires the return type to be promoted
872 // to at least 32-bit. But this is not necessary for non-C calling
873 // conventions. The frontend should mark functions whose return values
874 // require promoting with signext or zeroext attributes.
875 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
876 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
877 if (VT.bitsLT(MinVT))
881 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
882 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
883 SmallVector<SDValue, 4> Parts(NumParts);
884 getCopyToParts(DAG, getCurDebugLoc(), SDNodeOrder,
885 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
886 &Parts[0], NumParts, PartVT, ExtendKind);
888 // 'inreg' on function refers to return value
889 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
890 if (F->paramHasAttr(0, Attribute::InReg))
893 // Propagate extension type if any
894 if (F->paramHasAttr(0, Attribute::SExt))
896 else if (F->paramHasAttr(0, Attribute::ZExt))
899 for (unsigned i = 0; i < NumParts; ++i)
900 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
905 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
906 CallingConv::ID CallConv =
907 DAG.getMachineFunction().getFunction()->getCallingConv();
908 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
909 Outs, getCurDebugLoc(), DAG);
911 // Verify that the target's LowerReturn behaved as expected.
912 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
913 "LowerReturn didn't return a valid chain!");
915 // Update the DAG with the new chain value resulting from return lowering.
919 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
920 /// created for it, emit nodes to copy the value into the virtual
922 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
923 if (!V->use_empty()) {
924 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
925 if (VMI != FuncInfo.ValueMap.end())
926 CopyValueToVirtualRegister(V, VMI->second);
930 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
931 /// the current basic block, add it to ValueMap now so that we'll get a
933 void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
934 // No need to export constants.
935 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
938 if (FuncInfo.isExportedInst(V)) return;
940 unsigned Reg = FuncInfo.InitializeRegForValue(V);
941 CopyValueToVirtualRegister(V, Reg);
944 bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
945 const BasicBlock *FromBB) {
946 // The operands of the setcc have to be in this block. We don't know
947 // how to export them from some other block.
948 if (Instruction *VI = dyn_cast<Instruction>(V)) {
949 // Can export from current BB.
950 if (VI->getParent() == FromBB)
953 // Is already exported, noop.
954 return FuncInfo.isExportedInst(V);
957 // If this is an argument, we can export it if the BB is the entry block or
958 // if it is already exported.
959 if (isa<Argument>(V)) {
960 if (FromBB == &FromBB->getParent()->getEntryBlock())
963 // Otherwise, can only export this if it is already exported.
964 return FuncInfo.isExportedInst(V);
967 // Otherwise, constants can always be exported.
971 static bool InBlock(const Value *V, const BasicBlock *BB) {
972 if (const Instruction *I = dyn_cast<Instruction>(V))
973 return I->getParent() == BB;
977 /// getFCmpCondCode - Return the ISD condition code corresponding to
978 /// the given LLVM IR floating-point condition code. This includes
979 /// consideration of global floating-point math flags.
981 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
982 ISD::CondCode FPC, FOC;
984 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
985 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
986 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
987 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
988 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
989 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
990 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
991 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
992 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
993 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
994 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
995 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
996 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
997 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
998 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
999 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1001 llvm_unreachable("Invalid FCmp predicate opcode!");
1002 FOC = FPC = ISD::SETFALSE;
1005 if (FiniteOnlyFPMath())
1011 /// getICmpCondCode - Return the ISD condition code corresponding to
1012 /// the given LLVM IR integer condition code.
1014 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1016 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1017 case ICmpInst::ICMP_NE: return ISD::SETNE;
1018 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1019 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1020 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1021 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1022 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1023 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1024 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1025 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1027 llvm_unreachable("Invalid ICmp predicate opcode!");
1032 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1033 /// This function emits a branch and is used at the leaves of an OR or an
1034 /// AND operator tree.
1037 SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1038 MachineBasicBlock *TBB,
1039 MachineBasicBlock *FBB,
1040 MachineBasicBlock *CurBB) {
1041 const BasicBlock *BB = CurBB->getBasicBlock();
1043 // If the leaf of the tree is a comparison, merge the condition into
1045 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1046 // The operands of the cmp have to be in this block. We don't know
1047 // how to export them from some other block. If this is the first block
1048 // of the sequence, no exporting is needed.
1049 if (CurBB == CurMBB ||
1050 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1051 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1052 ISD::CondCode Condition;
1053 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1054 Condition = getICmpCondCode(IC->getPredicate());
1055 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1056 Condition = getFCmpCondCode(FC->getPredicate());
1058 Condition = ISD::SETEQ; // silence warning.
1059 llvm_unreachable("Unknown compare instruction");
1062 CaseBlock CB(Condition, BOp->getOperand(0),
1063 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1064 SwitchCases.push_back(CB);
1069 // Create a CaseBlock record representing this branch.
1070 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1071 NULL, TBB, FBB, CurBB);
1072 SwitchCases.push_back(CB);
1075 /// FindMergedConditions - If Cond is an expression like
1076 void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1077 MachineBasicBlock *TBB,
1078 MachineBasicBlock *FBB,
1079 MachineBasicBlock *CurBB,
1081 // If this node is not part of the or/and tree, emit it as a branch.
1082 Instruction *BOp = dyn_cast<Instruction>(Cond);
1083 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1084 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1085 BOp->getParent() != CurBB->getBasicBlock() ||
1086 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1087 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1088 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1092 // Create TmpBB after CurBB.
1093 MachineFunction::iterator BBI = CurBB;
1094 MachineFunction &MF = DAG.getMachineFunction();
1095 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1096 CurBB->getParent()->insert(++BBI, TmpBB);
1098 if (Opc == Instruction::Or) {
1099 // Codegen X | Y as:
1107 // Emit the LHS condition.
1108 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1110 // Emit the RHS condition into TmpBB.
1111 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1113 assert(Opc == Instruction::And && "Unknown merge op!");
1114 // Codegen X & Y as:
1121 // This requires creation of TmpBB after CurBB.
1123 // Emit the LHS condition.
1124 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1126 // Emit the RHS condition into TmpBB.
1127 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1131 /// If the set of cases should be emitted as a series of branches, return true.
1132 /// If we should emit this as a bunch of and/or'd together conditions, return
1135 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1136 if (Cases.size() != 2) return true;
1138 // If this is two comparisons of the same values or'd or and'd together, they
1139 // will get folded into a single comparison, so don't emit two blocks.
1140 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1141 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1142 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1143 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1147 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1148 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1149 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1150 Cases[0].CC == Cases[1].CC &&
1151 isa<Constant>(Cases[0].CmpRHS) &&
1152 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1153 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1155 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1162 void SelectionDAGBuilder::visitBr(BranchInst &I) {
1163 // Update machine-CFG edges.
1164 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1166 // Figure out which block is immediately after the current one.
1167 MachineBasicBlock *NextBlock = 0;
1168 MachineFunction::iterator BBI = CurMBB;
1169 if (++BBI != FuncInfo.MF->end())
1172 if (I.isUnconditional()) {
1173 // Update machine-CFG edges.
1174 CurMBB->addSuccessor(Succ0MBB);
1176 // If this is not a fall-through branch, emit the branch.
1177 if (Succ0MBB != NextBlock)
1178 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1179 MVT::Other, getControlRoot(),
1180 DAG.getBasicBlock(Succ0MBB)));
1185 // If this condition is one of the special cases we handle, do special stuff
1187 Value *CondVal = I.getCondition();
1188 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1190 // If this is a series of conditions that are or'd or and'd together, emit
1191 // this as a sequence of branches instead of setcc's with and/or operations.
1192 // For example, instead of something like:
1205 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1206 if (BOp->hasOneUse() &&
1207 (BOp->getOpcode() == Instruction::And ||
1208 BOp->getOpcode() == Instruction::Or)) {
1209 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1210 // If the compares in later blocks need to use values not currently
1211 // exported from this block, export them now. This block should always
1212 // be the first entry.
1213 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1215 // Allow some cases to be rejected.
1216 if (ShouldEmitAsBranches(SwitchCases)) {
1217 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1218 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1219 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1222 // Emit the branch for this block.
1223 visitSwitchCase(SwitchCases[0]);
1224 SwitchCases.erase(SwitchCases.begin());
1228 // Okay, we decided not to do this, remove any inserted MBB's and clear
1230 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1231 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1233 SwitchCases.clear();
1237 // Create a CaseBlock record representing this branch.
1238 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1239 NULL, Succ0MBB, Succ1MBB, CurMBB);
1241 // Use visitSwitchCase to actually insert the fast branch sequence for this
1243 visitSwitchCase(CB);
1246 /// visitSwitchCase - Emits the necessary code to represent a single node in
1247 /// the binary search tree resulting from lowering a switch instruction.
1248 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1250 SDValue CondLHS = getValue(CB.CmpLHS);
1251 DebugLoc dl = getCurDebugLoc();
1253 // Build the setcc now.
1254 if (CB.CmpMHS == NULL) {
1255 // Fold "(X == true)" to X and "(X == false)" to !X to
1256 // handle common cases produced by branch lowering.
1257 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1258 CB.CC == ISD::SETEQ)
1260 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1261 CB.CC == ISD::SETEQ) {
1262 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1263 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1265 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1267 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1269 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1270 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1272 SDValue CmpOp = getValue(CB.CmpMHS);
1273 EVT VT = CmpOp.getValueType();
1275 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1276 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1279 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1280 VT, CmpOp, DAG.getConstant(Low, VT));
1281 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1282 DAG.getConstant(High-Low, VT), ISD::SETULE);
1286 // Update successor info
1287 CurMBB->addSuccessor(CB.TrueBB);
1288 CurMBB->addSuccessor(CB.FalseBB);
1290 // Set NextBlock to be the MBB immediately after the current one, if any.
1291 // This is used to avoid emitting unnecessary branches to the next block.
1292 MachineBasicBlock *NextBlock = 0;
1293 MachineFunction::iterator BBI = CurMBB;
1294 if (++BBI != FuncInfo.MF->end())
1297 // If the lhs block is the next block, invert the condition so that we can
1298 // fall through to the lhs instead of the rhs block.
1299 if (CB.TrueBB == NextBlock) {
1300 std::swap(CB.TrueBB, CB.FalseBB);
1301 SDValue True = DAG.getConstant(1, Cond.getValueType());
1302 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1305 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1306 MVT::Other, getControlRoot(), Cond,
1307 DAG.getBasicBlock(CB.TrueBB));
1309 // If the branch was constant folded, fix up the CFG.
1310 if (BrCond.getOpcode() == ISD::BR) {
1311 CurMBB->removeSuccessor(CB.FalseBB);
1313 // Otherwise, go ahead and insert the false branch.
1314 if (BrCond == getControlRoot())
1315 CurMBB->removeSuccessor(CB.TrueBB);
1317 if (CB.FalseBB != NextBlock)
1318 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1319 DAG.getBasicBlock(CB.FalseBB));
1322 DAG.setRoot(BrCond);
1325 /// visitJumpTable - Emit JumpTable node in the current MBB
1326 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1327 // Emit the code for the jump table
1328 assert(JT.Reg != -1U && "Should lower JT Header first!");
1329 EVT PTy = TLI.getPointerTy();
1330 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1332 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1333 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1334 MVT::Other, Index.getValue(1),
1336 DAG.setRoot(BrJumpTable);
1339 /// visitJumpTableHeader - This function emits necessary code to produce index
1340 /// in the JumpTable from switch case.
1341 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1342 JumpTableHeader &JTH) {
1343 // Subtract the lowest switch case value from the value being switched on and
1344 // conditional branch to default mbb if the result is greater than the
1345 // difference between smallest and largest cases.
1346 SDValue SwitchOp = getValue(JTH.SValue);
1347 EVT VT = SwitchOp.getValueType();
1348 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1349 DAG.getConstant(JTH.First, VT));
1351 // The SDNode we just created, which holds the value being switched on minus
1352 // the the smallest case value, needs to be copied to a virtual register so it
1353 // can be used as an index into the jump table in a subsequent basic block.
1354 // This value may be smaller or larger than the target's pointer type, and
1355 // therefore require extension or truncating.
1356 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1358 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1359 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1360 JumpTableReg, SwitchOp);
1361 JT.Reg = JumpTableReg;
1363 // Emit the range check for the jump table, and branch to the default block
1364 // for the switch statement if the value being switched on exceeds the largest
1365 // case in the switch.
1366 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1367 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1368 DAG.getConstant(JTH.Last-JTH.First,VT),
1371 // Set NextBlock to be the MBB immediately after the current one, if any.
1372 // This is used to avoid emitting unnecessary branches to the next block.
1373 MachineBasicBlock *NextBlock = 0;
1374 MachineFunction::iterator BBI = CurMBB;
1376 if (++BBI != FuncInfo.MF->end())
1379 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1380 MVT::Other, CopyTo, CMP,
1381 DAG.getBasicBlock(JT.Default));
1383 if (JT.MBB != NextBlock)
1384 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1385 DAG.getBasicBlock(JT.MBB));
1387 DAG.setRoot(BrCond);
1390 /// visitBitTestHeader - This function emits necessary code to produce value
1391 /// suitable for "bit tests"
1392 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1393 // Subtract the minimum value
1394 SDValue SwitchOp = getValue(B.SValue);
1395 EVT VT = SwitchOp.getValueType();
1396 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1397 DAG.getConstant(B.First, VT));
1400 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1401 TLI.getSetCCResultType(Sub.getValueType()),
1402 Sub, DAG.getConstant(B.Range, VT),
1405 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1406 TLI.getPointerTy());
1408 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1409 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1412 // Set NextBlock to be the MBB immediately after the current one, if any.
1413 // This is used to avoid emitting unnecessary branches to the next block.
1414 MachineBasicBlock *NextBlock = 0;
1415 MachineFunction::iterator BBI = CurMBB;
1416 if (++BBI != FuncInfo.MF->end())
1419 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1421 CurMBB->addSuccessor(B.Default);
1422 CurMBB->addSuccessor(MBB);
1424 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1425 MVT::Other, CopyTo, RangeCmp,
1426 DAG.getBasicBlock(B.Default));
1428 if (MBB != NextBlock)
1429 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1430 DAG.getBasicBlock(MBB));
1432 DAG.setRoot(BrRange);
1435 /// visitBitTestCase - this function produces one "bit test"
1436 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1439 // Make desired shift
1440 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1441 TLI.getPointerTy());
1442 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1444 DAG.getConstant(1, TLI.getPointerTy()),
1447 // Emit bit tests and jumps
1448 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1449 TLI.getPointerTy(), SwitchVal,
1450 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1451 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1452 TLI.getSetCCResultType(AndOp.getValueType()),
1453 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1456 CurMBB->addSuccessor(B.TargetBB);
1457 CurMBB->addSuccessor(NextMBB);
1459 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1460 MVT::Other, getControlRoot(),
1461 AndCmp, DAG.getBasicBlock(B.TargetBB));
1463 // Set NextBlock to be the MBB immediately after the current one, if any.
1464 // This is used to avoid emitting unnecessary branches to the next block.
1465 MachineBasicBlock *NextBlock = 0;
1466 MachineFunction::iterator BBI = CurMBB;
1467 if (++BBI != FuncInfo.MF->end())
1470 if (NextMBB != NextBlock)
1471 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1472 DAG.getBasicBlock(NextMBB));
1477 void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
1478 // Retrieve successors.
1479 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1480 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1482 const Value *Callee(I.getCalledValue());
1483 if (isa<InlineAsm>(Callee))
1486 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1488 // If the value of the invoke is used outside of its defining block, make it
1489 // available as a virtual register.
1490 CopyToExportRegsIfNeeded(&I);
1492 // Update successor info
1493 CurMBB->addSuccessor(Return);
1494 CurMBB->addSuccessor(LandingPad);
1496 // Drop into normal successor.
1497 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1498 MVT::Other, getControlRoot(),
1499 DAG.getBasicBlock(Return)));
1502 void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
1505 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1506 /// small case ranges).
1507 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1508 CaseRecVector& WorkList,
1510 MachineBasicBlock* Default) {
1511 Case& BackCase = *(CR.Range.second-1);
1513 // Size is the number of Cases represented by this range.
1514 size_t Size = CR.Range.second - CR.Range.first;
1518 // Get the MachineFunction which holds the current MBB. This is used when
1519 // inserting any additional MBBs necessary to represent the switch.
1520 MachineFunction *CurMF = FuncInfo.MF;
1522 // Figure out which block is immediately after the current one.
1523 MachineBasicBlock *NextBlock = 0;
1524 MachineFunction::iterator BBI = CR.CaseBB;
1526 if (++BBI != FuncInfo.MF->end())
1529 // TODO: If any two of the cases has the same destination, and if one value
1530 // is the same as the other, but has one bit unset that the other has set,
1531 // use bit manipulation to do two compares at once. For example:
1532 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1534 // Rearrange the case blocks so that the last one falls through if possible.
1535 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1536 // The last case block won't fall through into 'NextBlock' if we emit the
1537 // branches in this order. See if rearranging a case value would help.
1538 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1539 if (I->BB == NextBlock) {
1540 std::swap(*I, BackCase);
1546 // Create a CaseBlock record representing a conditional branch to
1547 // the Case's target mbb if the value being switched on SV is equal
1549 MachineBasicBlock *CurBlock = CR.CaseBB;
1550 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1551 MachineBasicBlock *FallThrough;
1553 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1554 CurMF->insert(BBI, FallThrough);
1556 // Put SV in a virtual register to make it available from the new blocks.
1557 ExportFromCurrentBlock(SV);
1559 // If the last case doesn't match, go to the default block.
1560 FallThrough = Default;
1563 Value *RHS, *LHS, *MHS;
1565 if (I->High == I->Low) {
1566 // This is just small small case range :) containing exactly 1 case
1568 LHS = SV; RHS = I->High; MHS = NULL;
1571 LHS = I->Low; MHS = SV; RHS = I->High;
1573 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1575 // If emitting the first comparison, just call visitSwitchCase to emit the
1576 // code into the current block. Otherwise, push the CaseBlock onto the
1577 // vector to be later processed by SDISel, and insert the node's MBB
1578 // before the next MBB.
1579 if (CurBlock == CurMBB)
1580 visitSwitchCase(CB);
1582 SwitchCases.push_back(CB);
1584 CurBlock = FallThrough;
1590 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1591 return !DisableJumpTables &&
1592 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1593 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1596 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1597 APInt LastExt(Last), FirstExt(First);
1598 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1599 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1600 return (LastExt - FirstExt + 1ULL);
1603 /// handleJTSwitchCase - Emit jumptable for current switch case range
1604 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1605 CaseRecVector& WorkList,
1607 MachineBasicBlock* Default) {
1608 Case& FrontCase = *CR.Range.first;
1609 Case& BackCase = *(CR.Range.second-1);
1611 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1612 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1614 APInt TSize(First.getBitWidth(), 0);
1615 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1619 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1622 APInt Range = ComputeRange(First, Last);
1623 double Density = TSize.roundToDouble() / Range.roundToDouble();
1627 DEBUG(dbgs() << "Lowering jump table\n"
1628 << "First entry: " << First << ". Last entry: " << Last << '\n'
1629 << "Range: " << Range
1630 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1632 // Get the MachineFunction which holds the current MBB. This is used when
1633 // inserting any additional MBBs necessary to represent the switch.
1634 MachineFunction *CurMF = FuncInfo.MF;
1636 // Figure out which block is immediately after the current one.
1637 MachineFunction::iterator BBI = CR.CaseBB;
1640 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1642 // Create a new basic block to hold the code for loading the address
1643 // of the jump table, and jumping to it. Update successor information;
1644 // we will either branch to the default case for the switch, or the jump
1646 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1647 CurMF->insert(BBI, JumpTableBB);
1648 CR.CaseBB->addSuccessor(Default);
1649 CR.CaseBB->addSuccessor(JumpTableBB);
1651 // Build a vector of destination BBs, corresponding to each target
1652 // of the jump table. If the value of the jump table slot corresponds to
1653 // a case statement, push the case's BB onto the vector, otherwise, push
1655 std::vector<MachineBasicBlock*> DestBBs;
1657 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1658 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1659 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1661 if (Low.sle(TEI) && TEI.sle(High)) {
1662 DestBBs.push_back(I->BB);
1666 DestBBs.push_back(Default);
1670 // Update successor info. Add one edge to each unique successor.
1671 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1672 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1673 E = DestBBs.end(); I != E; ++I) {
1674 if (!SuccsHandled[(*I)->getNumber()]) {
1675 SuccsHandled[(*I)->getNumber()] = true;
1676 JumpTableBB->addSuccessor(*I);
1680 // Create a jump table index for this jump table, or return an existing
1682 unsigned JTEncoding = TLI.getJumpTableEncoding();
1683 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1684 ->getJumpTableIndex(DestBBs);
1686 // Set the jump table information so that we can codegen it as a second
1687 // MachineBasicBlock
1688 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1689 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1690 if (CR.CaseBB == CurMBB)
1691 visitJumpTableHeader(JT, JTH);
1693 JTCases.push_back(JumpTableBlock(JTH, JT));
1698 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1700 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1701 CaseRecVector& WorkList,
1703 MachineBasicBlock* Default) {
1704 // Get the MachineFunction which holds the current MBB. This is used when
1705 // inserting any additional MBBs necessary to represent the switch.
1706 MachineFunction *CurMF = FuncInfo.MF;
1708 // Figure out which block is immediately after the current one.
1709 MachineFunction::iterator BBI = CR.CaseBB;
1712 Case& FrontCase = *CR.Range.first;
1713 Case& BackCase = *(CR.Range.second-1);
1714 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1716 // Size is the number of Cases represented by this range.
1717 unsigned Size = CR.Range.second - CR.Range.first;
1719 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1720 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1722 CaseItr Pivot = CR.Range.first + Size/2;
1724 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1725 // (heuristically) allow us to emit JumpTable's later.
1726 APInt TSize(First.getBitWidth(), 0);
1727 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1731 APInt LSize = FrontCase.size();
1732 APInt RSize = TSize-LSize;
1733 DEBUG(dbgs() << "Selecting best pivot: \n"
1734 << "First: " << First << ", Last: " << Last <<'\n'
1735 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1736 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1738 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1739 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1740 APInt Range = ComputeRange(LEnd, RBegin);
1741 assert((Range - 2ULL).isNonNegative() &&
1742 "Invalid case distance");
1743 double LDensity = (double)LSize.roundToDouble() /
1744 (LEnd - First + 1ULL).roundToDouble();
1745 double RDensity = (double)RSize.roundToDouble() /
1746 (Last - RBegin + 1ULL).roundToDouble();
1747 double Metric = Range.logBase2()*(LDensity+RDensity);
1748 // Should always split in some non-trivial place
1749 DEBUG(dbgs() <<"=>Step\n"
1750 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1751 << "LDensity: " << LDensity
1752 << ", RDensity: " << RDensity << '\n'
1753 << "Metric: " << Metric << '\n');
1754 if (FMetric < Metric) {
1757 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
1763 if (areJTsAllowed(TLI)) {
1764 // If our case is dense we *really* should handle it earlier!
1765 assert((FMetric > 0) && "Should handle dense range earlier!");
1767 Pivot = CR.Range.first + Size/2;
1770 CaseRange LHSR(CR.Range.first, Pivot);
1771 CaseRange RHSR(Pivot, CR.Range.second);
1772 Constant *C = Pivot->Low;
1773 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1775 // We know that we branch to the LHS if the Value being switched on is
1776 // less than the Pivot value, C. We use this to optimize our binary
1777 // tree a bit, by recognizing that if SV is greater than or equal to the
1778 // LHS's Case Value, and that Case Value is exactly one less than the
1779 // Pivot's Value, then we can branch directly to the LHS's Target,
1780 // rather than creating a leaf node for it.
1781 if ((LHSR.second - LHSR.first) == 1 &&
1782 LHSR.first->High == CR.GE &&
1783 cast<ConstantInt>(C)->getValue() ==
1784 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1785 TrueBB = LHSR.first->BB;
1787 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1788 CurMF->insert(BBI, TrueBB);
1789 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1791 // Put SV in a virtual register to make it available from the new blocks.
1792 ExportFromCurrentBlock(SV);
1795 // Similar to the optimization above, if the Value being switched on is
1796 // known to be less than the Constant CR.LT, and the current Case Value
1797 // is CR.LT - 1, then we can branch directly to the target block for
1798 // the current Case Value, rather than emitting a RHS leaf node for it.
1799 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1800 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1801 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1802 FalseBB = RHSR.first->BB;
1804 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1805 CurMF->insert(BBI, FalseBB);
1806 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1808 // Put SV in a virtual register to make it available from the new blocks.
1809 ExportFromCurrentBlock(SV);
1812 // Create a CaseBlock record representing a conditional branch to
1813 // the LHS node if the value being switched on SV is less than C.
1814 // Otherwise, branch to LHS.
1815 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1817 if (CR.CaseBB == CurMBB)
1818 visitSwitchCase(CB);
1820 SwitchCases.push_back(CB);
1825 /// handleBitTestsSwitchCase - if current case range has few destination and
1826 /// range span less, than machine word bitwidth, encode case range into series
1827 /// of masks and emit bit tests with these masks.
1828 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1829 CaseRecVector& WorkList,
1831 MachineBasicBlock* Default){
1832 EVT PTy = TLI.getPointerTy();
1833 unsigned IntPtrBits = PTy.getSizeInBits();
1835 Case& FrontCase = *CR.Range.first;
1836 Case& BackCase = *(CR.Range.second-1);
1838 // Get the MachineFunction which holds the current MBB. This is used when
1839 // inserting any additional MBBs necessary to represent the switch.
1840 MachineFunction *CurMF = FuncInfo.MF;
1842 // If target does not have legal shift left, do not emit bit tests at all.
1843 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1847 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1849 // Single case counts one, case range - two.
1850 numCmps += (I->Low == I->High ? 1 : 2);
1853 // Count unique destinations
1854 SmallSet<MachineBasicBlock*, 4> Dests;
1855 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1856 Dests.insert(I->BB);
1857 if (Dests.size() > 3)
1858 // Don't bother the code below, if there are too much unique destinations
1861 DEBUG(dbgs() << "Total number of unique destinations: "
1862 << Dests.size() << '\n'
1863 << "Total number of comparisons: " << numCmps << '\n');
1865 // Compute span of values.
1866 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1867 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1868 APInt cmpRange = maxValue - minValue;
1870 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
1871 << "Low bound: " << minValue << '\n'
1872 << "High bound: " << maxValue << '\n');
1874 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1875 (!(Dests.size() == 1 && numCmps >= 3) &&
1876 !(Dests.size() == 2 && numCmps >= 5) &&
1877 !(Dests.size() >= 3 && numCmps >= 6)))
1880 DEBUG(dbgs() << "Emitting bit tests\n");
1881 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1883 // Optimize the case where all the case values fit in a
1884 // word without having to subtract minValue. In this case,
1885 // we can optimize away the subtraction.
1886 if (minValue.isNonNegative() &&
1887 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1888 cmpRange = maxValue;
1890 lowBound = minValue;
1893 CaseBitsVector CasesBits;
1894 unsigned i, count = 0;
1896 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1897 MachineBasicBlock* Dest = I->BB;
1898 for (i = 0; i < count; ++i)
1899 if (Dest == CasesBits[i].BB)
1903 assert((count < 3) && "Too much destinations to test!");
1904 CasesBits.push_back(CaseBits(0, Dest, 0));
1908 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1909 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1911 uint64_t lo = (lowValue - lowBound).getZExtValue();
1912 uint64_t hi = (highValue - lowBound).getZExtValue();
1914 for (uint64_t j = lo; j <= hi; j++) {
1915 CasesBits[i].Mask |= 1ULL << j;
1916 CasesBits[i].Bits++;
1920 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1924 // Figure out which block is immediately after the current one.
1925 MachineFunction::iterator BBI = CR.CaseBB;
1928 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1930 DEBUG(dbgs() << "Cases:\n");
1931 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1932 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
1933 << ", Bits: " << CasesBits[i].Bits
1934 << ", BB: " << CasesBits[i].BB << '\n');
1936 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1937 CurMF->insert(BBI, CaseBB);
1938 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1942 // Put SV in a virtual register to make it available from the new blocks.
1943 ExportFromCurrentBlock(SV);
1946 BitTestBlock BTB(lowBound, cmpRange, SV,
1947 -1U, (CR.CaseBB == CurMBB),
1948 CR.CaseBB, Default, BTC);
1950 if (CR.CaseBB == CurMBB)
1951 visitBitTestHeader(BTB);
1953 BitTestCases.push_back(BTB);
1958 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1959 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1960 const SwitchInst& SI) {
1963 // Start with "simple" cases
1964 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1965 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1966 Cases.push_back(Case(SI.getSuccessorValue(i),
1967 SI.getSuccessorValue(i),
1970 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1972 // Merge case into clusters
1973 if (Cases.size() >= 2)
1974 // Must recompute end() each iteration because it may be
1975 // invalidated by erase if we hold on to it
1976 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1977 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1978 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1979 MachineBasicBlock* nextBB = J->BB;
1980 MachineBasicBlock* currentBB = I->BB;
1982 // If the two neighboring cases go to the same destination, merge them
1983 // into a single case.
1984 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1992 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1993 if (I->Low != I->High)
1994 // A range counts double, since it requires two compares.
2001 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
2002 // Figure out which block is immediately after the current one.
2003 MachineBasicBlock *NextBlock = 0;
2004 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2006 // If there is only the default destination, branch to it if it is not the
2007 // next basic block. Otherwise, just fall through.
2008 if (SI.getNumOperands() == 2) {
2009 // Update machine-CFG edges.
2011 // If this is not a fall-through branch, emit the branch.
2012 CurMBB->addSuccessor(Default);
2013 if (Default != NextBlock)
2014 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2015 MVT::Other, getControlRoot(),
2016 DAG.getBasicBlock(Default)));
2021 // If there are any non-default case statements, create a vector of Cases
2022 // representing each one, and sort the vector so that we can efficiently
2023 // create a binary search tree from them.
2025 size_t numCmps = Clusterify(Cases, SI);
2026 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2027 << ". Total compares: " << numCmps << '\n');
2030 // Get the Value to be switched on and default basic blocks, which will be
2031 // inserted into CaseBlock records, representing basic blocks in the binary
2033 Value *SV = SI.getOperand(0);
2035 // Push the initial CaseRec onto the worklist
2036 CaseRecVector WorkList;
2037 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2039 while (!WorkList.empty()) {
2040 // Grab a record representing a case range to process off the worklist
2041 CaseRec CR = WorkList.back();
2042 WorkList.pop_back();
2044 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2047 // If the range has few cases (two or less) emit a series of specific
2049 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2052 // If the switch has more than 5 blocks, and at least 40% dense, and the
2053 // target supports indirect branches, then emit a jump table rather than
2054 // lowering the switch to a binary tree of conditional branches.
2055 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2058 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2059 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2060 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2064 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
2065 // Update machine-CFG edges.
2066 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2067 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2069 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2070 MVT::Other, getControlRoot(),
2071 getValue(I.getAddress())));
2074 void SelectionDAGBuilder::visitFSub(User &I) {
2075 // -0.0 - X --> fneg
2076 const Type *Ty = I.getType();
2077 if (isa<VectorType>(Ty)) {
2078 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2079 const VectorType *DestTy = cast<VectorType>(I.getType());
2080 const Type *ElTy = DestTy->getElementType();
2081 unsigned VL = DestTy->getNumElements();
2082 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2083 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2085 SDValue Op2 = getValue(I.getOperand(1));
2086 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2087 Op2.getValueType(), Op2));
2093 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2094 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2095 SDValue Op2 = getValue(I.getOperand(1));
2096 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2097 Op2.getValueType(), Op2));
2101 visitBinary(I, ISD::FSUB);
2104 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2105 SDValue Op1 = getValue(I.getOperand(0));
2106 SDValue Op2 = getValue(I.getOperand(1));
2107 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2108 Op1.getValueType(), Op1, Op2));
2111 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2112 SDValue Op1 = getValue(I.getOperand(0));
2113 SDValue Op2 = getValue(I.getOperand(1));
2114 if (!isa<VectorType>(I.getType()) &&
2115 Op2.getValueType() != TLI.getShiftAmountTy()) {
2116 // If the operand is smaller than the shift count type, promote it.
2117 EVT PTy = TLI.getPointerTy();
2118 EVT STy = TLI.getShiftAmountTy();
2119 if (STy.bitsGT(Op2.getValueType()))
2120 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2121 TLI.getShiftAmountTy(), Op2);
2122 // If the operand is larger than the shift count type but the shift
2123 // count type has enough bits to represent any shift value, truncate
2124 // it now. This is a common case and it exposes the truncate to
2125 // optimization early.
2126 else if (STy.getSizeInBits() >=
2127 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2128 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2129 TLI.getShiftAmountTy(), Op2);
2130 // Otherwise we'll need to temporarily settle for some other
2131 // convenient type; type legalization will make adjustments as
2133 else if (PTy.bitsLT(Op2.getValueType()))
2134 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2135 TLI.getPointerTy(), Op2);
2136 else if (PTy.bitsGT(Op2.getValueType()))
2137 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2138 TLI.getPointerTy(), Op2);
2141 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2142 Op1.getValueType(), Op1, Op2));
2145 void SelectionDAGBuilder::visitICmp(User &I) {
2146 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2147 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2148 predicate = IC->getPredicate();
2149 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2150 predicate = ICmpInst::Predicate(IC->getPredicate());
2151 SDValue Op1 = getValue(I.getOperand(0));
2152 SDValue Op2 = getValue(I.getOperand(1));
2153 ISD::CondCode Opcode = getICmpCondCode(predicate);
2155 EVT DestVT = TLI.getValueType(I.getType());
2156 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2159 void SelectionDAGBuilder::visitFCmp(User &I) {
2160 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2161 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2162 predicate = FC->getPredicate();
2163 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2164 predicate = FCmpInst::Predicate(FC->getPredicate());
2165 SDValue Op1 = getValue(I.getOperand(0));
2166 SDValue Op2 = getValue(I.getOperand(1));
2167 ISD::CondCode Condition = getFCmpCondCode(predicate);
2168 EVT DestVT = TLI.getValueType(I.getType());
2169 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2172 void SelectionDAGBuilder::visitSelect(User &I) {
2173 SmallVector<EVT, 4> ValueVTs;
2174 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2175 unsigned NumValues = ValueVTs.size();
2176 if (NumValues == 0) return;
2178 SmallVector<SDValue, 4> Values(NumValues);
2179 SDValue Cond = getValue(I.getOperand(0));
2180 SDValue TrueVal = getValue(I.getOperand(1));
2181 SDValue FalseVal = getValue(I.getOperand(2));
2183 for (unsigned i = 0; i != NumValues; ++i)
2184 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2185 TrueVal.getNode()->getValueType(i), Cond,
2186 SDValue(TrueVal.getNode(),
2187 TrueVal.getResNo() + i),
2188 SDValue(FalseVal.getNode(),
2189 FalseVal.getResNo() + i));
2191 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2192 DAG.getVTList(&ValueVTs[0], NumValues),
2193 &Values[0], NumValues));
2196 void SelectionDAGBuilder::visitTrunc(User &I) {
2197 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2198 SDValue N = getValue(I.getOperand(0));
2199 EVT DestVT = TLI.getValueType(I.getType());
2200 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2203 void SelectionDAGBuilder::visitZExt(User &I) {
2204 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2205 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2206 SDValue N = getValue(I.getOperand(0));
2207 EVT DestVT = TLI.getValueType(I.getType());
2208 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2211 void SelectionDAGBuilder::visitSExt(User &I) {
2212 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2213 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2214 SDValue N = getValue(I.getOperand(0));
2215 EVT DestVT = TLI.getValueType(I.getType());
2216 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2219 void SelectionDAGBuilder::visitFPTrunc(User &I) {
2220 // FPTrunc is never a no-op cast, no need to check
2221 SDValue N = getValue(I.getOperand(0));
2222 EVT DestVT = TLI.getValueType(I.getType());
2223 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2224 DestVT, N, DAG.getIntPtrConstant(0)));
2227 void SelectionDAGBuilder::visitFPExt(User &I){
2228 // FPTrunc is never a no-op cast, no need to check
2229 SDValue N = getValue(I.getOperand(0));
2230 EVT DestVT = TLI.getValueType(I.getType());
2231 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2234 void SelectionDAGBuilder::visitFPToUI(User &I) {
2235 // FPToUI is never a no-op cast, no need to check
2236 SDValue N = getValue(I.getOperand(0));
2237 EVT DestVT = TLI.getValueType(I.getType());
2238 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2241 void SelectionDAGBuilder::visitFPToSI(User &I) {
2242 // FPToSI is never a no-op cast, no need to check
2243 SDValue N = getValue(I.getOperand(0));
2244 EVT DestVT = TLI.getValueType(I.getType());
2245 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2248 void SelectionDAGBuilder::visitUIToFP(User &I) {
2249 // UIToFP is never a no-op cast, no need to check
2250 SDValue N = getValue(I.getOperand(0));
2251 EVT DestVT = TLI.getValueType(I.getType());
2252 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2255 void SelectionDAGBuilder::visitSIToFP(User &I){
2256 // SIToFP is never a no-op cast, no need to check
2257 SDValue N = getValue(I.getOperand(0));
2258 EVT DestVT = TLI.getValueType(I.getType());
2259 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2262 void SelectionDAGBuilder::visitPtrToInt(User &I) {
2263 // What to do depends on the size of the integer and the size of the pointer.
2264 // We can either truncate, zero extend, or no-op, accordingly.
2265 SDValue N = getValue(I.getOperand(0));
2266 EVT SrcVT = N.getValueType();
2267 EVT DestVT = TLI.getValueType(I.getType());
2268 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2271 void SelectionDAGBuilder::visitIntToPtr(User &I) {
2272 // What to do depends on the size of the integer and the size of the pointer.
2273 // We can either truncate, zero extend, or no-op, accordingly.
2274 SDValue N = getValue(I.getOperand(0));
2275 EVT SrcVT = N.getValueType();
2276 EVT DestVT = TLI.getValueType(I.getType());
2277 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2280 void SelectionDAGBuilder::visitBitCast(User &I) {
2281 SDValue N = getValue(I.getOperand(0));
2282 EVT DestVT = TLI.getValueType(I.getType());
2284 // BitCast assures us that source and destination are the same size so this is
2285 // either a BIT_CONVERT or a no-op.
2286 if (DestVT != N.getValueType())
2287 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2288 DestVT, N)); // convert types.
2290 setValue(&I, N); // noop cast.
2293 void SelectionDAGBuilder::visitInsertElement(User &I) {
2294 SDValue InVec = getValue(I.getOperand(0));
2295 SDValue InVal = getValue(I.getOperand(1));
2296 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2298 getValue(I.getOperand(2)));
2299 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2300 TLI.getValueType(I.getType()),
2301 InVec, InVal, InIdx));
2304 void SelectionDAGBuilder::visitExtractElement(User &I) {
2305 SDValue InVec = getValue(I.getOperand(0));
2306 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2308 getValue(I.getOperand(1)));
2309 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2310 TLI.getValueType(I.getType()), InVec, InIdx));
2313 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2314 // from SIndx and increasing to the element length (undefs are allowed).
2315 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2316 unsigned MaskNumElts = Mask.size();
2317 for (unsigned i = 0; i != MaskNumElts; ++i)
2318 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2323 void SelectionDAGBuilder::visitShuffleVector(User &I) {
2324 SmallVector<int, 8> Mask;
2325 SDValue Src1 = getValue(I.getOperand(0));
2326 SDValue Src2 = getValue(I.getOperand(1));
2328 // Convert the ConstantVector mask operand into an array of ints, with -1
2329 // representing undef values.
2330 SmallVector<Constant*, 8> MaskElts;
2331 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2332 unsigned MaskNumElts = MaskElts.size();
2333 for (unsigned i = 0; i != MaskNumElts; ++i) {
2334 if (isa<UndefValue>(MaskElts[i]))
2337 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2340 EVT VT = TLI.getValueType(I.getType());
2341 EVT SrcVT = Src1.getValueType();
2342 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2344 if (SrcNumElts == MaskNumElts) {
2345 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2350 // Normalize the shuffle vector since mask and vector length don't match.
2351 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2352 // Mask is longer than the source vectors and is a multiple of the source
2353 // vectors. We can use concatenate vector to make the mask and vectors
2355 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2356 // The shuffle is concatenating two vectors together.
2357 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2362 // Pad both vectors with undefs to make them the same length as the mask.
2363 unsigned NumConcat = MaskNumElts / SrcNumElts;
2364 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2365 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2366 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2368 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2369 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2373 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2374 getCurDebugLoc(), VT,
2375 &MOps1[0], NumConcat);
2376 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2377 getCurDebugLoc(), VT,
2378 &MOps2[0], NumConcat);
2380 // Readjust mask for new input vector length.
2381 SmallVector<int, 8> MappedOps;
2382 for (unsigned i = 0; i != MaskNumElts; ++i) {
2384 if (Idx < (int)SrcNumElts)
2385 MappedOps.push_back(Idx);
2387 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2390 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2395 if (SrcNumElts > MaskNumElts) {
2396 // Analyze the access pattern of the vector to see if we can extract
2397 // two subvectors and do the shuffle. The analysis is done by calculating
2398 // the range of elements the mask access on both vectors.
2399 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2400 int MaxRange[2] = {-1, -1};
2402 for (unsigned i = 0; i != MaskNumElts; ++i) {
2408 if (Idx >= (int)SrcNumElts) {
2412 if (Idx > MaxRange[Input])
2413 MaxRange[Input] = Idx;
2414 if (Idx < MinRange[Input])
2415 MinRange[Input] = Idx;
2418 // Check if the access is smaller than the vector size and can we find
2419 // a reasonable extract index.
2420 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2422 int StartIdx[2]; // StartIdx to extract from
2423 for (int Input=0; Input < 2; ++Input) {
2424 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2425 RangeUse[Input] = 0; // Unused
2426 StartIdx[Input] = 0;
2427 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2428 // Fits within range but we should see if we can find a good
2429 // start index that is a multiple of the mask length.
2430 if (MaxRange[Input] < (int)MaskNumElts) {
2431 RangeUse[Input] = 1; // Extract from beginning of the vector
2432 StartIdx[Input] = 0;
2434 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2435 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2436 StartIdx[Input] + MaskNumElts < SrcNumElts)
2437 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2442 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2443 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2446 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2447 // Extract appropriate subvector and generate a vector shuffle
2448 for (int Input=0; Input < 2; ++Input) {
2449 SDValue &Src = Input == 0 ? Src1 : Src2;
2450 if (RangeUse[Input] == 0)
2451 Src = DAG.getUNDEF(VT);
2453 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2454 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2457 // Calculate new mask.
2458 SmallVector<int, 8> MappedOps;
2459 for (unsigned i = 0; i != MaskNumElts; ++i) {
2462 MappedOps.push_back(Idx);
2463 else if (Idx < (int)SrcNumElts)
2464 MappedOps.push_back(Idx - StartIdx[0]);
2466 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2469 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2475 // We can't use either concat vectors or extract subvectors so fall back to
2476 // replacing the shuffle with extract and build vector.
2477 // to insert and build vector.
2478 EVT EltVT = VT.getVectorElementType();
2479 EVT PtrVT = TLI.getPointerTy();
2480 SmallVector<SDValue,8> Ops;
2481 for (unsigned i = 0; i != MaskNumElts; ++i) {
2483 Ops.push_back(DAG.getUNDEF(EltVT));
2488 if (Idx < (int)SrcNumElts)
2489 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2490 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2492 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2494 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2500 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2501 VT, &Ops[0], Ops.size()));
2504 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2505 const Value *Op0 = I.getOperand(0);
2506 const Value *Op1 = I.getOperand(1);
2507 const Type *AggTy = I.getType();
2508 const Type *ValTy = Op1->getType();
2509 bool IntoUndef = isa<UndefValue>(Op0);
2510 bool FromUndef = isa<UndefValue>(Op1);
2512 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2513 I.idx_begin(), I.idx_end());
2515 SmallVector<EVT, 4> AggValueVTs;
2516 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2517 SmallVector<EVT, 4> ValValueVTs;
2518 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2520 unsigned NumAggValues = AggValueVTs.size();
2521 unsigned NumValValues = ValValueVTs.size();
2522 SmallVector<SDValue, 4> Values(NumAggValues);
2524 SDValue Agg = getValue(Op0);
2525 SDValue Val = getValue(Op1);
2527 // Copy the beginning value(s) from the original aggregate.
2528 for (; i != LinearIndex; ++i)
2529 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2530 SDValue(Agg.getNode(), Agg.getResNo() + i);
2531 // Copy values from the inserted value(s).
2532 for (; i != LinearIndex + NumValValues; ++i)
2533 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2534 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2535 // Copy remaining value(s) from the original aggregate.
2536 for (; i != NumAggValues; ++i)
2537 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2538 SDValue(Agg.getNode(), Agg.getResNo() + i);
2540 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2541 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2542 &Values[0], NumAggValues));
2545 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2546 const Value *Op0 = I.getOperand(0);
2547 const Type *AggTy = Op0->getType();
2548 const Type *ValTy = I.getType();
2549 bool OutOfUndef = isa<UndefValue>(Op0);
2551 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2552 I.idx_begin(), I.idx_end());
2554 SmallVector<EVT, 4> ValValueVTs;
2555 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2557 unsigned NumValValues = ValValueVTs.size();
2558 SmallVector<SDValue, 4> Values(NumValValues);
2560 SDValue Agg = getValue(Op0);
2561 // Copy out the selected value(s).
2562 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2563 Values[i - LinearIndex] =
2565 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2566 SDValue(Agg.getNode(), Agg.getResNo() + i);
2568 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2569 DAG.getVTList(&ValValueVTs[0], NumValValues),
2570 &Values[0], NumValValues));
2573 void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2574 SDValue N = getValue(I.getOperand(0));
2575 const Type *Ty = I.getOperand(0)->getType();
2577 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2580 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2581 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2584 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2585 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2586 DAG.getIntPtrConstant(Offset));
2589 Ty = StTy->getElementType(Field);
2591 Ty = cast<SequentialType>(Ty)->getElementType();
2593 // If this is a constant subscript, handle it quickly.
2594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2595 if (CI->getZExtValue() == 0) continue;
2597 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2599 EVT PTy = TLI.getPointerTy();
2600 unsigned PtrBits = PTy.getSizeInBits();
2602 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2604 DAG.getConstant(Offs, MVT::i64));
2606 OffsVal = DAG.getIntPtrConstant(Offs);
2608 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2613 // N = N + Idx * ElementSize;
2614 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2615 TD->getTypeAllocSize(Ty));
2616 SDValue IdxN = getValue(Idx);
2618 // If the index is smaller or larger than intptr_t, truncate or extend
2620 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2622 // If this is a multiply by a power of two, turn it into a shl
2623 // immediately. This is a very common case.
2624 if (ElementSize != 1) {
2625 if (ElementSize.isPowerOf2()) {
2626 unsigned Amt = ElementSize.logBase2();
2627 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2628 N.getValueType(), IdxN,
2629 DAG.getConstant(Amt, TLI.getPointerTy()));
2631 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2632 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2633 N.getValueType(), IdxN, Scale);
2637 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2638 N.getValueType(), N, IdxN);
2645 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2646 // If this is a fixed sized alloca in the entry block of the function,
2647 // allocate it statically on the stack.
2648 if (FuncInfo.StaticAllocaMap.count(&I))
2649 return; // getValue will auto-populate this.
2651 const Type *Ty = I.getAllocatedType();
2652 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2654 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2657 SDValue AllocSize = getValue(I.getArraySize());
2659 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2661 DAG.getConstant(TySize, AllocSize.getValueType()));
2663 EVT IntPtr = TLI.getPointerTy();
2664 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2666 // Handle alignment. If the requested alignment is less than or equal to
2667 // the stack alignment, ignore it. If the size is greater than or equal to
2668 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2669 unsigned StackAlign =
2670 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2671 if (Align <= StackAlign)
2674 // Round the size of the allocation up to the stack alignment size
2675 // by add SA-1 to the size.
2676 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2677 AllocSize.getValueType(), AllocSize,
2678 DAG.getIntPtrConstant(StackAlign-1));
2680 // Mask out the low bits for alignment purposes.
2681 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2682 AllocSize.getValueType(), AllocSize,
2683 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2685 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2686 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2687 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2690 DAG.setRoot(DSA.getValue(1));
2692 // Inform the Frame Information that we have just allocated a variable-sized
2694 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2697 void SelectionDAGBuilder::visitLoad(LoadInst &I) {
2698 const Value *SV = I.getOperand(0);
2699 SDValue Ptr = getValue(SV);
2701 const Type *Ty = I.getType();
2702 bool isVolatile = I.isVolatile();
2703 unsigned Alignment = I.getAlignment();
2705 SmallVector<EVT, 4> ValueVTs;
2706 SmallVector<uint64_t, 4> Offsets;
2707 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2708 unsigned NumValues = ValueVTs.size();
2713 bool ConstantMemory = false;
2715 // Serialize volatile loads with other side effects.
2717 else if (AA->pointsToConstantMemory(SV)) {
2718 // Do not serialize (non-volatile) loads of constant memory with anything.
2719 Root = DAG.getEntryNode();
2720 ConstantMemory = true;
2722 // Do not serialize non-volatile loads against each other.
2723 Root = DAG.getRoot();
2726 SmallVector<SDValue, 4> Values(NumValues);
2727 SmallVector<SDValue, 4> Chains(NumValues);
2728 EVT PtrVT = Ptr.getValueType();
2729 for (unsigned i = 0; i != NumValues; ++i) {
2730 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2732 DAG.getConstant(Offsets[i], PtrVT));
2733 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2734 A, SV, Offsets[i], isVolatile, Alignment);
2737 Chains[i] = L.getValue(1);
2740 if (!ConstantMemory) {
2741 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2742 MVT::Other, &Chains[0], NumValues);
2746 PendingLoads.push_back(Chain);
2749 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2750 DAG.getVTList(&ValueVTs[0], NumValues),
2751 &Values[0], NumValues));
2754 void SelectionDAGBuilder::visitStore(StoreInst &I) {
2755 Value *SrcV = I.getOperand(0);
2756 Value *PtrV = I.getOperand(1);
2758 SmallVector<EVT, 4> ValueVTs;
2759 SmallVector<uint64_t, 4> Offsets;
2760 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2761 unsigned NumValues = ValueVTs.size();
2765 // Get the lowered operands. Note that we do this after
2766 // checking if NumResults is zero, because with zero results
2767 // the operands won't have values in the map.
2768 SDValue Src = getValue(SrcV);
2769 SDValue Ptr = getValue(PtrV);
2771 SDValue Root = getRoot();
2772 SmallVector<SDValue, 4> Chains(NumValues);
2773 EVT PtrVT = Ptr.getValueType();
2774 bool isVolatile = I.isVolatile();
2775 unsigned Alignment = I.getAlignment();
2777 for (unsigned i = 0; i != NumValues; ++i) {
2778 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2779 DAG.getConstant(Offsets[i], PtrVT));
2780 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2781 SDValue(Src.getNode(), Src.getResNo() + i),
2782 Add, PtrV, Offsets[i], isVolatile, Alignment);
2785 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2786 MVT::Other, &Chains[0], NumValues));
2789 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2791 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2792 unsigned Intrinsic) {
2793 bool HasChain = !I.doesNotAccessMemory();
2794 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2796 // Build the operand list.
2797 SmallVector<SDValue, 8> Ops;
2798 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2800 // We don't need to serialize loads against other loads.
2801 Ops.push_back(DAG.getRoot());
2803 Ops.push_back(getRoot());
2807 // Info is set by getTgtMemInstrinsic
2808 TargetLowering::IntrinsicInfo Info;
2809 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2811 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2812 if (!IsTgtIntrinsic)
2813 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2815 // Add all operands of the call to the operand list.
2816 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2817 SDValue Op = getValue(I.getOperand(i));
2818 assert(TLI.isTypeLegal(Op.getValueType()) &&
2819 "Intrinsic uses a non-legal type?");
2823 SmallVector<EVT, 4> ValueVTs;
2824 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2826 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2827 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2828 "Intrinsic uses a non-legal type?");
2833 ValueVTs.push_back(MVT::Other);
2835 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2839 if (IsTgtIntrinsic) {
2840 // This is target intrinsic that touches memory
2841 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2842 VTs, &Ops[0], Ops.size(),
2843 Info.memVT, Info.ptrVal, Info.offset,
2844 Info.align, Info.vol,
2845 Info.readMem, Info.writeMem);
2846 } else if (!HasChain) {
2847 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2848 VTs, &Ops[0], Ops.size());
2849 } else if (!I.getType()->isVoidTy()) {
2850 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2851 VTs, &Ops[0], Ops.size());
2853 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2854 VTs, &Ops[0], Ops.size());
2858 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2860 PendingLoads.push_back(Chain);
2865 if (!I.getType()->isVoidTy()) {
2866 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2867 EVT VT = TLI.getValueType(PTy);
2868 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2871 setValue(&I, Result);
2875 /// GetSignificand - Get the significand and build it into a floating-point
2876 /// number with exponent of 1:
2878 /// Op = (Op & 0x007fffff) | 0x3f800000;
2880 /// where Op is the hexidecimal representation of floating point value.
2882 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
2883 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2884 DAG.getConstant(0x007fffff, MVT::i32));
2885 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2886 DAG.getConstant(0x3f800000, MVT::i32));
2887 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
2890 /// GetExponent - Get the exponent:
2892 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
2894 /// where Op is the hexidecimal representation of floating point value.
2896 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
2897 DebugLoc dl, unsigned Order) {
2898 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2899 DAG.getConstant(0x7f800000, MVT::i32));
2900 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
2901 DAG.getConstant(23, TLI.getPointerTy()));
2902 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2903 DAG.getConstant(127, MVT::i32));
2904 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
2907 /// getF32Constant - Get 32-bit floating point constant.
2909 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2910 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2913 /// Inlined utility function to implement binary input atomic intrinsics for
2914 /// visitIntrinsicCall: I is a call instruction
2915 /// Op is the associated NodeType for I
2917 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2918 SDValue Root = getRoot();
2920 DAG.getAtomic(Op, getCurDebugLoc(),
2921 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2923 getValue(I.getOperand(1)),
2924 getValue(I.getOperand(2)),
2927 DAG.setRoot(L.getValue(1));
2931 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2933 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
2934 SDValue Op1 = getValue(I.getOperand(1));
2935 SDValue Op2 = getValue(I.getOperand(2));
2937 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
2938 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
2942 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2943 /// limited-precision mode.
2945 SelectionDAGBuilder::visitExp(CallInst &I) {
2947 DebugLoc dl = getCurDebugLoc();
2949 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2950 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2951 SDValue Op = getValue(I.getOperand(1));
2953 // Put the exponent in the right bit position for later addition to the
2956 // #define LOG2OFe 1.4426950f
2957 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2958 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
2959 getF32Constant(DAG, 0x3fb8aa3b));
2960 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
2962 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2963 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2964 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
2966 // IntegerPartOfX <<= 23;
2967 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
2968 DAG.getConstant(23, TLI.getPointerTy()));
2970 if (LimitFloatPrecision <= 6) {
2971 // For floating-point precision of 6:
2973 // TwoToFractionalPartOfX =
2975 // (0.735607626f + 0.252464424f * x) * x;
2977 // error 0.0144103317, which is 6 bits
2978 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2979 getF32Constant(DAG, 0x3e814304));
2980 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2981 getF32Constant(DAG, 0x3f3c50c8));
2982 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2983 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2984 getF32Constant(DAG, 0x3f7f5e7e));
2985 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
2987 // Add the exponent into the result in integer domain.
2988 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2989 TwoToFracPartOfX, IntegerPartOfX);
2991 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
2992 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2993 // For floating-point precision of 12:
2995 // TwoToFractionalPartOfX =
2998 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3000 // 0.000107046256 error, which is 13 to 14 bits
3001 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3002 getF32Constant(DAG, 0x3da235e3));
3003 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3004 getF32Constant(DAG, 0x3e65b8f3));
3005 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3006 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3007 getF32Constant(DAG, 0x3f324b07));
3008 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3009 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3010 getF32Constant(DAG, 0x3f7ff8fd));
3011 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3013 // Add the exponent into the result in integer domain.
3014 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3015 TwoToFracPartOfX, IntegerPartOfX);
3017 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3018 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3019 // For floating-point precision of 18:
3021 // TwoToFractionalPartOfX =
3025 // (0.554906021e-1f +
3026 // (0.961591928e-2f +
3027 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3029 // error 2.47208000*10^(-7), which is better than 18 bits
3030 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3031 getF32Constant(DAG, 0x3924b03e));
3032 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3033 getF32Constant(DAG, 0x3ab24b87));
3034 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3035 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3036 getF32Constant(DAG, 0x3c1d8c17));
3037 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3038 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3039 getF32Constant(DAG, 0x3d634a1d));
3040 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3041 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3042 getF32Constant(DAG, 0x3e75fe14));
3043 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3044 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3045 getF32Constant(DAG, 0x3f317234));
3046 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3047 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3048 getF32Constant(DAG, 0x3f800000));
3049 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3052 // Add the exponent into the result in integer domain.
3053 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3054 TwoToFracPartOfX, IntegerPartOfX);
3056 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3059 // No special expansion.
3060 result = DAG.getNode(ISD::FEXP, dl,
3061 getValue(I.getOperand(1)).getValueType(),
3062 getValue(I.getOperand(1)));
3065 setValue(&I, result);
3068 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3069 /// limited-precision mode.
3071 SelectionDAGBuilder::visitLog(CallInst &I) {
3073 DebugLoc dl = getCurDebugLoc();
3075 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3076 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3077 SDValue Op = getValue(I.getOperand(1));
3078 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3080 // Scale the exponent by log(2) [0.69314718f].
3081 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3082 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3083 getF32Constant(DAG, 0x3f317218));
3085 // Get the significand and build it into a floating-point number with
3087 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3089 if (LimitFloatPrecision <= 6) {
3090 // For floating-point precision of 6:
3094 // (1.4034025f - 0.23903021f * x) * x;
3096 // error 0.0034276066, which is better than 8 bits
3097 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3098 getF32Constant(DAG, 0xbe74c456));
3099 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3100 getF32Constant(DAG, 0x3fb3a2b1));
3101 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3102 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3103 getF32Constant(DAG, 0x3f949a29));
3105 result = DAG.getNode(ISD::FADD, dl,
3106 MVT::f32, LogOfExponent, LogOfMantissa);
3107 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3108 // For floating-point precision of 12:
3114 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3116 // error 0.000061011436, which is 14 bits
3117 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3118 getF32Constant(DAG, 0xbd67b6d6));
3119 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3120 getF32Constant(DAG, 0x3ee4f4b8));
3121 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3122 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3123 getF32Constant(DAG, 0x3fbc278b));
3124 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3125 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3126 getF32Constant(DAG, 0x40348e95));
3127 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3128 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3129 getF32Constant(DAG, 0x3fdef31a));
3131 result = DAG.getNode(ISD::FADD, dl,
3132 MVT::f32, LogOfExponent, LogOfMantissa);
3133 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3134 // For floating-point precision of 18:
3142 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3144 // error 0.0000023660568, which is better than 18 bits
3145 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3146 getF32Constant(DAG, 0xbc91e5ac));
3147 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3148 getF32Constant(DAG, 0x3e4350aa));
3149 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3150 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3151 getF32Constant(DAG, 0x3f60d3e3));
3152 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3153 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3154 getF32Constant(DAG, 0x4011cdf0));
3155 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3156 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3157 getF32Constant(DAG, 0x406cfd1c));
3158 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3159 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3160 getF32Constant(DAG, 0x408797cb));
3161 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3162 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3163 getF32Constant(DAG, 0x4006dcab));
3165 result = DAG.getNode(ISD::FADD, dl,
3166 MVT::f32, LogOfExponent, LogOfMantissa);
3169 // No special expansion.
3170 result = DAG.getNode(ISD::FLOG, dl,
3171 getValue(I.getOperand(1)).getValueType(),
3172 getValue(I.getOperand(1)));
3175 setValue(&I, result);
3178 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3179 /// limited-precision mode.
3181 SelectionDAGBuilder::visitLog2(CallInst &I) {
3183 DebugLoc dl = getCurDebugLoc();
3185 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3186 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3187 SDValue Op = getValue(I.getOperand(1));
3188 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3190 // Get the exponent.
3191 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3193 // Get the significand and build it into a floating-point number with
3195 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3197 // Different possible minimax approximations of significand in
3198 // floating-point for various degrees of accuracy over [1,2].
3199 if (LimitFloatPrecision <= 6) {
3200 // For floating-point precision of 6:
3202 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3204 // error 0.0049451742, which is more than 7 bits
3205 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3206 getF32Constant(DAG, 0xbeb08fe0));
3207 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3208 getF32Constant(DAG, 0x40019463));
3209 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3210 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3211 getF32Constant(DAG, 0x3fd6633d));
3213 result = DAG.getNode(ISD::FADD, dl,
3214 MVT::f32, LogOfExponent, Log2ofMantissa);
3215 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3216 // For floating-point precision of 12:
3222 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3224 // error 0.0000876136000, which is better than 13 bits
3225 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3226 getF32Constant(DAG, 0xbda7262e));
3227 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3228 getF32Constant(DAG, 0x3f25280b));
3229 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3230 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3231 getF32Constant(DAG, 0x4007b923));
3232 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3233 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3234 getF32Constant(DAG, 0x40823e2f));
3235 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3236 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3237 getF32Constant(DAG, 0x4020d29c));
3239 result = DAG.getNode(ISD::FADD, dl,
3240 MVT::f32, LogOfExponent, Log2ofMantissa);
3241 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3242 // For floating-point precision of 18:
3251 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3253 // error 0.0000018516, which is better than 18 bits
3254 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3255 getF32Constant(DAG, 0xbcd2769e));
3256 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3257 getF32Constant(DAG, 0x3e8ce0b9));
3258 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3259 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3260 getF32Constant(DAG, 0x3fa22ae7));
3261 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3262 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3263 getF32Constant(DAG, 0x40525723));
3264 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3265 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3266 getF32Constant(DAG, 0x40aaf200));
3267 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3268 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3269 getF32Constant(DAG, 0x40c39dad));
3270 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3271 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3272 getF32Constant(DAG, 0x4042902c));
3274 result = DAG.getNode(ISD::FADD, dl,
3275 MVT::f32, LogOfExponent, Log2ofMantissa);
3278 // No special expansion.
3279 result = DAG.getNode(ISD::FLOG2, dl,
3280 getValue(I.getOperand(1)).getValueType(),
3281 getValue(I.getOperand(1)));
3284 setValue(&I, result);
3287 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3288 /// limited-precision mode.
3290 SelectionDAGBuilder::visitLog10(CallInst &I) {
3292 DebugLoc dl = getCurDebugLoc();
3294 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3295 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3296 SDValue Op = getValue(I.getOperand(1));
3297 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3299 // Scale the exponent by log10(2) [0.30102999f].
3300 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3301 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3302 getF32Constant(DAG, 0x3e9a209a));
3304 // Get the significand and build it into a floating-point number with
3306 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3308 if (LimitFloatPrecision <= 6) {
3309 // For floating-point precision of 6:
3311 // Log10ofMantissa =
3313 // (0.60948995f - 0.10380950f * x) * x;
3315 // error 0.0014886165, which is 6 bits
3316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3317 getF32Constant(DAG, 0xbdd49a13));
3318 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3319 getF32Constant(DAG, 0x3f1c0789));
3320 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3321 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3322 getF32Constant(DAG, 0x3f011300));
3324 result = DAG.getNode(ISD::FADD, dl,
3325 MVT::f32, LogOfExponent, Log10ofMantissa);
3326 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3327 // For floating-point precision of 12:
3329 // Log10ofMantissa =
3332 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3334 // error 0.00019228036, which is better than 12 bits
3335 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3336 getF32Constant(DAG, 0x3d431f31));
3337 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3338 getF32Constant(DAG, 0x3ea21fb2));
3339 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3340 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3341 getF32Constant(DAG, 0x3f6ae232));
3342 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3343 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3344 getF32Constant(DAG, 0x3f25f7c3));
3346 result = DAG.getNode(ISD::FADD, dl,
3347 MVT::f32, LogOfExponent, Log10ofMantissa);
3348 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3349 // For floating-point precision of 18:
3351 // Log10ofMantissa =
3356 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3358 // error 0.0000037995730, which is better than 18 bits
3359 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3360 getF32Constant(DAG, 0x3c5d51ce));
3361 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3362 getF32Constant(DAG, 0x3e00685a));
3363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3364 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3365 getF32Constant(DAG, 0x3efb6798));
3366 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3367 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3368 getF32Constant(DAG, 0x3f88d192));
3369 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3370 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3371 getF32Constant(DAG, 0x3fc4316c));
3372 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3373 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3374 getF32Constant(DAG, 0x3f57ce70));
3376 result = DAG.getNode(ISD::FADD, dl,
3377 MVT::f32, LogOfExponent, Log10ofMantissa);
3380 // No special expansion.
3381 result = DAG.getNode(ISD::FLOG10, dl,
3382 getValue(I.getOperand(1)).getValueType(),
3383 getValue(I.getOperand(1)));
3386 setValue(&I, result);
3389 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3390 /// limited-precision mode.
3392 SelectionDAGBuilder::visitExp2(CallInst &I) {
3394 DebugLoc dl = getCurDebugLoc();
3396 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3397 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3398 SDValue Op = getValue(I.getOperand(1));
3400 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3402 // FractionalPartOfX = x - (float)IntegerPartOfX;
3403 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3404 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3406 // IntegerPartOfX <<= 23;
3407 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3408 DAG.getConstant(23, TLI.getPointerTy()));
3410 if (LimitFloatPrecision <= 6) {
3411 // For floating-point precision of 6:
3413 // TwoToFractionalPartOfX =
3415 // (0.735607626f + 0.252464424f * x) * x;
3417 // error 0.0144103317, which is 6 bits
3418 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3419 getF32Constant(DAG, 0x3e814304));
3420 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3421 getF32Constant(DAG, 0x3f3c50c8));
3422 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3423 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3424 getF32Constant(DAG, 0x3f7f5e7e));
3425 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3426 SDValue TwoToFractionalPartOfX =
3427 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3429 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3430 MVT::f32, TwoToFractionalPartOfX);
3431 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3432 // For floating-point precision of 12:
3434 // TwoToFractionalPartOfX =
3437 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3439 // error 0.000107046256, which is 13 to 14 bits
3440 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3441 getF32Constant(DAG, 0x3da235e3));
3442 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3443 getF32Constant(DAG, 0x3e65b8f3));
3444 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3445 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3446 getF32Constant(DAG, 0x3f324b07));
3447 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3448 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3449 getF32Constant(DAG, 0x3f7ff8fd));
3450 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3451 SDValue TwoToFractionalPartOfX =
3452 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3454 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3455 MVT::f32, TwoToFractionalPartOfX);
3456 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3457 // For floating-point precision of 18:
3459 // TwoToFractionalPartOfX =
3463 // (0.554906021e-1f +
3464 // (0.961591928e-2f +
3465 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3466 // error 2.47208000*10^(-7), which is better than 18 bits
3467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3468 getF32Constant(DAG, 0x3924b03e));
3469 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3470 getF32Constant(DAG, 0x3ab24b87));
3471 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3472 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3473 getF32Constant(DAG, 0x3c1d8c17));
3474 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3475 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3476 getF32Constant(DAG, 0x3d634a1d));
3477 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3478 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3479 getF32Constant(DAG, 0x3e75fe14));
3480 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3481 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3482 getF32Constant(DAG, 0x3f317234));
3483 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3484 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3485 getF32Constant(DAG, 0x3f800000));
3486 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3487 SDValue TwoToFractionalPartOfX =
3488 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3490 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3491 MVT::f32, TwoToFractionalPartOfX);
3494 // No special expansion.
3495 result = DAG.getNode(ISD::FEXP2, dl,
3496 getValue(I.getOperand(1)).getValueType(),
3497 getValue(I.getOperand(1)));
3500 setValue(&I, result);
3503 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3504 /// limited-precision mode with x == 10.0f.
3506 SelectionDAGBuilder::visitPow(CallInst &I) {
3508 Value *Val = I.getOperand(1);
3509 DebugLoc dl = getCurDebugLoc();
3510 bool IsExp10 = false;
3512 if (getValue(Val).getValueType() == MVT::f32 &&
3513 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3514 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3515 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3516 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3518 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3523 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3524 SDValue Op = getValue(I.getOperand(2));
3526 // Put the exponent in the right bit position for later addition to the
3529 // #define LOG2OF10 3.3219281f
3530 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3531 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3532 getF32Constant(DAG, 0x40549a78));
3533 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3535 // FractionalPartOfX = x - (float)IntegerPartOfX;
3536 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3537 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3539 // IntegerPartOfX <<= 23;
3540 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3541 DAG.getConstant(23, TLI.getPointerTy()));
3543 if (LimitFloatPrecision <= 6) {
3544 // For floating-point precision of 6:
3546 // twoToFractionalPartOfX =
3548 // (0.735607626f + 0.252464424f * x) * x;
3550 // error 0.0144103317, which is 6 bits
3551 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3552 getF32Constant(DAG, 0x3e814304));
3553 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3554 getF32Constant(DAG, 0x3f3c50c8));
3555 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3556 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3557 getF32Constant(DAG, 0x3f7f5e7e));
3558 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3559 SDValue TwoToFractionalPartOfX =
3560 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3562 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3563 MVT::f32, TwoToFractionalPartOfX);
3564 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3565 // For floating-point precision of 12:
3567 // TwoToFractionalPartOfX =
3570 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3572 // error 0.000107046256, which is 13 to 14 bits
3573 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3574 getF32Constant(DAG, 0x3da235e3));
3575 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3576 getF32Constant(DAG, 0x3e65b8f3));
3577 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3578 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3579 getF32Constant(DAG, 0x3f324b07));
3580 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3581 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3582 getF32Constant(DAG, 0x3f7ff8fd));
3583 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3584 SDValue TwoToFractionalPartOfX =
3585 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3587 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3588 MVT::f32, TwoToFractionalPartOfX);
3589 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3590 // For floating-point precision of 18:
3592 // TwoToFractionalPartOfX =
3596 // (0.554906021e-1f +
3597 // (0.961591928e-2f +
3598 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3599 // error 2.47208000*10^(-7), which is better than 18 bits
3600 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3601 getF32Constant(DAG, 0x3924b03e));
3602 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3603 getF32Constant(DAG, 0x3ab24b87));
3604 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3605 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3606 getF32Constant(DAG, 0x3c1d8c17));
3607 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3608 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3609 getF32Constant(DAG, 0x3d634a1d));
3610 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3611 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3612 getF32Constant(DAG, 0x3e75fe14));
3613 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3614 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3615 getF32Constant(DAG, 0x3f317234));
3616 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3617 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3618 getF32Constant(DAG, 0x3f800000));
3619 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3620 SDValue TwoToFractionalPartOfX =
3621 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3623 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3624 MVT::f32, TwoToFractionalPartOfX);
3627 // No special expansion.
3628 result = DAG.getNode(ISD::FPOW, dl,
3629 getValue(I.getOperand(1)).getValueType(),
3630 getValue(I.getOperand(1)),
3631 getValue(I.getOperand(2)));
3634 setValue(&I, result);
3638 /// ExpandPowI - Expand a llvm.powi intrinsic.
3639 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3640 SelectionDAG &DAG) {
3641 // If RHS is a constant, we can expand this out to a multiplication tree,
3642 // otherwise we end up lowering to a call to __powidf2 (for example). When
3643 // optimizing for size, we only want to do this if the expansion would produce
3644 // a small number of multiplies, otherwise we do the full expansion.
3645 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3646 // Get the exponent as a positive value.
3647 unsigned Val = RHSC->getSExtValue();
3648 if ((int)Val < 0) Val = -Val;
3650 // powi(x, 0) -> 1.0
3652 return DAG.getConstantFP(1.0, LHS.getValueType());
3654 Function *F = DAG.getMachineFunction().getFunction();
3655 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3656 // If optimizing for size, don't insert too many multiplies. This
3657 // inserts up to 5 multiplies.
3658 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3659 // We use the simple binary decomposition method to generate the multiply
3660 // sequence. There are more optimal ways to do this (for example,
3661 // powi(x,15) generates one more multiply than it should), but this has
3662 // the benefit of being both really simple and much better than a libcall.
3663 SDValue Res; // Logically starts equal to 1.0
3664 SDValue CurSquare = LHS;
3668 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3670 Res = CurSquare; // 1.0*CurSquare.
3673 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3674 CurSquare, CurSquare);
3678 // If the original was negative, invert the result, producing 1/(x*x*x).
3679 if (RHSC->getSExtValue() < 0)
3680 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3681 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3686 // Otherwise, expand to a libcall.
3687 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3691 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3692 /// we want to emit this as a call to a named external function, return the name
3693 /// otherwise lower it and return null.
3695 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3696 DebugLoc dl = getCurDebugLoc();
3699 switch (Intrinsic) {
3701 // By default, turn this into a target intrinsic node.
3702 visitTargetIntrinsic(I, Intrinsic);
3704 case Intrinsic::vastart: visitVAStart(I); return 0;
3705 case Intrinsic::vaend: visitVAEnd(I); return 0;
3706 case Intrinsic::vacopy: visitVACopy(I); return 0;
3707 case Intrinsic::returnaddress:
3708 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3709 getValue(I.getOperand(1))));
3711 case Intrinsic::frameaddress:
3712 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3713 getValue(I.getOperand(1))));
3715 case Intrinsic::setjmp:
3716 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3717 case Intrinsic::longjmp:
3718 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3719 case Intrinsic::memcpy: {
3720 SDValue Op1 = getValue(I.getOperand(1));
3721 SDValue Op2 = getValue(I.getOperand(2));
3722 SDValue Op3 = getValue(I.getOperand(3));
3723 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3724 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3725 I.getOperand(1), 0, I.getOperand(2), 0));
3728 case Intrinsic::memset: {
3729 SDValue Op1 = getValue(I.getOperand(1));
3730 SDValue Op2 = getValue(I.getOperand(2));
3731 SDValue Op3 = getValue(I.getOperand(3));
3732 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3733 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3734 I.getOperand(1), 0));
3737 case Intrinsic::memmove: {
3738 SDValue Op1 = getValue(I.getOperand(1));
3739 SDValue Op2 = getValue(I.getOperand(2));
3740 SDValue Op3 = getValue(I.getOperand(3));
3741 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3743 // If the source and destination are known to not be aliases, we can
3744 // lower memmove as memcpy.
3745 uint64_t Size = -1ULL;
3746 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3747 Size = C->getZExtValue();
3748 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3749 AliasAnalysis::NoAlias) {
3750 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3751 I.getOperand(1), 0, I.getOperand(2), 0));
3755 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3756 I.getOperand(1), 0, I.getOperand(2), 0));
3759 case Intrinsic::dbg_declare: {
3760 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3761 // The real handling of this intrinsic is in FastISel.
3762 if (OptLevel != CodeGenOpt::None)
3763 // FIXME: Variable debug info is not supported here.
3765 DwarfWriter *DW = DAG.getDwarfWriter();
3768 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3769 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3772 MDNode *Variable = DI.getVariable();
3773 Value *Address = DI.getAddress();
3776 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3777 Address = BCI->getOperand(0);
3778 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3779 // Don't handle byval struct arguments or VLAs, for example.
3782 DenseMap<const AllocaInst*, int>::iterator SI =
3783 FuncInfo.StaticAllocaMap.find(AI);
3784 if (SI == FuncInfo.StaticAllocaMap.end())
3786 int FI = SI->second;
3788 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3789 if (MDNode *Dbg = DI.getMetadata("dbg"))
3790 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3793 case Intrinsic::dbg_value: {
3794 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3795 // The real handling of this intrinsic is in FastISel.
3796 if (OptLevel != CodeGenOpt::None)
3797 // FIXME: Variable debug info is not supported here.
3799 DwarfWriter *DW = DAG.getDwarfWriter();
3802 DbgValueInst &DI = cast<DbgValueInst>(I);
3803 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3806 MDNode *Variable = DI.getVariable();
3807 Value *V = DI.getValue();
3810 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3811 V = BCI->getOperand(0);
3812 AllocaInst *AI = dyn_cast<AllocaInst>(V);
3813 // Don't handle byval struct arguments or VLAs, for example.
3816 DenseMap<const AllocaInst*, int>::iterator SI =
3817 FuncInfo.StaticAllocaMap.find(AI);
3818 if (SI == FuncInfo.StaticAllocaMap.end())
3820 int FI = SI->second;
3821 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3822 if (MDNode *Dbg = DI.getMetadata("dbg"))
3823 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3826 case Intrinsic::eh_exception: {
3827 // Insert the EXCEPTIONADDR instruction.
3828 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3829 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3831 Ops[0] = DAG.getRoot();
3832 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3834 DAG.setRoot(Op.getValue(1));
3838 case Intrinsic::eh_selector: {
3839 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3841 if (CurMBB->isLandingPad())
3842 AddCatchInfo(I, MMI, CurMBB);
3845 FuncInfo.CatchInfoLost.insert(&I);
3847 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3848 unsigned Reg = TLI.getExceptionSelectorRegister();
3849 if (Reg) CurMBB->addLiveIn(Reg);
3852 // Insert the EHSELECTION instruction.
3853 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3855 Ops[0] = getValue(I.getOperand(1));
3857 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3858 DAG.setRoot(Op.getValue(1));
3859 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
3863 case Intrinsic::eh_typeid_for: {
3864 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3867 // Find the type id for the given typeinfo.
3868 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3869 unsigned TypeID = MMI->getTypeIDFor(GV);
3870 Res = DAG.getConstant(TypeID, MVT::i32);
3872 // Return something different to eh_selector.
3873 Res = DAG.getConstant(1, MVT::i32);
3880 case Intrinsic::eh_return_i32:
3881 case Intrinsic::eh_return_i64:
3882 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3883 MMI->setCallsEHReturn(true);
3884 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3887 getValue(I.getOperand(1)),
3888 getValue(I.getOperand(2))));
3890 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3894 case Intrinsic::eh_unwind_init:
3895 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3896 MMI->setCallsUnwindInit(true);
3899 case Intrinsic::eh_dwarf_cfa: {
3900 EVT VT = getValue(I.getOperand(1)).getValueType();
3901 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3902 TLI.getPointerTy());
3903 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3905 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
3906 TLI.getPointerTy()),
3908 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
3910 DAG.getConstant(0, TLI.getPointerTy()));
3911 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3915 case Intrinsic::eh_sjlj_callsite: {
3916 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3917 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3918 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3919 assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!");
3921 MMI->setCurrentCallSite(CI->getZExtValue());
3925 case Intrinsic::convertff:
3926 case Intrinsic::convertfsi:
3927 case Intrinsic::convertfui:
3928 case Intrinsic::convertsif:
3929 case Intrinsic::convertuif:
3930 case Intrinsic::convertss:
3931 case Intrinsic::convertsu:
3932 case Intrinsic::convertus:
3933 case Intrinsic::convertuu: {
3934 ISD::CvtCode Code = ISD::CVT_INVALID;
3935 switch (Intrinsic) {
3936 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3937 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3938 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3939 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3940 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3941 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3942 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3943 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3944 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3946 EVT DestVT = TLI.getValueType(I.getType());
3947 Value *Op1 = I.getOperand(1);
3948 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3949 DAG.getValueType(DestVT),
3950 DAG.getValueType(getValue(Op1).getValueType()),
3951 getValue(I.getOperand(2)),
3952 getValue(I.getOperand(3)),
3957 case Intrinsic::sqrt:
3958 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3959 getValue(I.getOperand(1)).getValueType(),
3960 getValue(I.getOperand(1))));
3962 case Intrinsic::powi:
3963 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3964 getValue(I.getOperand(2)), DAG));
3966 case Intrinsic::sin:
3967 setValue(&I, DAG.getNode(ISD::FSIN, dl,
3968 getValue(I.getOperand(1)).getValueType(),
3969 getValue(I.getOperand(1))));
3971 case Intrinsic::cos:
3972 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3973 getValue(I.getOperand(1)).getValueType(),
3974 getValue(I.getOperand(1))));
3976 case Intrinsic::log:
3979 case Intrinsic::log2:
3982 case Intrinsic::log10:
3985 case Intrinsic::exp:
3988 case Intrinsic::exp2:
3991 case Intrinsic::pow:
3994 case Intrinsic::pcmarker: {
3995 SDValue Tmp = getValue(I.getOperand(1));
3996 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
3999 case Intrinsic::readcyclecounter: {
4000 SDValue Op = getRoot();
4001 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4002 DAG.getVTList(MVT::i64, MVT::Other),
4005 DAG.setRoot(Res.getValue(1));
4008 case Intrinsic::bswap:
4009 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4010 getValue(I.getOperand(1)).getValueType(),
4011 getValue(I.getOperand(1))));
4013 case Intrinsic::cttz: {
4014 SDValue Arg = getValue(I.getOperand(1));
4015 EVT Ty = Arg.getValueType();
4016 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4019 case Intrinsic::ctlz: {
4020 SDValue Arg = getValue(I.getOperand(1));
4021 EVT Ty = Arg.getValueType();
4022 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4025 case Intrinsic::ctpop: {
4026 SDValue Arg = getValue(I.getOperand(1));
4027 EVT Ty = Arg.getValueType();
4028 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4031 case Intrinsic::stacksave: {
4032 SDValue Op = getRoot();
4033 Res = DAG.getNode(ISD::STACKSAVE, dl,
4034 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4036 DAG.setRoot(Res.getValue(1));
4039 case Intrinsic::stackrestore: {
4040 Res = getValue(I.getOperand(1));
4041 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4044 case Intrinsic::stackprotector: {
4045 // Emit code into the DAG to store the stack guard onto the stack.
4046 MachineFunction &MF = DAG.getMachineFunction();
4047 MachineFrameInfo *MFI = MF.getFrameInfo();
4048 EVT PtrTy = TLI.getPointerTy();
4050 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4051 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4053 int FI = FuncInfo.StaticAllocaMap[Slot];
4054 MFI->setStackProtectorIndex(FI);
4056 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4058 // Store the stack protector onto the stack.
4059 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4060 PseudoSourceValue::getFixedStack(FI),
4066 case Intrinsic::objectsize: {
4067 // If we don't know by now, we're never going to know.
4068 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4070 assert(CI && "Non-constant type in __builtin_object_size?");
4072 SDValue Arg = getValue(I.getOperand(0));
4073 EVT Ty = Arg.getValueType();
4075 if (CI->getZExtValue() == 0)
4076 Res = DAG.getConstant(-1ULL, Ty);
4078 Res = DAG.getConstant(0, Ty);
4083 case Intrinsic::var_annotation:
4084 // Discard annotate attributes
4087 case Intrinsic::init_trampoline: {
4088 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4092 Ops[1] = getValue(I.getOperand(1));
4093 Ops[2] = getValue(I.getOperand(2));
4094 Ops[3] = getValue(I.getOperand(3));
4095 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4096 Ops[5] = DAG.getSrcValue(F);
4098 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4099 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4103 DAG.setRoot(Res.getValue(1));
4106 case Intrinsic::gcroot:
4108 Value *Alloca = I.getOperand(1);
4109 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4111 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4112 GFI->addStackRoot(FI->getIndex(), TypeMap);
4115 case Intrinsic::gcread:
4116 case Intrinsic::gcwrite:
4117 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4119 case Intrinsic::flt_rounds:
4120 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4122 case Intrinsic::trap:
4123 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4125 case Intrinsic::uadd_with_overflow:
4126 return implVisitAluOverflow(I, ISD::UADDO);
4127 case Intrinsic::sadd_with_overflow:
4128 return implVisitAluOverflow(I, ISD::SADDO);
4129 case Intrinsic::usub_with_overflow:
4130 return implVisitAluOverflow(I, ISD::USUBO);
4131 case Intrinsic::ssub_with_overflow:
4132 return implVisitAluOverflow(I, ISD::SSUBO);
4133 case Intrinsic::umul_with_overflow:
4134 return implVisitAluOverflow(I, ISD::UMULO);
4135 case Intrinsic::smul_with_overflow:
4136 return implVisitAluOverflow(I, ISD::SMULO);
4138 case Intrinsic::prefetch: {
4141 Ops[1] = getValue(I.getOperand(1));
4142 Ops[2] = getValue(I.getOperand(2));
4143 Ops[3] = getValue(I.getOperand(3));
4144 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4148 case Intrinsic::memory_barrier: {
4151 for (int x = 1; x < 6; ++x)
4152 Ops[x] = getValue(I.getOperand(x));
4154 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4157 case Intrinsic::atomic_cmp_swap: {
4158 SDValue Root = getRoot();
4160 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4161 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4163 getValue(I.getOperand(1)),
4164 getValue(I.getOperand(2)),
4165 getValue(I.getOperand(3)),
4168 DAG.setRoot(L.getValue(1));
4171 case Intrinsic::atomic_load_add:
4172 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4173 case Intrinsic::atomic_load_sub:
4174 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4175 case Intrinsic::atomic_load_or:
4176 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4177 case Intrinsic::atomic_load_xor:
4178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4179 case Intrinsic::atomic_load_and:
4180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4181 case Intrinsic::atomic_load_nand:
4182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4183 case Intrinsic::atomic_load_max:
4184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4185 case Intrinsic::atomic_load_min:
4186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4187 case Intrinsic::atomic_load_umin:
4188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4189 case Intrinsic::atomic_load_umax:
4190 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4191 case Intrinsic::atomic_swap:
4192 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4194 case Intrinsic::invariant_start:
4195 case Intrinsic::lifetime_start:
4196 // Discard region information.
4197 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4199 case Intrinsic::invariant_end:
4200 case Intrinsic::lifetime_end:
4201 // Discard region information.
4206 /// Test if the given instruction is in a position to be optimized
4207 /// with a tail-call. This roughly means that it's in a block with
4208 /// a return and there's nothing that needs to be scheduled
4209 /// between it and the return.
4211 /// This function only tests target-independent requirements.
4213 isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
4214 const TargetLowering &TLI) {
4215 const Instruction *I = CS.getInstruction();
4216 const BasicBlock *ExitBB = I->getParent();
4217 const TerminatorInst *Term = ExitBB->getTerminator();
4218 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4219 const Function *F = ExitBB->getParent();
4221 // The block must end in a return statement or unreachable.
4223 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4224 // an unreachable, for now. The way tailcall optimization is currently
4225 // implemented means it will add an epilogue followed by a jump. That is
4226 // not profitable. Also, if the callee is a special function (e.g.
4227 // longjmp on x86), it can end up causing miscompilation that has not
4228 // been fully understood.
4230 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
4232 // If I will have a chain, make sure no other instruction that will have a
4233 // chain interposes between I and the return.
4234 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4235 !I->isSafeToSpeculativelyExecute())
4236 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4240 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4241 !BBI->isSafeToSpeculativelyExecute())
4245 // If the block ends with a void return or unreachable, it doesn't matter
4246 // what the call's return type is.
4247 if (!Ret || Ret->getNumOperands() == 0) return true;
4249 // If the return value is undef, it doesn't matter what the call's
4251 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4253 // Conservatively require the attributes of the call to match those of
4254 // the return. Ignore noalias because it doesn't affect the call sequence.
4255 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4256 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4259 // It's not safe to eliminate the sign / zero extension of the return value.
4260 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4263 // Otherwise, make sure the unmodified return value of I is the return value.
4264 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4265 U = dyn_cast<Instruction>(U->getOperand(0))) {
4268 if (!U->hasOneUse())
4272 // Check for a truly no-op truncate.
4273 if (isa<TruncInst>(U) &&
4274 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4276 // Check for a truly no-op bitcast.
4277 if (isa<BitCastInst>(U) &&
4278 (U->getOperand(0)->getType() == U->getType() ||
4279 (isa<PointerType>(U->getOperand(0)->getType()) &&
4280 isa<PointerType>(U->getType()))))
4282 // Otherwise it's not a true no-op.
4289 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4291 MachineBasicBlock *LandingPad) {
4292 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4293 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4294 const Type *RetTy = FTy->getReturnType();
4295 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4296 unsigned BeginLabel = 0, EndLabel = 0;
4298 TargetLowering::ArgListTy Args;
4299 TargetLowering::ArgListEntry Entry;
4300 Args.reserve(CS.arg_size());
4302 // Check whether the function can return without sret-demotion.
4303 SmallVector<EVT, 4> OutVTs;
4304 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4305 SmallVector<uint64_t, 4> Offsets;
4306 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4307 OutVTs, OutsFlags, TLI, &Offsets);
4309 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4310 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4312 SDValue DemoteStackSlot;
4314 if (!CanLowerReturn) {
4315 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4316 FTy->getReturnType());
4317 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4318 FTy->getReturnType());
4319 MachineFunction &MF = DAG.getMachineFunction();
4320 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4321 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4323 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4324 Entry.Node = DemoteStackSlot;
4325 Entry.Ty = StackSlotPtrType;
4326 Entry.isSExt = false;
4327 Entry.isZExt = false;
4328 Entry.isInReg = false;
4329 Entry.isSRet = true;
4330 Entry.isNest = false;
4331 Entry.isByVal = false;
4332 Entry.Alignment = Align;
4333 Args.push_back(Entry);
4334 RetTy = Type::getVoidTy(FTy->getContext());
4337 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4339 SDValue ArgNode = getValue(*i);
4340 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4342 unsigned attrInd = i - CS.arg_begin() + 1;
4343 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4344 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4345 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4346 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4347 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4348 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4349 Entry.Alignment = CS.getParamAlignment(attrInd);
4350 Args.push_back(Entry);
4353 if (LandingPad && MMI) {
4354 // Insert a label before the invoke call to mark the try range. This can be
4355 // used to detect deletion of the invoke via the MachineModuleInfo.
4356 BeginLabel = MMI->NextLabelID();
4358 // For SjLj, keep track of which landing pads go with which invokes
4359 // so as to maintain the ordering of pads in the LSDA.
4360 unsigned CallSiteIndex = MMI->getCurrentCallSite();
4361 if (CallSiteIndex) {
4362 MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4363 // Now that the call site is handled, stop tracking it.
4364 MMI->setCurrentCallSite(0);
4367 // Both PendingLoads and PendingExports must be flushed here;
4368 // this call might not return.
4370 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4371 getControlRoot(), BeginLabel));
4374 // Check if target-independent constraints permit a tail call here.
4375 // Target-dependent constraints are checked within TLI.LowerCallTo.
4377 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4380 std::pair<SDValue,SDValue> Result =
4381 TLI.LowerCallTo(getRoot(), RetTy,
4382 CS.paramHasAttr(0, Attribute::SExt),
4383 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4384 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4385 CS.getCallingConv(),
4387 !CS.getInstruction()->use_empty(),
4388 Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder);
4389 assert((isTailCall || Result.second.getNode()) &&
4390 "Non-null chain expected with non-tail call!");
4391 assert((Result.second.getNode() || !Result.first.getNode()) &&
4392 "Null value expected with tail call!");
4393 if (Result.first.getNode()) {
4394 setValue(CS.getInstruction(), Result.first);
4395 } else if (!CanLowerReturn && Result.second.getNode()) {
4396 // The instruction result is the result of loading from the
4397 // hidden sret parameter.
4398 SmallVector<EVT, 1> PVTs;
4399 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4401 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4402 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4403 EVT PtrVT = PVTs[0];
4404 unsigned NumValues = OutVTs.size();
4405 SmallVector<SDValue, 4> Values(NumValues);
4406 SmallVector<SDValue, 4> Chains(NumValues);
4408 for (unsigned i = 0; i < NumValues; ++i) {
4409 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4411 DAG.getConstant(Offsets[i], PtrVT));
4412 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4413 Add, NULL, Offsets[i], false, 1);
4415 Chains[i] = L.getValue(1);
4418 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4419 MVT::Other, &Chains[0], NumValues);
4420 PendingLoads.push_back(Chain);
4422 // Collect the legal value parts into potentially illegal values
4423 // that correspond to the original function's return values.
4424 SmallVector<EVT, 4> RetTys;
4425 RetTy = FTy->getReturnType();
4426 ComputeValueVTs(TLI, RetTy, RetTys);
4427 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4428 SmallVector<SDValue, 4> ReturnValues;
4429 unsigned CurReg = 0;
4430 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4432 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4433 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4435 SDValue ReturnValue =
4436 getCopyFromParts(DAG, getCurDebugLoc(), SDNodeOrder, &Values[CurReg], NumRegs,
4437 RegisterVT, VT, AssertOp);
4438 ReturnValues.push_back(ReturnValue);
4442 setValue(CS.getInstruction(),
4443 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4444 DAG.getVTList(&RetTys[0], RetTys.size()),
4445 &ReturnValues[0], ReturnValues.size()));
4449 // As a special case, a null chain means that a tail call has been emitted and
4450 // the DAG root is already updated.
4451 if (Result.second.getNode())
4452 DAG.setRoot(Result.second);
4456 if (LandingPad && MMI) {
4457 // Insert a label at the end of the invoke call to mark the try range. This
4458 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4459 EndLabel = MMI->NextLabelID();
4460 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4461 getRoot(), EndLabel));
4463 // Inform MachineModuleInfo of range.
4464 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4468 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4469 /// value is equal or not-equal to zero.
4470 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
4471 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
4473 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4474 if (IC->isEquality())
4475 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4476 if (C->isNullValue())
4478 // Unknown instruction.
4484 static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
4485 SelectionDAGBuilder &Builder) {
4487 // Check to see if this load can be trivially constant folded, e.g. if the
4488 // input is from a string literal.
4489 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4490 // Cast pointer to the type we really want to load.
4491 LoadInput = ConstantExpr::getBitCast(LoadInput,
4492 PointerType::getUnqual(LoadTy));
4494 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
4495 return Builder.getValue(LoadCst);
4498 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4499 // still constant memory, the input chain can be the entry node.
4501 bool ConstantMemory = false;
4503 // Do not serialize (non-volatile) loads of constant memory with anything.
4504 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4505 Root = Builder.DAG.getEntryNode();
4506 ConstantMemory = true;
4508 // Do not serialize non-volatile loads against each other.
4509 Root = Builder.DAG.getRoot();
4512 SDValue Ptr = Builder.getValue(PtrVal);
4513 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4514 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4515 false /*volatile*/, 1 /* align=1 */);
4517 if (!ConstantMemory)
4518 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4523 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4524 /// If so, return true and lower it, otherwise return false and it will be
4525 /// lowered like a normal call.
4526 bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
4527 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4528 if (I.getNumOperands() != 4)
4531 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
4532 if (!isa<PointerType>(LHS->getType()) || !isa<PointerType>(RHS->getType()) ||
4533 !isa<IntegerType>(I.getOperand(3)->getType()) ||
4534 !isa<IntegerType>(I.getType()))
4537 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
4539 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4540 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
4541 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4542 bool ActuallyDoIt = true;
4545 switch (Size->getZExtValue()) {
4547 LoadVT = MVT::Other;
4549 ActuallyDoIt = false;
4553 LoadTy = Type::getInt16Ty(Size->getContext());
4557 LoadTy = Type::getInt32Ty(Size->getContext());
4561 LoadTy = Type::getInt64Ty(Size->getContext());
4565 LoadVT = MVT::v4i32;
4566 LoadTy = Type::getInt32Ty(Size->getContext());
4567 LoadTy = VectorType::get(LoadTy, 4);
4572 // This turns into unaligned loads. We only do this if the target natively
4573 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4574 // we'll only produce a small number of byte loads.
4576 // Require that we can find a legal MVT, and only do this if the target
4577 // supports unaligned loads of that type. Expanding into byte loads would
4579 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4580 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4581 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4582 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4583 ActuallyDoIt = false;
4587 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4588 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
4590 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4592 EVT CallVT = TLI.getValueType(I.getType(), true);
4593 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4603 void SelectionDAGBuilder::visitCall(CallInst &I) {
4604 const char *RenameFn = 0;
4605 if (Function *F = I.getCalledFunction()) {
4606 if (F->isDeclaration()) {
4607 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4609 if (unsigned IID = II->getIntrinsicID(F)) {
4610 RenameFn = visitIntrinsicCall(I, IID);
4615 if (unsigned IID = F->getIntrinsicID()) {
4616 RenameFn = visitIntrinsicCall(I, IID);
4622 // Check for well-known libc/libm calls. If the function is internal, it
4623 // can't be a library call.
4624 if (!F->hasLocalLinkage() && F->hasName()) {
4625 StringRef Name = F->getName();
4626 if (Name == "copysign" || Name == "copysignf") {
4627 if (I.getNumOperands() == 3 && // Basic sanity checks.
4628 I.getOperand(1)->getType()->isFloatingPoint() &&
4629 I.getType() == I.getOperand(1)->getType() &&
4630 I.getType() == I.getOperand(2)->getType()) {
4631 SDValue LHS = getValue(I.getOperand(1));
4632 SDValue RHS = getValue(I.getOperand(2));
4633 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4634 LHS.getValueType(), LHS, RHS));
4637 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4638 if (I.getNumOperands() == 2 && // Basic sanity checks.
4639 I.getOperand(1)->getType()->isFloatingPoint() &&
4640 I.getType() == I.getOperand(1)->getType()) {
4641 SDValue Tmp = getValue(I.getOperand(1));
4642 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4643 Tmp.getValueType(), Tmp));
4646 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4647 if (I.getNumOperands() == 2 && // Basic sanity checks.
4648 I.getOperand(1)->getType()->isFloatingPoint() &&
4649 I.getType() == I.getOperand(1)->getType() &&
4650 I.onlyReadsMemory()) {
4651 SDValue Tmp = getValue(I.getOperand(1));
4652 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4653 Tmp.getValueType(), Tmp));
4656 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4657 if (I.getNumOperands() == 2 && // Basic sanity checks.
4658 I.getOperand(1)->getType()->isFloatingPoint() &&
4659 I.getType() == I.getOperand(1)->getType() &&
4660 I.onlyReadsMemory()) {
4661 SDValue Tmp = getValue(I.getOperand(1));
4662 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4663 Tmp.getValueType(), Tmp));
4666 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4667 if (I.getNumOperands() == 2 && // Basic sanity checks.
4668 I.getOperand(1)->getType()->isFloatingPoint() &&
4669 I.getType() == I.getOperand(1)->getType() &&
4670 I.onlyReadsMemory()) {
4671 SDValue Tmp = getValue(I.getOperand(1));
4672 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4673 Tmp.getValueType(), Tmp));
4676 } else if (Name == "memcmp") {
4677 if (visitMemCmpCall(I))
4681 } else if (isa<InlineAsm>(I.getOperand(0))) {
4688 Callee = getValue(I.getOperand(0));
4690 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4692 // Check if we can potentially perform a tail call. More detailed checking is
4693 // be done within LowerCallTo, after more information about the call is known.
4694 LowerCallTo(&I, Callee, I.isTailCall());
4697 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4698 /// this value and returns the result as a ValueVT value. This uses
4699 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4700 /// If the Flag pointer is NULL, no flag is used.
4701 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4702 unsigned Order, SDValue &Chain,
4703 SDValue *Flag) const {
4704 // Assemble the legal parts into the final values.
4705 SmallVector<SDValue, 4> Values(ValueVTs.size());
4706 SmallVector<SDValue, 8> Parts;
4707 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4708 // Copy the legal parts from the registers.
4709 EVT ValueVT = ValueVTs[Value];
4710 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4711 EVT RegisterVT = RegVTs[Value];
4713 Parts.resize(NumRegs);
4714 for (unsigned i = 0; i != NumRegs; ++i) {
4717 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4719 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4720 *Flag = P.getValue(2);
4723 Chain = P.getValue(1);
4725 // If the source register was virtual and if we know something about it,
4726 // add an assert node.
4727 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4728 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4729 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4730 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4731 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4732 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4734 unsigned RegSize = RegisterVT.getSizeInBits();
4735 unsigned NumSignBits = LOI.NumSignBits;
4736 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4738 // FIXME: We capture more information than the dag can represent. For
4739 // now, just use the tightest assertzext/assertsext possible.
4741 EVT FromVT(MVT::Other);
4742 if (NumSignBits == RegSize)
4743 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4744 else if (NumZeroBits >= RegSize-1)
4745 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4746 else if (NumSignBits > RegSize-8)
4747 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4748 else if (NumZeroBits >= RegSize-8)
4749 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4750 else if (NumSignBits > RegSize-16)
4751 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4752 else if (NumZeroBits >= RegSize-16)
4753 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4754 else if (NumSignBits > RegSize-32)
4755 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4756 else if (NumZeroBits >= RegSize-32)
4757 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4759 if (FromVT != MVT::Other)
4760 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4761 RegisterVT, P, DAG.getValueType(FromVT));
4768 Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(),
4769 NumRegs, RegisterVT, ValueVT);
4774 return DAG.getNode(ISD::MERGE_VALUES, dl,
4775 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4776 &Values[0], ValueVTs.size());
4779 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4780 /// specified value into the registers specified by this object. This uses
4781 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4782 /// If the Flag pointer is NULL, no flag is used.
4783 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4784 unsigned Order, SDValue &Chain,
4785 SDValue *Flag) const {
4786 // Get the list of the values's legal parts.
4787 unsigned NumRegs = Regs.size();
4788 SmallVector<SDValue, 8> Parts(NumRegs);
4789 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4790 EVT ValueVT = ValueVTs[Value];
4791 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4792 EVT RegisterVT = RegVTs[Value];
4794 getCopyToParts(DAG, dl, Order,
4795 Val.getValue(Val.getResNo() + Value),
4796 &Parts[Part], NumParts, RegisterVT);
4800 // Copy the parts into the registers.
4801 SmallVector<SDValue, 8> Chains(NumRegs);
4802 for (unsigned i = 0; i != NumRegs; ++i) {
4805 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4807 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4808 *Flag = Part.getValue(1);
4811 Chains[i] = Part.getValue(0);
4814 if (NumRegs == 1 || Flag)
4815 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4816 // flagged to it. That is the CopyToReg nodes and the user are considered
4817 // a single scheduling unit. If we create a TokenFactor and return it as
4818 // chain, then the TokenFactor is both a predecessor (operand) of the
4819 // user as well as a successor (the TF operands are flagged to the user).
4820 // c1, f1 = CopyToReg
4821 // c2, f2 = CopyToReg
4822 // c3 = TokenFactor c1, c2
4825 Chain = Chains[NumRegs-1];
4827 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4830 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4831 /// operand list. This adds the code marker and includes the number of
4832 /// values added into it.
4833 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4834 bool HasMatching,unsigned MatchingIdx,
4835 SelectionDAG &DAG, unsigned Order,
4836 std::vector<SDValue> &Ops) const {
4837 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4838 unsigned Flag = Code | (Regs.size() << 3);
4840 Flag |= 0x80000000 | (MatchingIdx << 16);
4841 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
4844 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4845 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4846 EVT RegisterVT = RegVTs[Value];
4847 for (unsigned i = 0; i != NumRegs; ++i) {
4848 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4849 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4854 /// isAllocatableRegister - If the specified register is safe to allocate,
4855 /// i.e. it isn't a stack pointer or some other special register, return the
4856 /// register class for the register. Otherwise, return null.
4857 static const TargetRegisterClass *
4858 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4859 const TargetLowering &TLI,
4860 const TargetRegisterInfo *TRI) {
4861 EVT FoundVT = MVT::Other;
4862 const TargetRegisterClass *FoundRC = 0;
4863 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4864 E = TRI->regclass_end(); RCI != E; ++RCI) {
4865 EVT ThisVT = MVT::Other;
4867 const TargetRegisterClass *RC = *RCI;
4868 // If none of the the value types for this register class are valid, we
4869 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4870 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4872 if (TLI.isTypeLegal(*I)) {
4873 // If we have already found this register in a different register class,
4874 // choose the one with the largest VT specified. For example, on
4875 // PowerPC, we favor f64 register classes over f32.
4876 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4883 if (ThisVT == MVT::Other) continue;
4885 // NOTE: This isn't ideal. In particular, this might allocate the
4886 // frame pointer in functions that need it (due to them not being taken
4887 // out of allocation, because a variable sized allocation hasn't been seen
4888 // yet). This is a slight code pessimization, but should still work.
4889 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4890 E = RC->allocation_order_end(MF); I != E; ++I)
4892 // We found a matching register class. Keep looking at others in case
4893 // we find one with larger registers that this physreg is also in.
4904 /// AsmOperandInfo - This contains information for each constraint that we are
4906 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4907 public TargetLowering::AsmOperandInfo {
4909 /// CallOperand - If this is the result output operand or a clobber
4910 /// this is null, otherwise it is the incoming operand to the CallInst.
4911 /// This gets modified as the asm is processed.
4912 SDValue CallOperand;
4914 /// AssignedRegs - If this is a register or register class operand, this
4915 /// contains the set of register corresponding to the operand.
4916 RegsForValue AssignedRegs;
4918 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4919 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4922 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4923 /// busy in OutputRegs/InputRegs.
4924 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4925 std::set<unsigned> &OutputRegs,
4926 std::set<unsigned> &InputRegs,
4927 const TargetRegisterInfo &TRI) const {
4929 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4930 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4933 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4934 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4938 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4939 /// corresponds to. If there is no Value* for this operand, it returns
4941 EVT getCallOperandValEVT(LLVMContext &Context,
4942 const TargetLowering &TLI,
4943 const TargetData *TD) const {
4944 if (CallOperandVal == 0) return MVT::Other;
4946 if (isa<BasicBlock>(CallOperandVal))
4947 return TLI.getPointerTy();
4949 const llvm::Type *OpTy = CallOperandVal->getType();
4951 // If this is an indirect operand, the operand is a pointer to the
4954 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4956 llvm_report_error("Indirect operand for inline asm not a pointer!");
4957 OpTy = PtrTy->getElementType();
4960 // If OpTy is not a single value, it may be a struct/union that we
4961 // can tile with integers.
4962 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4963 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4972 OpTy = IntegerType::get(Context, BitSize);
4977 return TLI.getValueType(OpTy, true);
4981 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4983 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4984 const TargetRegisterInfo &TRI) {
4985 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4987 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4988 for (; *Aliases; ++Aliases)
4989 Regs.insert(*Aliases);
4992 } // end llvm namespace.
4995 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4996 /// specified operand. We prefer to assign virtual registers, to allow the
4997 /// register allocator to handle the assignment process. However, if the asm
4998 /// uses features that we can't model on machineinstrs, we have SDISel do the
4999 /// allocation. This produces generally horrible, but correct, code.
5001 /// OpInfo describes the operand.
5002 /// Input and OutputRegs are the set of already allocated physical registers.
5004 void SelectionDAGBuilder::
5005 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5006 std::set<unsigned> &OutputRegs,
5007 std::set<unsigned> &InputRegs) {
5008 LLVMContext &Context = FuncInfo.Fn->getContext();
5010 // Compute whether this value requires an input register, an output register,
5012 bool isOutReg = false;
5013 bool isInReg = false;
5014 switch (OpInfo.Type) {
5015 case InlineAsm::isOutput:
5018 // If there is an input constraint that matches this, we need to reserve
5019 // the input register so no other inputs allocate to it.
5020 isInReg = OpInfo.hasMatchingInput();
5022 case InlineAsm::isInput:
5026 case InlineAsm::isClobber:
5033 MachineFunction &MF = DAG.getMachineFunction();
5034 SmallVector<unsigned, 4> Regs;
5036 // If this is a constraint for a single physreg, or a constraint for a
5037 // register class, find it.
5038 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5039 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5040 OpInfo.ConstraintVT);
5042 unsigned NumRegs = 1;
5043 if (OpInfo.ConstraintVT != MVT::Other) {
5044 // If this is a FP input in an integer register (or visa versa) insert a bit
5045 // cast of the input value. More generally, handle any case where the input
5046 // value disagrees with the register class we plan to stick this in.
5047 if (OpInfo.Type == InlineAsm::isInput &&
5048 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5049 // Try to convert to the first EVT that the reg class contains. If the
5050 // types are identical size, use a bitcast to convert (e.g. two differing
5052 EVT RegVT = *PhysReg.second->vt_begin();
5053 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5054 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5055 RegVT, OpInfo.CallOperand);
5056 OpInfo.ConstraintVT = RegVT;
5057 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5058 // If the input is a FP value and we want it in FP registers, do a
5059 // bitcast to the corresponding integer type. This turns an f64 value
5060 // into i64, which can be passed with two i32 values on a 32-bit
5062 RegVT = EVT::getIntegerVT(Context,
5063 OpInfo.ConstraintVT.getSizeInBits());
5064 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5065 RegVT, OpInfo.CallOperand);
5066 OpInfo.ConstraintVT = RegVT;
5070 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5074 EVT ValueVT = OpInfo.ConstraintVT;
5076 // If this is a constraint for a specific physical register, like {r17},
5078 if (unsigned AssignedReg = PhysReg.first) {
5079 const TargetRegisterClass *RC = PhysReg.second;
5080 if (OpInfo.ConstraintVT == MVT::Other)
5081 ValueVT = *RC->vt_begin();
5083 // Get the actual register value type. This is important, because the user
5084 // may have asked for (e.g.) the AX register in i32 type. We need to
5085 // remember that AX is actually i16 to get the right extension.
5086 RegVT = *RC->vt_begin();
5088 // This is a explicit reference to a physical register.
5089 Regs.push_back(AssignedReg);
5091 // If this is an expanded reference, add the rest of the regs to Regs.
5093 TargetRegisterClass::iterator I = RC->begin();
5094 for (; *I != AssignedReg; ++I)
5095 assert(I != RC->end() && "Didn't find reg!");
5097 // Already added the first reg.
5099 for (; NumRegs; --NumRegs, ++I) {
5100 assert(I != RC->end() && "Ran out of registers to allocate!");
5105 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5106 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5107 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5111 // Otherwise, if this was a reference to an LLVM register class, create vregs
5112 // for this reference.
5113 if (const TargetRegisterClass *RC = PhysReg.second) {
5114 RegVT = *RC->vt_begin();
5115 if (OpInfo.ConstraintVT == MVT::Other)
5118 // Create the appropriate number of virtual registers.
5119 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5120 for (; NumRegs; --NumRegs)
5121 Regs.push_back(RegInfo.createVirtualRegister(RC));
5123 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5127 // This is a reference to a register class that doesn't directly correspond
5128 // to an LLVM register class. Allocate NumRegs consecutive, available,
5129 // registers from the class.
5130 std::vector<unsigned> RegClassRegs
5131 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5132 OpInfo.ConstraintVT);
5134 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5135 unsigned NumAllocated = 0;
5136 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5137 unsigned Reg = RegClassRegs[i];
5138 // See if this register is available.
5139 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5140 (isInReg && InputRegs.count(Reg))) { // Already used.
5141 // Make sure we find consecutive registers.
5146 // Check to see if this register is allocatable (i.e. don't give out the
5148 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5149 if (!RC) { // Couldn't allocate this register.
5150 // Reset NumAllocated to make sure we return consecutive registers.
5155 // Okay, this register is good, we can use it.
5158 // If we allocated enough consecutive registers, succeed.
5159 if (NumAllocated == NumRegs) {
5160 unsigned RegStart = (i-NumAllocated)+1;
5161 unsigned RegEnd = i+1;
5162 // Mark all of the allocated registers used.
5163 for (unsigned i = RegStart; i != RegEnd; ++i)
5164 Regs.push_back(RegClassRegs[i]);
5166 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5167 OpInfo.ConstraintVT);
5168 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5173 // Otherwise, we couldn't allocate enough registers for this.
5176 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5177 /// processed uses a memory 'm' constraint.
5179 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5180 const TargetLowering &TLI) {
5181 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5182 InlineAsm::ConstraintInfo &CI = CInfos[i];
5183 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5184 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5185 if (CType == TargetLowering::C_Memory)
5189 // Indirect operand accesses access memory.
5197 /// visitInlineAsm - Handle a call to an InlineAsm object.
5199 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
5200 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5202 /// ConstraintOperands - Information about all of the constraints.
5203 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5205 std::set<unsigned> OutputRegs, InputRegs;
5207 // Do a prepass over the constraints, canonicalizing them, and building up the
5208 // ConstraintOperands list.
5209 std::vector<InlineAsm::ConstraintInfo>
5210 ConstraintInfos = IA->ParseConstraints();
5212 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5214 SDValue Chain, Flag;
5216 // We won't need to flush pending loads if this asm doesn't touch
5217 // memory and is nonvolatile.
5218 if (hasMemory || IA->hasSideEffects())
5221 Chain = DAG.getRoot();
5223 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5224 unsigned ResNo = 0; // ResNo - The result number of the next output.
5225 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5226 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5227 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5229 EVT OpVT = MVT::Other;
5231 // Compute the value type for each operand.
5232 switch (OpInfo.Type) {
5233 case InlineAsm::isOutput:
5234 // Indirect outputs just consume an argument.
5235 if (OpInfo.isIndirect) {
5236 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5240 // The return value of the call is this value. As such, there is no
5241 // corresponding argument.
5242 assert(!CS.getType()->isVoidTy() &&
5244 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5245 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5247 assert(ResNo == 0 && "Asm only has one result!");
5248 OpVT = TLI.getValueType(CS.getType());
5252 case InlineAsm::isInput:
5253 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5255 case InlineAsm::isClobber:
5260 // If this is an input or an indirect output, process the call argument.
5261 // BasicBlocks are labels, currently appearing only in asm's.
5262 if (OpInfo.CallOperandVal) {
5263 // Strip bitcasts, if any. This mostly comes up for functions.
5264 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5266 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5267 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5269 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5272 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5275 OpInfo.ConstraintVT = OpVT;
5278 // Second pass over the constraints: compute which constraint option to use
5279 // and assign registers to constraints that want a specific physreg.
5280 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5281 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5283 // If this is an output operand with a matching input operand, look up the
5284 // matching input. If their types mismatch, e.g. one is an integer, the
5285 // other is floating point, or their sizes are different, flag it as an
5287 if (OpInfo.hasMatchingInput()) {
5288 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5289 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5290 if ((OpInfo.ConstraintVT.isInteger() !=
5291 Input.ConstraintVT.isInteger()) ||
5292 (OpInfo.ConstraintVT.getSizeInBits() !=
5293 Input.ConstraintVT.getSizeInBits())) {
5294 llvm_report_error("Unsupported asm: input constraint"
5295 " with a matching output constraint of incompatible"
5298 Input.ConstraintVT = OpInfo.ConstraintVT;
5302 // Compute the constraint code and ConstraintType to use.
5303 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5305 // If this is a memory input, and if the operand is not indirect, do what we
5306 // need to to provide an address for the memory input.
5307 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5308 !OpInfo.isIndirect) {
5309 assert(OpInfo.Type == InlineAsm::isInput &&
5310 "Can only indirectify direct input operands!");
5312 // Memory operands really want the address of the value. If we don't have
5313 // an indirect input, put it in the constpool if we can, otherwise spill
5314 // it to a stack slot.
5316 // If the operand is a float, integer, or vector constant, spill to a
5317 // constant pool entry to get its address.
5318 Value *OpVal = OpInfo.CallOperandVal;
5319 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5320 isa<ConstantVector>(OpVal)) {
5321 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5322 TLI.getPointerTy());
5324 // Otherwise, create a stack slot and emit a store to it before the
5326 const Type *Ty = OpVal->getType();
5327 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5328 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5329 MachineFunction &MF = DAG.getMachineFunction();
5330 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5331 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5332 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5333 OpInfo.CallOperand, StackSlot, NULL, 0);
5334 OpInfo.CallOperand = StackSlot;
5337 // There is no longer a Value* corresponding to this operand.
5338 OpInfo.CallOperandVal = 0;
5340 // It is now an indirect operand.
5341 OpInfo.isIndirect = true;
5344 // If this constraint is for a specific register, allocate it before
5346 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5347 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5350 ConstraintInfos.clear();
5352 // Second pass - Loop over all of the operands, assigning virtual or physregs
5353 // to register class operands.
5354 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5355 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5357 // C_Register operands have already been allocated, Other/Memory don't need
5359 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5360 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5363 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5364 std::vector<SDValue> AsmNodeOperands;
5365 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5366 AsmNodeOperands.push_back(
5367 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5368 TLI.getPointerTy()));
5371 // Loop over all of the inputs, copying the operand values into the
5372 // appropriate registers and processing the output regs.
5373 RegsForValue RetValRegs;
5375 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5376 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5378 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5379 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5381 switch (OpInfo.Type) {
5382 case InlineAsm::isOutput: {
5383 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5384 OpInfo.ConstraintType != TargetLowering::C_Register) {
5385 // Memory output, or 'other' output (e.g. 'X' constraint).
5386 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5388 // Add information to the INLINEASM node to know about this output.
5389 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5390 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5391 TLI.getPointerTy()));
5392 AsmNodeOperands.push_back(OpInfo.CallOperand);
5396 // Otherwise, this is a register or register class output.
5398 // Copy the output from the appropriate register. Find a register that
5400 if (OpInfo.AssignedRegs.Regs.empty()) {
5401 llvm_report_error("Couldn't allocate output reg for"
5402 " constraint '" + OpInfo.ConstraintCode + "'!");
5405 // If this is an indirect operand, store through the pointer after the
5407 if (OpInfo.isIndirect) {
5408 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5409 OpInfo.CallOperandVal));
5411 // This is the result value of the call.
5412 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5413 // Concatenate this output onto the outputs list.
5414 RetValRegs.append(OpInfo.AssignedRegs);
5417 // Add information to the INLINEASM node to know that this register is
5419 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5420 6 /* EARLYCLOBBER REGDEF */ :
5428 case InlineAsm::isInput: {
5429 SDValue InOperandVal = OpInfo.CallOperand;
5431 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5432 // If this is required to match an output register we have already set,
5433 // just use its register.
5434 unsigned OperandNo = OpInfo.getMatchedOperand();
5436 // Scan until we find the definition we already emitted of this operand.
5437 // When we find it, create a RegsForValue operand.
5438 unsigned CurOp = 2; // The first operand.
5439 for (; OperandNo; --OperandNo) {
5440 // Advance to the next operand.
5442 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5443 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5444 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5445 (OpFlag & 7) == 4 /*MEM*/) &&
5446 "Skipped past definitions?");
5447 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5451 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5452 if ((OpFlag & 7) == 2 /*REGDEF*/
5453 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5454 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5455 if (OpInfo.isIndirect) {
5456 llvm_report_error("Don't know how to handle tied indirect "
5457 "register inputs yet!");
5459 RegsForValue MatchedRegs;
5460 MatchedRegs.TLI = &TLI;
5461 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5462 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5463 MatchedRegs.RegVTs.push_back(RegVT);
5464 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5465 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5467 MatchedRegs.Regs.push_back
5468 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5470 // Use the produced MatchedRegs object to
5471 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5472 SDNodeOrder, Chain, &Flag);
5473 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5474 true, OpInfo.getMatchedOperand(),
5475 DAG, SDNodeOrder, AsmNodeOperands);
5478 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5479 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5480 "Unexpected number of operands");
5481 // Add information to the INLINEASM node to know about this input.
5482 // See InlineAsm.h isUseOperandTiedToDef.
5483 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5484 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5485 TLI.getPointerTy()));
5486 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5491 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5492 assert(!OpInfo.isIndirect &&
5493 "Don't know how to handle indirect other inputs yet!");
5495 std::vector<SDValue> Ops;
5496 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5497 hasMemory, Ops, DAG);
5499 llvm_report_error("Invalid operand for inline asm"
5500 " constraint '" + OpInfo.ConstraintCode + "'!");
5503 // Add information to the INLINEASM node to know about this input.
5504 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5505 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5506 TLI.getPointerTy()));
5507 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5509 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5510 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5511 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5512 "Memory operands expect pointer values");
5514 // Add information to the INLINEASM node to know about this input.
5515 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5516 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5517 TLI.getPointerTy()));
5518 AsmNodeOperands.push_back(InOperandVal);
5522 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5523 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5524 "Unknown constraint type!");
5525 assert(!OpInfo.isIndirect &&
5526 "Don't know how to handle indirect register inputs yet!");
5528 // Copy the input into the appropriate registers.
5529 if (OpInfo.AssignedRegs.Regs.empty() ||
5530 !OpInfo.AssignedRegs.areValueTypesLegal()) {
5531 llvm_report_error("Couldn't allocate input reg for"
5532 " constraint '"+ OpInfo.ConstraintCode +"'!");
5535 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5536 SDNodeOrder, Chain, &Flag);
5538 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5543 case InlineAsm::isClobber: {
5544 // Add the clobbered value to the operand list, so that the register
5545 // allocator is aware that the physreg got clobbered.
5546 if (!OpInfo.AssignedRegs.Regs.empty())
5547 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5548 false, 0, DAG, SDNodeOrder,
5555 // Finish up input operands.
5556 AsmNodeOperands[0] = Chain;
5557 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5559 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5560 DAG.getVTList(MVT::Other, MVT::Flag),
5561 &AsmNodeOperands[0], AsmNodeOperands.size());
5562 Flag = Chain.getValue(1);
5564 // If this asm returns a register value, copy the result from that register
5565 // and set it as the value of the call.
5566 if (!RetValRegs.Regs.empty()) {
5567 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5568 SDNodeOrder, Chain, &Flag);
5570 // FIXME: Why don't we do this for inline asms with MRVs?
5571 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5572 EVT ResultType = TLI.getValueType(CS.getType());
5574 // If any of the results of the inline asm is a vector, it may have the
5575 // wrong width/num elts. This can happen for register classes that can
5576 // contain multiple different value types. The preg or vreg allocated may
5577 // not have the same VT as was expected. Convert it to the right type
5578 // with bit_convert.
5579 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5580 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5583 } else if (ResultType != Val.getValueType() &&
5584 ResultType.isInteger() && Val.getValueType().isInteger()) {
5585 // If a result value was tied to an input value, the computed result may
5586 // have a wider width than the expected result. Extract the relevant
5588 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5591 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5594 setValue(CS.getInstruction(), Val);
5595 // Don't need to use this as a chain in this case.
5596 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5600 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5602 // Process indirect outputs, first output all of the flagged copies out of
5604 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5605 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5606 Value *Ptr = IndirectStoresToEmit[i].second;
5607 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5608 SDNodeOrder, Chain, &Flag);
5609 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5613 // Emit the non-flagged stores from the physregs.
5614 SmallVector<SDValue, 8> OutChains;
5615 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5616 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5617 StoresToEmit[i].first,
5618 getValue(StoresToEmit[i].second),
5619 StoresToEmit[i].second, 0);
5620 OutChains.push_back(Val);
5623 if (!OutChains.empty())
5624 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5625 &OutChains[0], OutChains.size());
5630 void SelectionDAGBuilder::visitVAStart(CallInst &I) {
5631 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5632 MVT::Other, getRoot(),
5633 getValue(I.getOperand(1)),
5634 DAG.getSrcValue(I.getOperand(1))));
5637 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
5638 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5639 getRoot(), getValue(I.getOperand(0)),
5640 DAG.getSrcValue(I.getOperand(0)));
5642 DAG.setRoot(V.getValue(1));
5645 void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
5646 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5647 MVT::Other, getRoot(),
5648 getValue(I.getOperand(1)),
5649 DAG.getSrcValue(I.getOperand(1))));
5652 void SelectionDAGBuilder::visitVACopy(CallInst &I) {
5653 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5654 MVT::Other, getRoot(),
5655 getValue(I.getOperand(1)),
5656 getValue(I.getOperand(2)),
5657 DAG.getSrcValue(I.getOperand(1)),
5658 DAG.getSrcValue(I.getOperand(2))));
5661 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5662 /// implementation, which just calls LowerCall.
5663 /// FIXME: When all targets are
5664 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5665 std::pair<SDValue, SDValue>
5666 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5667 bool RetSExt, bool RetZExt, bool isVarArg,
5668 bool isInreg, unsigned NumFixedArgs,
5669 CallingConv::ID CallConv, bool isTailCall,
5670 bool isReturnValueUsed,
5672 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl,
5674 // Handle all of the outgoing arguments.
5675 SmallVector<ISD::OutputArg, 32> Outs;
5676 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5677 SmallVector<EVT, 4> ValueVTs;
5678 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5679 for (unsigned Value = 0, NumValues = ValueVTs.size();
5680 Value != NumValues; ++Value) {
5681 EVT VT = ValueVTs[Value];
5682 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5683 SDValue Op = SDValue(Args[i].Node.getNode(),
5684 Args[i].Node.getResNo() + Value);
5685 ISD::ArgFlagsTy Flags;
5686 unsigned OriginalAlignment =
5687 getTargetData()->getABITypeAlignment(ArgTy);
5693 if (Args[i].isInReg)
5697 if (Args[i].isByVal) {
5699 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5700 const Type *ElementTy = Ty->getElementType();
5701 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5702 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5703 // For ByVal, alignment should come from FE. BE will guess if this
5704 // info is not there but there are cases it cannot get right.
5705 if (Args[i].Alignment)
5706 FrameAlign = Args[i].Alignment;
5707 Flags.setByValAlign(FrameAlign);
5708 Flags.setByValSize(FrameSize);
5712 Flags.setOrigAlign(OriginalAlignment);
5714 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5715 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5716 SmallVector<SDValue, 4> Parts(NumParts);
5717 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5720 ExtendKind = ISD::SIGN_EXTEND;
5721 else if (Args[i].isZExt)
5722 ExtendKind = ISD::ZERO_EXTEND;
5724 getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts,
5725 PartVT, ExtendKind);
5727 for (unsigned j = 0; j != NumParts; ++j) {
5728 // if it isn't first piece, alignment must be 1
5729 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5730 if (NumParts > 1 && j == 0)
5731 MyFlags.Flags.setSplit();
5733 MyFlags.Flags.setOrigAlign(1);
5735 Outs.push_back(MyFlags);
5740 // Handle the incoming return values from the call.
5741 SmallVector<ISD::InputArg, 32> Ins;
5742 SmallVector<EVT, 4> RetTys;
5743 ComputeValueVTs(*this, RetTy, RetTys);
5744 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5746 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5747 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5748 for (unsigned i = 0; i != NumRegs; ++i) {
5749 ISD::InputArg MyFlags;
5750 MyFlags.VT = RegisterVT;
5751 MyFlags.Used = isReturnValueUsed;
5753 MyFlags.Flags.setSExt();
5755 MyFlags.Flags.setZExt();
5757 MyFlags.Flags.setInReg();
5758 Ins.push_back(MyFlags);
5762 SmallVector<SDValue, 4> InVals;
5763 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5764 Outs, Ins, dl, DAG, InVals);
5766 // Verify that the target's LowerCall behaved as expected.
5767 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5768 "LowerCall didn't return a valid chain!");
5769 assert((!isTailCall || InVals.empty()) &&
5770 "LowerCall emitted a return value for a tail call!");
5771 assert((isTailCall || InVals.size() == Ins.size()) &&
5772 "LowerCall didn't emit the correct number of values!");
5773 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5774 assert(InVals[i].getNode() &&
5775 "LowerCall emitted a null value!");
5776 assert(Ins[i].VT == InVals[i].getValueType() &&
5777 "LowerCall emitted a value with the wrong type!");
5780 // For a tail call, the return value is merely live-out and there aren't
5781 // any nodes in the DAG representing it. Return a special value to
5782 // indicate that a tail call has been emitted and no more Instructions
5783 // should be processed in the current block.
5786 return std::make_pair(SDValue(), SDValue());
5789 // Collect the legal value parts into potentially illegal values
5790 // that correspond to the original function's return values.
5791 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5793 AssertOp = ISD::AssertSext;
5795 AssertOp = ISD::AssertZext;
5796 SmallVector<SDValue, 4> ReturnValues;
5797 unsigned CurReg = 0;
5798 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5800 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5801 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5803 ReturnValues.push_back(getCopyFromParts(DAG, dl, Order, &InVals[CurReg],
5804 NumRegs, RegisterVT, VT,
5809 // For a function returning void, there is no return value. We can't create
5810 // such a node, so we just return a null return value in that case. In
5811 // that case, nothing will actualy look at the value.
5812 if (ReturnValues.empty())
5813 return std::make_pair(SDValue(), Chain);
5815 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5816 DAG.getVTList(&RetTys[0], RetTys.size()),
5817 &ReturnValues[0], ReturnValues.size());
5818 return std::make_pair(Res, Chain);
5821 void TargetLowering::LowerOperationWrapper(SDNode *N,
5822 SmallVectorImpl<SDValue> &Results,
5823 SelectionDAG &DAG) {
5824 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5826 Results.push_back(Res);
5829 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5830 llvm_unreachable("LowerOperation not implemented for this target!");
5834 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5835 SDValue Op = getValue(V);
5836 assert((Op.getOpcode() != ISD::CopyFromReg ||
5837 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5838 "Copy from a reg to the same reg!");
5839 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5841 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5842 SDValue Chain = DAG.getEntryNode();
5843 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
5844 PendingExports.push_back(Chain);
5847 #include "llvm/CodeGen/SelectionDAGISel.h"
5849 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
5850 // If this is the entry block, emit arguments.
5851 Function &F = *LLVMBB->getParent();
5852 SelectionDAG &DAG = SDB->DAG;
5853 SDValue OldRoot = DAG.getRoot();
5854 DebugLoc dl = SDB->getCurDebugLoc();
5855 const TargetData *TD = TLI.getTargetData();
5856 SmallVector<ISD::InputArg, 16> Ins;
5858 // Check whether the function can return without sret-demotion.
5859 SmallVector<EVT, 4> OutVTs;
5860 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5861 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5862 OutVTs, OutsFlags, TLI);
5863 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5865 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5866 OutVTs, OutsFlags, DAG);
5867 if (!FLI.CanLowerReturn) {
5868 // Put in an sret pointer parameter before all the other parameters.
5869 SmallVector<EVT, 1> ValueVTs;
5870 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5872 // NOTE: Assuming that a pointer will never break down to more than one VT
5874 ISD::ArgFlagsTy Flags;
5876 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5877 ISD::InputArg RetArg(Flags, RegisterVT, true);
5878 Ins.push_back(RetArg);
5881 // Set up the incoming argument description vector.
5883 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5884 I != E; ++I, ++Idx) {
5885 SmallVector<EVT, 4> ValueVTs;
5886 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5887 bool isArgValueUsed = !I->use_empty();
5888 for (unsigned Value = 0, NumValues = ValueVTs.size();
5889 Value != NumValues; ++Value) {
5890 EVT VT = ValueVTs[Value];
5891 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5892 ISD::ArgFlagsTy Flags;
5893 unsigned OriginalAlignment =
5894 TD->getABITypeAlignment(ArgTy);
5896 if (F.paramHasAttr(Idx, Attribute::ZExt))
5898 if (F.paramHasAttr(Idx, Attribute::SExt))
5900 if (F.paramHasAttr(Idx, Attribute::InReg))
5902 if (F.paramHasAttr(Idx, Attribute::StructRet))
5904 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5906 const PointerType *Ty = cast<PointerType>(I->getType());
5907 const Type *ElementTy = Ty->getElementType();
5908 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5909 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5910 // For ByVal, alignment should be passed from FE. BE will guess if
5911 // this info is not there but there are cases it cannot get right.
5912 if (F.getParamAlignment(Idx))
5913 FrameAlign = F.getParamAlignment(Idx);
5914 Flags.setByValAlign(FrameAlign);
5915 Flags.setByValSize(FrameSize);
5917 if (F.paramHasAttr(Idx, Attribute::Nest))
5919 Flags.setOrigAlign(OriginalAlignment);
5921 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5922 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5923 for (unsigned i = 0; i != NumRegs; ++i) {
5924 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5925 if (NumRegs > 1 && i == 0)
5926 MyFlags.Flags.setSplit();
5927 // if it isn't first piece, alignment must be 1
5929 MyFlags.Flags.setOrigAlign(1);
5930 Ins.push_back(MyFlags);
5935 // Call the target to set up the argument values.
5936 SmallVector<SDValue, 8> InVals;
5937 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5941 // Verify that the target's LowerFormalArguments behaved as expected.
5942 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5943 "LowerFormalArguments didn't return a valid chain!");
5944 assert(InVals.size() == Ins.size() &&
5945 "LowerFormalArguments didn't emit the correct number of values!");
5947 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5948 assert(InVals[i].getNode() &&
5949 "LowerFormalArguments emitted a null value!");
5950 assert(Ins[i].VT == InVals[i].getValueType() &&
5951 "LowerFormalArguments emitted a value with the wrong type!");
5955 // Update the DAG with the new chain value resulting from argument lowering.
5956 DAG.setRoot(NewRoot);
5958 // Set up the argument values.
5961 if (!FLI.CanLowerReturn) {
5962 // Create a virtual register for the sret pointer, and put in a copy
5963 // from the sret argument into it.
5964 SmallVector<EVT, 1> ValueVTs;
5965 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5966 EVT VT = ValueVTs[0];
5967 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5968 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5969 SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1,
5970 RegVT, VT, AssertOp);
5972 MachineFunction& MF = SDB->DAG.getMachineFunction();
5973 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5974 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5975 FLI.DemoteRegister = SRetReg;
5976 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
5978 DAG.setRoot(NewRoot);
5980 // i indexes lowered arguments. Bump it past the hidden sret argument.
5981 // Idx indexes LLVM arguments. Don't touch it.
5985 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5987 SmallVector<SDValue, 4> ArgValues;
5988 SmallVector<EVT, 4> ValueVTs;
5989 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5990 unsigned NumValues = ValueVTs.size();
5991 for (unsigned Value = 0; Value != NumValues; ++Value) {
5992 EVT VT = ValueVTs[Value];
5993 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5994 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5996 if (!I->use_empty()) {
5997 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5998 if (F.paramHasAttr(Idx, Attribute::SExt))
5999 AssertOp = ISD::AssertSext;
6000 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6001 AssertOp = ISD::AssertZext;
6003 ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i],
6004 NumParts, PartVT, VT,
6011 if (!I->use_empty()) {
6012 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6013 SDB->getCurDebugLoc());
6014 SDB->setValue(I, Res);
6016 // If this argument is live outside of the entry block, insert a copy from
6017 // whereever we got it to the vreg that other BB's will reference it as.
6018 SDB->CopyToExportRegsIfNeeded(I);
6022 assert(i == InVals.size() && "Argument register count mismatch!");
6024 // Finally, if the target has anything special to do, allow it to do so.
6025 // FIXME: this should insert code into the DAG!
6026 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
6029 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6030 /// ensure constants are generated when needed. Remember the virtual registers
6031 /// that need to be added to the Machine PHI nodes as input. We cannot just
6032 /// directly add them, because expansion might result in multiple MBB's for one
6033 /// BB. As such, the start of the BB might correspond to a different MBB than
6037 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6038 TerminatorInst *TI = LLVMBB->getTerminator();
6040 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6042 // Check successor nodes' PHI nodes that expect a constant to be available
6044 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6045 BasicBlock *SuccBB = TI->getSuccessor(succ);
6046 if (!isa<PHINode>(SuccBB->begin())) continue;
6047 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6049 // If this terminator has multiple identical successors (common for
6050 // switches), only handle each succ once.
6051 if (!SuccsHandled.insert(SuccMBB)) continue;
6053 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6056 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6057 // nodes and Machine PHI nodes, but the incoming operands have not been
6059 for (BasicBlock::iterator I = SuccBB->begin();
6060 (PN = dyn_cast<PHINode>(I)); ++I) {
6061 // Ignore dead phi's.
6062 if (PN->use_empty()) continue;
6065 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6067 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6068 unsigned &RegOut = SDB->ConstantsOut[C];
6070 RegOut = FuncInfo->CreateRegForValue(C);
6071 SDB->CopyValueToVirtualRegister(C, RegOut);
6075 Reg = FuncInfo->ValueMap[PHIOp];
6077 assert(isa<AllocaInst>(PHIOp) &&
6078 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6079 "Didn't codegen value into a register!??");
6080 Reg = FuncInfo->CreateRegForValue(PHIOp);
6081 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6085 // Remember that this register needs to added to the machine PHI node as
6086 // the input for this MBB.
6087 SmallVector<EVT, 4> ValueVTs;
6088 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6089 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6090 EVT VT = ValueVTs[vti];
6091 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6092 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6093 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6094 Reg += NumRegisters;
6098 SDB->ConstantsOut.clear();
6101 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6102 /// supports legal types, and it emits MachineInstrs directly instead of
6103 /// creating SelectionDAG nodes.
6106 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6108 TerminatorInst *TI = LLVMBB->getTerminator();
6110 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6111 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6113 // Check successor nodes' PHI nodes that expect a constant to be available
6115 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6116 BasicBlock *SuccBB = TI->getSuccessor(succ);
6117 if (!isa<PHINode>(SuccBB->begin())) continue;
6118 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6120 // If this terminator has multiple identical successors (common for
6121 // switches), only handle each succ once.
6122 if (!SuccsHandled.insert(SuccMBB)) continue;
6124 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6127 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6128 // nodes and Machine PHI nodes, but the incoming operands have not been
6130 for (BasicBlock::iterator I = SuccBB->begin();
6131 (PN = dyn_cast<PHINode>(I)); ++I) {
6132 // Ignore dead phi's.
6133 if (PN->use_empty()) continue;
6135 // Only handle legal types. Two interesting things to note here. First,
6136 // by bailing out early, we may leave behind some dead instructions,
6137 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6138 // own moves. Second, this check is necessary becuase FastISel doesn't
6139 // use CreateRegForValue to create registers, so it always creates
6140 // exactly one register for each non-void instruction.
6141 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6142 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6145 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6147 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6152 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6154 unsigned Reg = F->getRegForValue(PHIOp);
6156 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6159 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));