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 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 with unique successors.
2066 SmallVector<BasicBlock*, 32> succs;
2067 succs.reserve(I.getNumSuccessors());
2068 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2069 succs.push_back(I.getSuccessor(i));
2070 array_pod_sort(succs.begin(), succs.end());
2071 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2072 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2073 CurMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2075 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2076 MVT::Other, getControlRoot(),
2077 getValue(I.getAddress())));
2080 void SelectionDAGBuilder::visitFSub(User &I) {
2081 // -0.0 - X --> fneg
2082 const Type *Ty = I.getType();
2083 if (isa<VectorType>(Ty)) {
2084 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2085 const VectorType *DestTy = cast<VectorType>(I.getType());
2086 const Type *ElTy = DestTy->getElementType();
2087 unsigned VL = DestTy->getNumElements();
2088 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2089 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2091 SDValue Op2 = getValue(I.getOperand(1));
2092 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2093 Op2.getValueType(), Op2));
2099 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2100 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2101 SDValue Op2 = getValue(I.getOperand(1));
2102 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2103 Op2.getValueType(), Op2));
2107 visitBinary(I, ISD::FSUB);
2110 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2111 SDValue Op1 = getValue(I.getOperand(0));
2112 SDValue Op2 = getValue(I.getOperand(1));
2113 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2114 Op1.getValueType(), Op1, Op2));
2117 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2118 SDValue Op1 = getValue(I.getOperand(0));
2119 SDValue Op2 = getValue(I.getOperand(1));
2120 if (!isa<VectorType>(I.getType()) &&
2121 Op2.getValueType() != TLI.getShiftAmountTy()) {
2122 // If the operand is smaller than the shift count type, promote it.
2123 EVT PTy = TLI.getPointerTy();
2124 EVT STy = TLI.getShiftAmountTy();
2125 if (STy.bitsGT(Op2.getValueType()))
2126 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2127 TLI.getShiftAmountTy(), Op2);
2128 // If the operand is larger than the shift count type but the shift
2129 // count type has enough bits to represent any shift value, truncate
2130 // it now. This is a common case and it exposes the truncate to
2131 // optimization early.
2132 else if (STy.getSizeInBits() >=
2133 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2134 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2135 TLI.getShiftAmountTy(), Op2);
2136 // Otherwise we'll need to temporarily settle for some other
2137 // convenient type; type legalization will make adjustments as
2139 else if (PTy.bitsLT(Op2.getValueType()))
2140 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2141 TLI.getPointerTy(), Op2);
2142 else if (PTy.bitsGT(Op2.getValueType()))
2143 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2144 TLI.getPointerTy(), Op2);
2147 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2148 Op1.getValueType(), Op1, Op2));
2151 void SelectionDAGBuilder::visitICmp(User &I) {
2152 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2153 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2154 predicate = IC->getPredicate();
2155 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2156 predicate = ICmpInst::Predicate(IC->getPredicate());
2157 SDValue Op1 = getValue(I.getOperand(0));
2158 SDValue Op2 = getValue(I.getOperand(1));
2159 ISD::CondCode Opcode = getICmpCondCode(predicate);
2161 EVT DestVT = TLI.getValueType(I.getType());
2162 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2165 void SelectionDAGBuilder::visitFCmp(User &I) {
2166 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2167 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2168 predicate = FC->getPredicate();
2169 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2170 predicate = FCmpInst::Predicate(FC->getPredicate());
2171 SDValue Op1 = getValue(I.getOperand(0));
2172 SDValue Op2 = getValue(I.getOperand(1));
2173 ISD::CondCode Condition = getFCmpCondCode(predicate);
2174 EVT DestVT = TLI.getValueType(I.getType());
2175 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2178 void SelectionDAGBuilder::visitSelect(User &I) {
2179 SmallVector<EVT, 4> ValueVTs;
2180 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2181 unsigned NumValues = ValueVTs.size();
2182 if (NumValues == 0) return;
2184 SmallVector<SDValue, 4> Values(NumValues);
2185 SDValue Cond = getValue(I.getOperand(0));
2186 SDValue TrueVal = getValue(I.getOperand(1));
2187 SDValue FalseVal = getValue(I.getOperand(2));
2189 for (unsigned i = 0; i != NumValues; ++i)
2190 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2191 TrueVal.getNode()->getValueType(i), Cond,
2192 SDValue(TrueVal.getNode(),
2193 TrueVal.getResNo() + i),
2194 SDValue(FalseVal.getNode(),
2195 FalseVal.getResNo() + i));
2197 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2198 DAG.getVTList(&ValueVTs[0], NumValues),
2199 &Values[0], NumValues));
2202 void SelectionDAGBuilder::visitTrunc(User &I) {
2203 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2204 SDValue N = getValue(I.getOperand(0));
2205 EVT DestVT = TLI.getValueType(I.getType());
2206 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2209 void SelectionDAGBuilder::visitZExt(User &I) {
2210 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2211 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2212 SDValue N = getValue(I.getOperand(0));
2213 EVT DestVT = TLI.getValueType(I.getType());
2214 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2217 void SelectionDAGBuilder::visitSExt(User &I) {
2218 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2219 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2220 SDValue N = getValue(I.getOperand(0));
2221 EVT DestVT = TLI.getValueType(I.getType());
2222 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2225 void SelectionDAGBuilder::visitFPTrunc(User &I) {
2226 // FPTrunc is never a no-op cast, no need to check
2227 SDValue N = getValue(I.getOperand(0));
2228 EVT DestVT = TLI.getValueType(I.getType());
2229 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2230 DestVT, N, DAG.getIntPtrConstant(0)));
2233 void SelectionDAGBuilder::visitFPExt(User &I){
2234 // FPTrunc is never a no-op cast, no need to check
2235 SDValue N = getValue(I.getOperand(0));
2236 EVT DestVT = TLI.getValueType(I.getType());
2237 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2240 void SelectionDAGBuilder::visitFPToUI(User &I) {
2241 // FPToUI is never a no-op cast, no need to check
2242 SDValue N = getValue(I.getOperand(0));
2243 EVT DestVT = TLI.getValueType(I.getType());
2244 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2247 void SelectionDAGBuilder::visitFPToSI(User &I) {
2248 // FPToSI is never a no-op cast, no need to check
2249 SDValue N = getValue(I.getOperand(0));
2250 EVT DestVT = TLI.getValueType(I.getType());
2251 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2254 void SelectionDAGBuilder::visitUIToFP(User &I) {
2255 // UIToFP is never a no-op cast, no need to check
2256 SDValue N = getValue(I.getOperand(0));
2257 EVT DestVT = TLI.getValueType(I.getType());
2258 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2261 void SelectionDAGBuilder::visitSIToFP(User &I){
2262 // SIToFP is never a no-op cast, no need to check
2263 SDValue N = getValue(I.getOperand(0));
2264 EVT DestVT = TLI.getValueType(I.getType());
2265 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2268 void SelectionDAGBuilder::visitPtrToInt(User &I) {
2269 // What to do depends on the size of the integer and the size of the pointer.
2270 // We can either truncate, zero extend, or no-op, accordingly.
2271 SDValue N = getValue(I.getOperand(0));
2272 EVT SrcVT = N.getValueType();
2273 EVT DestVT = TLI.getValueType(I.getType());
2274 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2277 void SelectionDAGBuilder::visitIntToPtr(User &I) {
2278 // What to do depends on the size of the integer and the size of the pointer.
2279 // We can either truncate, zero extend, or no-op, accordingly.
2280 SDValue N = getValue(I.getOperand(0));
2281 EVT SrcVT = N.getValueType();
2282 EVT DestVT = TLI.getValueType(I.getType());
2283 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2286 void SelectionDAGBuilder::visitBitCast(User &I) {
2287 SDValue N = getValue(I.getOperand(0));
2288 EVT DestVT = TLI.getValueType(I.getType());
2290 // BitCast assures us that source and destination are the same size so this is
2291 // either a BIT_CONVERT or a no-op.
2292 if (DestVT != N.getValueType())
2293 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2294 DestVT, N)); // convert types.
2296 setValue(&I, N); // noop cast.
2299 void SelectionDAGBuilder::visitInsertElement(User &I) {
2300 SDValue InVec = getValue(I.getOperand(0));
2301 SDValue InVal = getValue(I.getOperand(1));
2302 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2304 getValue(I.getOperand(2)));
2305 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2306 TLI.getValueType(I.getType()),
2307 InVec, InVal, InIdx));
2310 void SelectionDAGBuilder::visitExtractElement(User &I) {
2311 SDValue InVec = getValue(I.getOperand(0));
2312 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2314 getValue(I.getOperand(1)));
2315 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2316 TLI.getValueType(I.getType()), InVec, InIdx));
2319 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2320 // from SIndx and increasing to the element length (undefs are allowed).
2321 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2322 unsigned MaskNumElts = Mask.size();
2323 for (unsigned i = 0; i != MaskNumElts; ++i)
2324 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2329 void SelectionDAGBuilder::visitShuffleVector(User &I) {
2330 SmallVector<int, 8> Mask;
2331 SDValue Src1 = getValue(I.getOperand(0));
2332 SDValue Src2 = getValue(I.getOperand(1));
2334 // Convert the ConstantVector mask operand into an array of ints, with -1
2335 // representing undef values.
2336 SmallVector<Constant*, 8> MaskElts;
2337 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2338 unsigned MaskNumElts = MaskElts.size();
2339 for (unsigned i = 0; i != MaskNumElts; ++i) {
2340 if (isa<UndefValue>(MaskElts[i]))
2343 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2346 EVT VT = TLI.getValueType(I.getType());
2347 EVT SrcVT = Src1.getValueType();
2348 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2350 if (SrcNumElts == MaskNumElts) {
2351 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2356 // Normalize the shuffle vector since mask and vector length don't match.
2357 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2358 // Mask is longer than the source vectors and is a multiple of the source
2359 // vectors. We can use concatenate vector to make the mask and vectors
2361 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2362 // The shuffle is concatenating two vectors together.
2363 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2368 // Pad both vectors with undefs to make them the same length as the mask.
2369 unsigned NumConcat = MaskNumElts / SrcNumElts;
2370 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2371 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2372 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2374 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2375 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2379 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2380 getCurDebugLoc(), VT,
2381 &MOps1[0], NumConcat);
2382 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2383 getCurDebugLoc(), VT,
2384 &MOps2[0], NumConcat);
2386 // Readjust mask for new input vector length.
2387 SmallVector<int, 8> MappedOps;
2388 for (unsigned i = 0; i != MaskNumElts; ++i) {
2390 if (Idx < (int)SrcNumElts)
2391 MappedOps.push_back(Idx);
2393 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2396 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2401 if (SrcNumElts > MaskNumElts) {
2402 // Analyze the access pattern of the vector to see if we can extract
2403 // two subvectors and do the shuffle. The analysis is done by calculating
2404 // the range of elements the mask access on both vectors.
2405 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2406 int MaxRange[2] = {-1, -1};
2408 for (unsigned i = 0; i != MaskNumElts; ++i) {
2414 if (Idx >= (int)SrcNumElts) {
2418 if (Idx > MaxRange[Input])
2419 MaxRange[Input] = Idx;
2420 if (Idx < MinRange[Input])
2421 MinRange[Input] = Idx;
2424 // Check if the access is smaller than the vector size and can we find
2425 // a reasonable extract index.
2426 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2428 int StartIdx[2]; // StartIdx to extract from
2429 for (int Input=0; Input < 2; ++Input) {
2430 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2431 RangeUse[Input] = 0; // Unused
2432 StartIdx[Input] = 0;
2433 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2434 // Fits within range but we should see if we can find a good
2435 // start index that is a multiple of the mask length.
2436 if (MaxRange[Input] < (int)MaskNumElts) {
2437 RangeUse[Input] = 1; // Extract from beginning of the vector
2438 StartIdx[Input] = 0;
2440 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2441 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2442 StartIdx[Input] + MaskNumElts < SrcNumElts)
2443 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2448 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2449 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2452 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2453 // Extract appropriate subvector and generate a vector shuffle
2454 for (int Input=0; Input < 2; ++Input) {
2455 SDValue &Src = Input == 0 ? Src1 : Src2;
2456 if (RangeUse[Input] == 0)
2457 Src = DAG.getUNDEF(VT);
2459 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2460 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2463 // Calculate new mask.
2464 SmallVector<int, 8> MappedOps;
2465 for (unsigned i = 0; i != MaskNumElts; ++i) {
2468 MappedOps.push_back(Idx);
2469 else if (Idx < (int)SrcNumElts)
2470 MappedOps.push_back(Idx - StartIdx[0]);
2472 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2475 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2481 // We can't use either concat vectors or extract subvectors so fall back to
2482 // replacing the shuffle with extract and build vector.
2483 // to insert and build vector.
2484 EVT EltVT = VT.getVectorElementType();
2485 EVT PtrVT = TLI.getPointerTy();
2486 SmallVector<SDValue,8> Ops;
2487 for (unsigned i = 0; i != MaskNumElts; ++i) {
2489 Ops.push_back(DAG.getUNDEF(EltVT));
2494 if (Idx < (int)SrcNumElts)
2495 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2496 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2498 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2500 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2506 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2507 VT, &Ops[0], Ops.size()));
2510 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2511 const Value *Op0 = I.getOperand(0);
2512 const Value *Op1 = I.getOperand(1);
2513 const Type *AggTy = I.getType();
2514 const Type *ValTy = Op1->getType();
2515 bool IntoUndef = isa<UndefValue>(Op0);
2516 bool FromUndef = isa<UndefValue>(Op1);
2518 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2519 I.idx_begin(), I.idx_end());
2521 SmallVector<EVT, 4> AggValueVTs;
2522 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2523 SmallVector<EVT, 4> ValValueVTs;
2524 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2526 unsigned NumAggValues = AggValueVTs.size();
2527 unsigned NumValValues = ValValueVTs.size();
2528 SmallVector<SDValue, 4> Values(NumAggValues);
2530 SDValue Agg = getValue(Op0);
2531 SDValue Val = getValue(Op1);
2533 // Copy the beginning value(s) from the original aggregate.
2534 for (; i != LinearIndex; ++i)
2535 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2536 SDValue(Agg.getNode(), Agg.getResNo() + i);
2537 // Copy values from the inserted value(s).
2538 for (; i != LinearIndex + NumValValues; ++i)
2539 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2540 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2541 // Copy remaining value(s) from the original aggregate.
2542 for (; i != NumAggValues; ++i)
2543 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2544 SDValue(Agg.getNode(), Agg.getResNo() + i);
2546 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2547 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2548 &Values[0], NumAggValues));
2551 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2552 const Value *Op0 = I.getOperand(0);
2553 const Type *AggTy = Op0->getType();
2554 const Type *ValTy = I.getType();
2555 bool OutOfUndef = isa<UndefValue>(Op0);
2557 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2558 I.idx_begin(), I.idx_end());
2560 SmallVector<EVT, 4> ValValueVTs;
2561 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2563 unsigned NumValValues = ValValueVTs.size();
2564 SmallVector<SDValue, 4> Values(NumValValues);
2566 SDValue Agg = getValue(Op0);
2567 // Copy out the selected value(s).
2568 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2569 Values[i - LinearIndex] =
2571 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2572 SDValue(Agg.getNode(), Agg.getResNo() + i);
2574 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2575 DAG.getVTList(&ValValueVTs[0], NumValValues),
2576 &Values[0], NumValValues));
2579 void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2580 SDValue N = getValue(I.getOperand(0));
2581 const Type *Ty = I.getOperand(0)->getType();
2583 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2586 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2587 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2590 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2591 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2592 DAG.getIntPtrConstant(Offset));
2595 Ty = StTy->getElementType(Field);
2597 Ty = cast<SequentialType>(Ty)->getElementType();
2599 // If this is a constant subscript, handle it quickly.
2600 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2601 if (CI->getZExtValue() == 0) continue;
2603 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2605 EVT PTy = TLI.getPointerTy();
2606 unsigned PtrBits = PTy.getSizeInBits();
2608 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2610 DAG.getConstant(Offs, MVT::i64));
2612 OffsVal = DAG.getIntPtrConstant(Offs);
2614 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2619 // N = N + Idx * ElementSize;
2620 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2621 TD->getTypeAllocSize(Ty));
2622 SDValue IdxN = getValue(Idx);
2624 // If the index is smaller or larger than intptr_t, truncate or extend
2626 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2628 // If this is a multiply by a power of two, turn it into a shl
2629 // immediately. This is a very common case.
2630 if (ElementSize != 1) {
2631 if (ElementSize.isPowerOf2()) {
2632 unsigned Amt = ElementSize.logBase2();
2633 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2634 N.getValueType(), IdxN,
2635 DAG.getConstant(Amt, TLI.getPointerTy()));
2637 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2638 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2639 N.getValueType(), IdxN, Scale);
2643 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2644 N.getValueType(), N, IdxN);
2651 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2652 // If this is a fixed sized alloca in the entry block of the function,
2653 // allocate it statically on the stack.
2654 if (FuncInfo.StaticAllocaMap.count(&I))
2655 return; // getValue will auto-populate this.
2657 const Type *Ty = I.getAllocatedType();
2658 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2660 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2663 SDValue AllocSize = getValue(I.getArraySize());
2665 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2667 DAG.getConstant(TySize, AllocSize.getValueType()));
2669 EVT IntPtr = TLI.getPointerTy();
2670 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2672 // Handle alignment. If the requested alignment is less than or equal to
2673 // the stack alignment, ignore it. If the size is greater than or equal to
2674 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2675 unsigned StackAlign =
2676 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2677 if (Align <= StackAlign)
2680 // Round the size of the allocation up to the stack alignment size
2681 // by add SA-1 to the size.
2682 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2683 AllocSize.getValueType(), AllocSize,
2684 DAG.getIntPtrConstant(StackAlign-1));
2686 // Mask out the low bits for alignment purposes.
2687 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2688 AllocSize.getValueType(), AllocSize,
2689 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2691 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2692 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2693 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2696 DAG.setRoot(DSA.getValue(1));
2698 // Inform the Frame Information that we have just allocated a variable-sized
2700 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2703 void SelectionDAGBuilder::visitLoad(LoadInst &I) {
2704 const Value *SV = I.getOperand(0);
2705 SDValue Ptr = getValue(SV);
2707 const Type *Ty = I.getType();
2708 bool isVolatile = I.isVolatile();
2709 unsigned Alignment = I.getAlignment();
2711 SmallVector<EVT, 4> ValueVTs;
2712 SmallVector<uint64_t, 4> Offsets;
2713 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2714 unsigned NumValues = ValueVTs.size();
2719 bool ConstantMemory = false;
2721 // Serialize volatile loads with other side effects.
2723 else if (AA->pointsToConstantMemory(SV)) {
2724 // Do not serialize (non-volatile) loads of constant memory with anything.
2725 Root = DAG.getEntryNode();
2726 ConstantMemory = true;
2728 // Do not serialize non-volatile loads against each other.
2729 Root = DAG.getRoot();
2732 SmallVector<SDValue, 4> Values(NumValues);
2733 SmallVector<SDValue, 4> Chains(NumValues);
2734 EVT PtrVT = Ptr.getValueType();
2735 for (unsigned i = 0; i != NumValues; ++i) {
2736 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2738 DAG.getConstant(Offsets[i], PtrVT));
2739 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2740 A, SV, Offsets[i], isVolatile, Alignment);
2743 Chains[i] = L.getValue(1);
2746 if (!ConstantMemory) {
2747 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2748 MVT::Other, &Chains[0], NumValues);
2752 PendingLoads.push_back(Chain);
2755 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2756 DAG.getVTList(&ValueVTs[0], NumValues),
2757 &Values[0], NumValues));
2760 void SelectionDAGBuilder::visitStore(StoreInst &I) {
2761 Value *SrcV = I.getOperand(0);
2762 Value *PtrV = I.getOperand(1);
2764 SmallVector<EVT, 4> ValueVTs;
2765 SmallVector<uint64_t, 4> Offsets;
2766 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2767 unsigned NumValues = ValueVTs.size();
2771 // Get the lowered operands. Note that we do this after
2772 // checking if NumResults is zero, because with zero results
2773 // the operands won't have values in the map.
2774 SDValue Src = getValue(SrcV);
2775 SDValue Ptr = getValue(PtrV);
2777 SDValue Root = getRoot();
2778 SmallVector<SDValue, 4> Chains(NumValues);
2779 EVT PtrVT = Ptr.getValueType();
2780 bool isVolatile = I.isVolatile();
2781 unsigned Alignment = I.getAlignment();
2783 for (unsigned i = 0; i != NumValues; ++i) {
2784 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2785 DAG.getConstant(Offsets[i], PtrVT));
2786 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2787 SDValue(Src.getNode(), Src.getResNo() + i),
2788 Add, PtrV, Offsets[i], isVolatile, Alignment);
2791 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2792 MVT::Other, &Chains[0], NumValues));
2795 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2797 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2798 unsigned Intrinsic) {
2799 bool HasChain = !I.doesNotAccessMemory();
2800 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2802 // Build the operand list.
2803 SmallVector<SDValue, 8> Ops;
2804 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2806 // We don't need to serialize loads against other loads.
2807 Ops.push_back(DAG.getRoot());
2809 Ops.push_back(getRoot());
2813 // Info is set by getTgtMemInstrinsic
2814 TargetLowering::IntrinsicInfo Info;
2815 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2817 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2818 if (!IsTgtIntrinsic)
2819 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2821 // Add all operands of the call to the operand list.
2822 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2823 SDValue Op = getValue(I.getOperand(i));
2824 assert(TLI.isTypeLegal(Op.getValueType()) &&
2825 "Intrinsic uses a non-legal type?");
2829 SmallVector<EVT, 4> ValueVTs;
2830 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2832 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2833 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2834 "Intrinsic uses a non-legal type?");
2839 ValueVTs.push_back(MVT::Other);
2841 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2845 if (IsTgtIntrinsic) {
2846 // This is target intrinsic that touches memory
2847 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2848 VTs, &Ops[0], Ops.size(),
2849 Info.memVT, Info.ptrVal, Info.offset,
2850 Info.align, Info.vol,
2851 Info.readMem, Info.writeMem);
2852 } else if (!HasChain) {
2853 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2854 VTs, &Ops[0], Ops.size());
2855 } else if (!I.getType()->isVoidTy()) {
2856 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2857 VTs, &Ops[0], Ops.size());
2859 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2860 VTs, &Ops[0], Ops.size());
2864 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2866 PendingLoads.push_back(Chain);
2871 if (!I.getType()->isVoidTy()) {
2872 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2873 EVT VT = TLI.getValueType(PTy);
2874 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2877 setValue(&I, Result);
2881 /// GetSignificand - Get the significand and build it into a floating-point
2882 /// number with exponent of 1:
2884 /// Op = (Op & 0x007fffff) | 0x3f800000;
2886 /// where Op is the hexidecimal representation of floating point value.
2888 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
2889 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2890 DAG.getConstant(0x007fffff, MVT::i32));
2891 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2892 DAG.getConstant(0x3f800000, MVT::i32));
2893 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
2896 /// GetExponent - Get the exponent:
2898 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
2900 /// where Op is the hexidecimal representation of floating point value.
2902 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
2903 DebugLoc dl, unsigned Order) {
2904 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2905 DAG.getConstant(0x7f800000, MVT::i32));
2906 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
2907 DAG.getConstant(23, TLI.getPointerTy()));
2908 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2909 DAG.getConstant(127, MVT::i32));
2910 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
2913 /// getF32Constant - Get 32-bit floating point constant.
2915 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2916 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2919 /// Inlined utility function to implement binary input atomic intrinsics for
2920 /// visitIntrinsicCall: I is a call instruction
2921 /// Op is the associated NodeType for I
2923 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2924 SDValue Root = getRoot();
2926 DAG.getAtomic(Op, getCurDebugLoc(),
2927 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2929 getValue(I.getOperand(1)),
2930 getValue(I.getOperand(2)),
2933 DAG.setRoot(L.getValue(1));
2937 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2939 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
2940 SDValue Op1 = getValue(I.getOperand(1));
2941 SDValue Op2 = getValue(I.getOperand(2));
2943 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
2944 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
2948 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2949 /// limited-precision mode.
2951 SelectionDAGBuilder::visitExp(CallInst &I) {
2953 DebugLoc dl = getCurDebugLoc();
2955 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2956 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2957 SDValue Op = getValue(I.getOperand(1));
2959 // Put the exponent in the right bit position for later addition to the
2962 // #define LOG2OFe 1.4426950f
2963 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2964 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
2965 getF32Constant(DAG, 0x3fb8aa3b));
2966 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
2968 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2969 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2970 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
2972 // IntegerPartOfX <<= 23;
2973 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
2974 DAG.getConstant(23, TLI.getPointerTy()));
2976 if (LimitFloatPrecision <= 6) {
2977 // For floating-point precision of 6:
2979 // TwoToFractionalPartOfX =
2981 // (0.735607626f + 0.252464424f * x) * x;
2983 // error 0.0144103317, which is 6 bits
2984 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2985 getF32Constant(DAG, 0x3e814304));
2986 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2987 getF32Constant(DAG, 0x3f3c50c8));
2988 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2989 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2990 getF32Constant(DAG, 0x3f7f5e7e));
2991 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
2993 // Add the exponent into the result in integer domain.
2994 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2995 TwoToFracPartOfX, IntegerPartOfX);
2997 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
2998 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2999 // For floating-point precision of 12:
3001 // TwoToFractionalPartOfX =
3004 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3006 // 0.000107046256 error, which is 13 to 14 bits
3007 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3008 getF32Constant(DAG, 0x3da235e3));
3009 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3010 getF32Constant(DAG, 0x3e65b8f3));
3011 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3012 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3013 getF32Constant(DAG, 0x3f324b07));
3014 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3015 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3016 getF32Constant(DAG, 0x3f7ff8fd));
3017 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3019 // Add the exponent into the result in integer domain.
3020 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3021 TwoToFracPartOfX, IntegerPartOfX);
3023 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3024 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3025 // For floating-point precision of 18:
3027 // TwoToFractionalPartOfX =
3031 // (0.554906021e-1f +
3032 // (0.961591928e-2f +
3033 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3035 // error 2.47208000*10^(-7), which is better than 18 bits
3036 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3037 getF32Constant(DAG, 0x3924b03e));
3038 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3039 getF32Constant(DAG, 0x3ab24b87));
3040 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3041 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3042 getF32Constant(DAG, 0x3c1d8c17));
3043 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3044 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3045 getF32Constant(DAG, 0x3d634a1d));
3046 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3047 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3048 getF32Constant(DAG, 0x3e75fe14));
3049 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3050 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3051 getF32Constant(DAG, 0x3f317234));
3052 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3053 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3054 getF32Constant(DAG, 0x3f800000));
3055 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3058 // Add the exponent into the result in integer domain.
3059 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3060 TwoToFracPartOfX, IntegerPartOfX);
3062 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3065 // No special expansion.
3066 result = DAG.getNode(ISD::FEXP, dl,
3067 getValue(I.getOperand(1)).getValueType(),
3068 getValue(I.getOperand(1)));
3071 setValue(&I, result);
3074 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3075 /// limited-precision mode.
3077 SelectionDAGBuilder::visitLog(CallInst &I) {
3079 DebugLoc dl = getCurDebugLoc();
3081 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3082 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3083 SDValue Op = getValue(I.getOperand(1));
3084 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3086 // Scale the exponent by log(2) [0.69314718f].
3087 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3088 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3089 getF32Constant(DAG, 0x3f317218));
3091 // Get the significand and build it into a floating-point number with
3093 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3095 if (LimitFloatPrecision <= 6) {
3096 // For floating-point precision of 6:
3100 // (1.4034025f - 0.23903021f * x) * x;
3102 // error 0.0034276066, which is better than 8 bits
3103 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3104 getF32Constant(DAG, 0xbe74c456));
3105 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3106 getF32Constant(DAG, 0x3fb3a2b1));
3107 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3108 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3109 getF32Constant(DAG, 0x3f949a29));
3111 result = DAG.getNode(ISD::FADD, dl,
3112 MVT::f32, LogOfExponent, LogOfMantissa);
3113 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3114 // For floating-point precision of 12:
3120 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3122 // error 0.000061011436, which is 14 bits
3123 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3124 getF32Constant(DAG, 0xbd67b6d6));
3125 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3126 getF32Constant(DAG, 0x3ee4f4b8));
3127 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3128 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3129 getF32Constant(DAG, 0x3fbc278b));
3130 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3131 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3132 getF32Constant(DAG, 0x40348e95));
3133 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3134 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3135 getF32Constant(DAG, 0x3fdef31a));
3137 result = DAG.getNode(ISD::FADD, dl,
3138 MVT::f32, LogOfExponent, LogOfMantissa);
3139 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3140 // For floating-point precision of 18:
3148 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3150 // error 0.0000023660568, which is better than 18 bits
3151 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3152 getF32Constant(DAG, 0xbc91e5ac));
3153 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3154 getF32Constant(DAG, 0x3e4350aa));
3155 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3156 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3157 getF32Constant(DAG, 0x3f60d3e3));
3158 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3159 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3160 getF32Constant(DAG, 0x4011cdf0));
3161 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3162 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3163 getF32Constant(DAG, 0x406cfd1c));
3164 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3165 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3166 getF32Constant(DAG, 0x408797cb));
3167 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3168 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3169 getF32Constant(DAG, 0x4006dcab));
3171 result = DAG.getNode(ISD::FADD, dl,
3172 MVT::f32, LogOfExponent, LogOfMantissa);
3175 // No special expansion.
3176 result = DAG.getNode(ISD::FLOG, dl,
3177 getValue(I.getOperand(1)).getValueType(),
3178 getValue(I.getOperand(1)));
3181 setValue(&I, result);
3184 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3185 /// limited-precision mode.
3187 SelectionDAGBuilder::visitLog2(CallInst &I) {
3189 DebugLoc dl = getCurDebugLoc();
3191 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3192 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3193 SDValue Op = getValue(I.getOperand(1));
3194 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3196 // Get the exponent.
3197 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3199 // Get the significand and build it into a floating-point number with
3201 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3203 // Different possible minimax approximations of significand in
3204 // floating-point for various degrees of accuracy over [1,2].
3205 if (LimitFloatPrecision <= 6) {
3206 // For floating-point precision of 6:
3208 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3210 // error 0.0049451742, which is more than 7 bits
3211 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3212 getF32Constant(DAG, 0xbeb08fe0));
3213 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3214 getF32Constant(DAG, 0x40019463));
3215 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3216 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3217 getF32Constant(DAG, 0x3fd6633d));
3219 result = DAG.getNode(ISD::FADD, dl,
3220 MVT::f32, LogOfExponent, Log2ofMantissa);
3221 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3222 // For floating-point precision of 12:
3228 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3230 // error 0.0000876136000, which is better than 13 bits
3231 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3232 getF32Constant(DAG, 0xbda7262e));
3233 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3234 getF32Constant(DAG, 0x3f25280b));
3235 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3236 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3237 getF32Constant(DAG, 0x4007b923));
3238 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3239 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3240 getF32Constant(DAG, 0x40823e2f));
3241 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3242 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3243 getF32Constant(DAG, 0x4020d29c));
3245 result = DAG.getNode(ISD::FADD, dl,
3246 MVT::f32, LogOfExponent, Log2ofMantissa);
3247 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3248 // For floating-point precision of 18:
3257 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3259 // error 0.0000018516, which is better than 18 bits
3260 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3261 getF32Constant(DAG, 0xbcd2769e));
3262 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3263 getF32Constant(DAG, 0x3e8ce0b9));
3264 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3265 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3266 getF32Constant(DAG, 0x3fa22ae7));
3267 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3268 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3269 getF32Constant(DAG, 0x40525723));
3270 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3271 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3272 getF32Constant(DAG, 0x40aaf200));
3273 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3274 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3275 getF32Constant(DAG, 0x40c39dad));
3276 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3277 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3278 getF32Constant(DAG, 0x4042902c));
3280 result = DAG.getNode(ISD::FADD, dl,
3281 MVT::f32, LogOfExponent, Log2ofMantissa);
3284 // No special expansion.
3285 result = DAG.getNode(ISD::FLOG2, dl,
3286 getValue(I.getOperand(1)).getValueType(),
3287 getValue(I.getOperand(1)));
3290 setValue(&I, result);
3293 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3294 /// limited-precision mode.
3296 SelectionDAGBuilder::visitLog10(CallInst &I) {
3298 DebugLoc dl = getCurDebugLoc();
3300 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3301 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3302 SDValue Op = getValue(I.getOperand(1));
3303 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3305 // Scale the exponent by log10(2) [0.30102999f].
3306 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3307 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3308 getF32Constant(DAG, 0x3e9a209a));
3310 // Get the significand and build it into a floating-point number with
3312 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3314 if (LimitFloatPrecision <= 6) {
3315 // For floating-point precision of 6:
3317 // Log10ofMantissa =
3319 // (0.60948995f - 0.10380950f * x) * x;
3321 // error 0.0014886165, which is 6 bits
3322 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3323 getF32Constant(DAG, 0xbdd49a13));
3324 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3325 getF32Constant(DAG, 0x3f1c0789));
3326 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3327 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3328 getF32Constant(DAG, 0x3f011300));
3330 result = DAG.getNode(ISD::FADD, dl,
3331 MVT::f32, LogOfExponent, Log10ofMantissa);
3332 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3333 // For floating-point precision of 12:
3335 // Log10ofMantissa =
3338 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3340 // error 0.00019228036, which is better than 12 bits
3341 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3342 getF32Constant(DAG, 0x3d431f31));
3343 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3344 getF32Constant(DAG, 0x3ea21fb2));
3345 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3346 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3347 getF32Constant(DAG, 0x3f6ae232));
3348 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3349 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3350 getF32Constant(DAG, 0x3f25f7c3));
3352 result = DAG.getNode(ISD::FADD, dl,
3353 MVT::f32, LogOfExponent, Log10ofMantissa);
3354 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3355 // For floating-point precision of 18:
3357 // Log10ofMantissa =
3362 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3364 // error 0.0000037995730, which is better than 18 bits
3365 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3366 getF32Constant(DAG, 0x3c5d51ce));
3367 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3368 getF32Constant(DAG, 0x3e00685a));
3369 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3370 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3371 getF32Constant(DAG, 0x3efb6798));
3372 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3373 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3374 getF32Constant(DAG, 0x3f88d192));
3375 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3376 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3377 getF32Constant(DAG, 0x3fc4316c));
3378 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3379 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3380 getF32Constant(DAG, 0x3f57ce70));
3382 result = DAG.getNode(ISD::FADD, dl,
3383 MVT::f32, LogOfExponent, Log10ofMantissa);
3386 // No special expansion.
3387 result = DAG.getNode(ISD::FLOG10, dl,
3388 getValue(I.getOperand(1)).getValueType(),
3389 getValue(I.getOperand(1)));
3392 setValue(&I, result);
3395 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3396 /// limited-precision mode.
3398 SelectionDAGBuilder::visitExp2(CallInst &I) {
3400 DebugLoc dl = getCurDebugLoc();
3402 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3403 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3404 SDValue Op = getValue(I.getOperand(1));
3406 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3408 // FractionalPartOfX = x - (float)IntegerPartOfX;
3409 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3410 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3412 // IntegerPartOfX <<= 23;
3413 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3414 DAG.getConstant(23, TLI.getPointerTy()));
3416 if (LimitFloatPrecision <= 6) {
3417 // For floating-point precision of 6:
3419 // TwoToFractionalPartOfX =
3421 // (0.735607626f + 0.252464424f * x) * x;
3423 // error 0.0144103317, which is 6 bits
3424 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3425 getF32Constant(DAG, 0x3e814304));
3426 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3427 getF32Constant(DAG, 0x3f3c50c8));
3428 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3429 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3430 getF32Constant(DAG, 0x3f7f5e7e));
3431 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3432 SDValue TwoToFractionalPartOfX =
3433 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3435 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3436 MVT::f32, TwoToFractionalPartOfX);
3437 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3438 // For floating-point precision of 12:
3440 // TwoToFractionalPartOfX =
3443 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3445 // error 0.000107046256, which is 13 to 14 bits
3446 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3447 getF32Constant(DAG, 0x3da235e3));
3448 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3449 getF32Constant(DAG, 0x3e65b8f3));
3450 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3451 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3452 getF32Constant(DAG, 0x3f324b07));
3453 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3454 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3455 getF32Constant(DAG, 0x3f7ff8fd));
3456 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3457 SDValue TwoToFractionalPartOfX =
3458 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3460 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3461 MVT::f32, TwoToFractionalPartOfX);
3462 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3463 // For floating-point precision of 18:
3465 // TwoToFractionalPartOfX =
3469 // (0.554906021e-1f +
3470 // (0.961591928e-2f +
3471 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3472 // error 2.47208000*10^(-7), which is better than 18 bits
3473 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3474 getF32Constant(DAG, 0x3924b03e));
3475 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3476 getF32Constant(DAG, 0x3ab24b87));
3477 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3478 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3479 getF32Constant(DAG, 0x3c1d8c17));
3480 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3481 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3482 getF32Constant(DAG, 0x3d634a1d));
3483 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3484 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3485 getF32Constant(DAG, 0x3e75fe14));
3486 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3487 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3488 getF32Constant(DAG, 0x3f317234));
3489 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3490 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3491 getF32Constant(DAG, 0x3f800000));
3492 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3493 SDValue TwoToFractionalPartOfX =
3494 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3496 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3497 MVT::f32, TwoToFractionalPartOfX);
3500 // No special expansion.
3501 result = DAG.getNode(ISD::FEXP2, dl,
3502 getValue(I.getOperand(1)).getValueType(),
3503 getValue(I.getOperand(1)));
3506 setValue(&I, result);
3509 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3510 /// limited-precision mode with x == 10.0f.
3512 SelectionDAGBuilder::visitPow(CallInst &I) {
3514 Value *Val = I.getOperand(1);
3515 DebugLoc dl = getCurDebugLoc();
3516 bool IsExp10 = false;
3518 if (getValue(Val).getValueType() == MVT::f32 &&
3519 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3520 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3521 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3522 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3524 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3529 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3530 SDValue Op = getValue(I.getOperand(2));
3532 // Put the exponent in the right bit position for later addition to the
3535 // #define LOG2OF10 3.3219281f
3536 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3537 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3538 getF32Constant(DAG, 0x40549a78));
3539 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3541 // FractionalPartOfX = x - (float)IntegerPartOfX;
3542 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3543 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3545 // IntegerPartOfX <<= 23;
3546 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3547 DAG.getConstant(23, TLI.getPointerTy()));
3549 if (LimitFloatPrecision <= 6) {
3550 // For floating-point precision of 6:
3552 // twoToFractionalPartOfX =
3554 // (0.735607626f + 0.252464424f * x) * x;
3556 // error 0.0144103317, which is 6 bits
3557 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3558 getF32Constant(DAG, 0x3e814304));
3559 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3560 getF32Constant(DAG, 0x3f3c50c8));
3561 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3562 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3563 getF32Constant(DAG, 0x3f7f5e7e));
3564 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3565 SDValue TwoToFractionalPartOfX =
3566 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3568 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3569 MVT::f32, TwoToFractionalPartOfX);
3570 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3571 // For floating-point precision of 12:
3573 // TwoToFractionalPartOfX =
3576 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3578 // error 0.000107046256, which is 13 to 14 bits
3579 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3580 getF32Constant(DAG, 0x3da235e3));
3581 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3582 getF32Constant(DAG, 0x3e65b8f3));
3583 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3584 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3585 getF32Constant(DAG, 0x3f324b07));
3586 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3587 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3588 getF32Constant(DAG, 0x3f7ff8fd));
3589 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3590 SDValue TwoToFractionalPartOfX =
3591 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3593 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3594 MVT::f32, TwoToFractionalPartOfX);
3595 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3596 // For floating-point precision of 18:
3598 // TwoToFractionalPartOfX =
3602 // (0.554906021e-1f +
3603 // (0.961591928e-2f +
3604 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3605 // error 2.47208000*10^(-7), which is better than 18 bits
3606 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3607 getF32Constant(DAG, 0x3924b03e));
3608 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3609 getF32Constant(DAG, 0x3ab24b87));
3610 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3611 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3612 getF32Constant(DAG, 0x3c1d8c17));
3613 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3614 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3615 getF32Constant(DAG, 0x3d634a1d));
3616 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3617 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3618 getF32Constant(DAG, 0x3e75fe14));
3619 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3620 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3621 getF32Constant(DAG, 0x3f317234));
3622 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3623 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3624 getF32Constant(DAG, 0x3f800000));
3625 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3626 SDValue TwoToFractionalPartOfX =
3627 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3629 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3630 MVT::f32, TwoToFractionalPartOfX);
3633 // No special expansion.
3634 result = DAG.getNode(ISD::FPOW, dl,
3635 getValue(I.getOperand(1)).getValueType(),
3636 getValue(I.getOperand(1)),
3637 getValue(I.getOperand(2)));
3640 setValue(&I, result);
3644 /// ExpandPowI - Expand a llvm.powi intrinsic.
3645 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3646 SelectionDAG &DAG) {
3647 // If RHS is a constant, we can expand this out to a multiplication tree,
3648 // otherwise we end up lowering to a call to __powidf2 (for example). When
3649 // optimizing for size, we only want to do this if the expansion would produce
3650 // a small number of multiplies, otherwise we do the full expansion.
3651 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3652 // Get the exponent as a positive value.
3653 unsigned Val = RHSC->getSExtValue();
3654 if ((int)Val < 0) Val = -Val;
3656 // powi(x, 0) -> 1.0
3658 return DAG.getConstantFP(1.0, LHS.getValueType());
3660 Function *F = DAG.getMachineFunction().getFunction();
3661 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3662 // If optimizing for size, don't insert too many multiplies. This
3663 // inserts up to 5 multiplies.
3664 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3665 // We use the simple binary decomposition method to generate the multiply
3666 // sequence. There are more optimal ways to do this (for example,
3667 // powi(x,15) generates one more multiply than it should), but this has
3668 // the benefit of being both really simple and much better than a libcall.
3669 SDValue Res; // Logically starts equal to 1.0
3670 SDValue CurSquare = LHS;
3674 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3676 Res = CurSquare; // 1.0*CurSquare.
3679 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3680 CurSquare, CurSquare);
3684 // If the original was negative, invert the result, producing 1/(x*x*x).
3685 if (RHSC->getSExtValue() < 0)
3686 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3687 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3692 // Otherwise, expand to a libcall.
3693 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3697 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3698 /// we want to emit this as a call to a named external function, return the name
3699 /// otherwise lower it and return null.
3701 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3702 DebugLoc dl = getCurDebugLoc();
3705 switch (Intrinsic) {
3707 // By default, turn this into a target intrinsic node.
3708 visitTargetIntrinsic(I, Intrinsic);
3710 case Intrinsic::vastart: visitVAStart(I); return 0;
3711 case Intrinsic::vaend: visitVAEnd(I); return 0;
3712 case Intrinsic::vacopy: visitVACopy(I); return 0;
3713 case Intrinsic::returnaddress:
3714 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3715 getValue(I.getOperand(1))));
3717 case Intrinsic::frameaddress:
3718 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3719 getValue(I.getOperand(1))));
3721 case Intrinsic::setjmp:
3722 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3723 case Intrinsic::longjmp:
3724 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3725 case Intrinsic::memcpy: {
3726 SDValue Op1 = getValue(I.getOperand(1));
3727 SDValue Op2 = getValue(I.getOperand(2));
3728 SDValue Op3 = getValue(I.getOperand(3));
3729 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3730 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3731 I.getOperand(1), 0, I.getOperand(2), 0));
3734 case Intrinsic::memset: {
3735 SDValue Op1 = getValue(I.getOperand(1));
3736 SDValue Op2 = getValue(I.getOperand(2));
3737 SDValue Op3 = getValue(I.getOperand(3));
3738 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3739 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3740 I.getOperand(1), 0));
3743 case Intrinsic::memmove: {
3744 SDValue Op1 = getValue(I.getOperand(1));
3745 SDValue Op2 = getValue(I.getOperand(2));
3746 SDValue Op3 = getValue(I.getOperand(3));
3747 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3749 // If the source and destination are known to not be aliases, we can
3750 // lower memmove as memcpy.
3751 uint64_t Size = -1ULL;
3752 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3753 Size = C->getZExtValue();
3754 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3755 AliasAnalysis::NoAlias) {
3756 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3757 I.getOperand(1), 0, I.getOperand(2), 0));
3761 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3762 I.getOperand(1), 0, I.getOperand(2), 0));
3765 case Intrinsic::dbg_declare: {
3766 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3767 // The real handling of this intrinsic is in FastISel.
3768 if (OptLevel != CodeGenOpt::None)
3769 // FIXME: Variable debug info is not supported here.
3771 DwarfWriter *DW = DAG.getDwarfWriter();
3774 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3775 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3778 MDNode *Variable = DI.getVariable();
3779 Value *Address = DI.getAddress();
3782 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3783 Address = BCI->getOperand(0);
3784 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3785 // Don't handle byval struct arguments or VLAs, for example.
3788 DenseMap<const AllocaInst*, int>::iterator SI =
3789 FuncInfo.StaticAllocaMap.find(AI);
3790 if (SI == FuncInfo.StaticAllocaMap.end())
3792 int FI = SI->second;
3794 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3795 if (MDNode *Dbg = DI.getMetadata("dbg"))
3796 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3799 case Intrinsic::dbg_value: {
3800 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3801 // The real handling of this intrinsic is in FastISel.
3802 if (OptLevel != CodeGenOpt::None)
3803 // FIXME: Variable debug info is not supported here.
3805 DwarfWriter *DW = DAG.getDwarfWriter();
3808 DbgValueInst &DI = cast<DbgValueInst>(I);
3809 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3812 MDNode *Variable = DI.getVariable();
3813 Value *V = DI.getValue();
3816 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3817 V = BCI->getOperand(0);
3818 AllocaInst *AI = dyn_cast<AllocaInst>(V);
3819 // Don't handle byval struct arguments or VLAs, for example.
3822 DenseMap<const AllocaInst*, int>::iterator SI =
3823 FuncInfo.StaticAllocaMap.find(AI);
3824 if (SI == FuncInfo.StaticAllocaMap.end())
3826 int FI = SI->second;
3827 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3828 if (MDNode *Dbg = DI.getMetadata("dbg"))
3829 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3832 case Intrinsic::eh_exception: {
3833 // Insert the EXCEPTIONADDR instruction.
3834 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3835 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3837 Ops[0] = DAG.getRoot();
3838 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3840 DAG.setRoot(Op.getValue(1));
3844 case Intrinsic::eh_selector: {
3845 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3847 if (CurMBB->isLandingPad())
3848 AddCatchInfo(I, MMI, CurMBB);
3851 FuncInfo.CatchInfoLost.insert(&I);
3853 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3854 unsigned Reg = TLI.getExceptionSelectorRegister();
3855 if (Reg) CurMBB->addLiveIn(Reg);
3858 // Insert the EHSELECTION instruction.
3859 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3861 Ops[0] = getValue(I.getOperand(1));
3863 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3864 DAG.setRoot(Op.getValue(1));
3865 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
3869 case Intrinsic::eh_typeid_for: {
3870 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3873 // Find the type id for the given typeinfo.
3874 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3875 unsigned TypeID = MMI->getTypeIDFor(GV);
3876 Res = DAG.getConstant(TypeID, MVT::i32);
3878 // Return something different to eh_selector.
3879 Res = DAG.getConstant(1, MVT::i32);
3886 case Intrinsic::eh_return_i32:
3887 case Intrinsic::eh_return_i64:
3888 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3889 MMI->setCallsEHReturn(true);
3890 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3893 getValue(I.getOperand(1)),
3894 getValue(I.getOperand(2))));
3896 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3900 case Intrinsic::eh_unwind_init:
3901 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3902 MMI->setCallsUnwindInit(true);
3905 case Intrinsic::eh_dwarf_cfa: {
3906 EVT VT = getValue(I.getOperand(1)).getValueType();
3907 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3908 TLI.getPointerTy());
3909 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3911 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
3912 TLI.getPointerTy()),
3914 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
3916 DAG.getConstant(0, TLI.getPointerTy()));
3917 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3921 case Intrinsic::eh_sjlj_callsite: {
3922 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3923 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3924 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3925 assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!");
3927 MMI->setCurrentCallSite(CI->getZExtValue());
3931 case Intrinsic::convertff:
3932 case Intrinsic::convertfsi:
3933 case Intrinsic::convertfui:
3934 case Intrinsic::convertsif:
3935 case Intrinsic::convertuif:
3936 case Intrinsic::convertss:
3937 case Intrinsic::convertsu:
3938 case Intrinsic::convertus:
3939 case Intrinsic::convertuu: {
3940 ISD::CvtCode Code = ISD::CVT_INVALID;
3941 switch (Intrinsic) {
3942 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3943 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3944 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3945 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3946 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3947 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3948 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3949 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3950 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3952 EVT DestVT = TLI.getValueType(I.getType());
3953 Value *Op1 = I.getOperand(1);
3954 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3955 DAG.getValueType(DestVT),
3956 DAG.getValueType(getValue(Op1).getValueType()),
3957 getValue(I.getOperand(2)),
3958 getValue(I.getOperand(3)),
3963 case Intrinsic::sqrt:
3964 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3965 getValue(I.getOperand(1)).getValueType(),
3966 getValue(I.getOperand(1))));
3968 case Intrinsic::powi:
3969 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3970 getValue(I.getOperand(2)), DAG));
3972 case Intrinsic::sin:
3973 setValue(&I, DAG.getNode(ISD::FSIN, dl,
3974 getValue(I.getOperand(1)).getValueType(),
3975 getValue(I.getOperand(1))));
3977 case Intrinsic::cos:
3978 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3979 getValue(I.getOperand(1)).getValueType(),
3980 getValue(I.getOperand(1))));
3982 case Intrinsic::log:
3985 case Intrinsic::log2:
3988 case Intrinsic::log10:
3991 case Intrinsic::exp:
3994 case Intrinsic::exp2:
3997 case Intrinsic::pow:
4000 case Intrinsic::pcmarker: {
4001 SDValue Tmp = getValue(I.getOperand(1));
4002 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4005 case Intrinsic::readcyclecounter: {
4006 SDValue Op = getRoot();
4007 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4008 DAG.getVTList(MVT::i64, MVT::Other),
4011 DAG.setRoot(Res.getValue(1));
4014 case Intrinsic::bswap:
4015 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4016 getValue(I.getOperand(1)).getValueType(),
4017 getValue(I.getOperand(1))));
4019 case Intrinsic::cttz: {
4020 SDValue Arg = getValue(I.getOperand(1));
4021 EVT Ty = Arg.getValueType();
4022 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4025 case Intrinsic::ctlz: {
4026 SDValue Arg = getValue(I.getOperand(1));
4027 EVT Ty = Arg.getValueType();
4028 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4031 case Intrinsic::ctpop: {
4032 SDValue Arg = getValue(I.getOperand(1));
4033 EVT Ty = Arg.getValueType();
4034 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4037 case Intrinsic::stacksave: {
4038 SDValue Op = getRoot();
4039 Res = DAG.getNode(ISD::STACKSAVE, dl,
4040 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4042 DAG.setRoot(Res.getValue(1));
4045 case Intrinsic::stackrestore: {
4046 Res = getValue(I.getOperand(1));
4047 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4050 case Intrinsic::stackprotector: {
4051 // Emit code into the DAG to store the stack guard onto the stack.
4052 MachineFunction &MF = DAG.getMachineFunction();
4053 MachineFrameInfo *MFI = MF.getFrameInfo();
4054 EVT PtrTy = TLI.getPointerTy();
4056 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4057 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4059 int FI = FuncInfo.StaticAllocaMap[Slot];
4060 MFI->setStackProtectorIndex(FI);
4062 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4064 // Store the stack protector onto the stack.
4065 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4066 PseudoSourceValue::getFixedStack(FI),
4072 case Intrinsic::objectsize: {
4073 // If we don't know by now, we're never going to know.
4074 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4076 assert(CI && "Non-constant type in __builtin_object_size?");
4078 SDValue Arg = getValue(I.getOperand(0));
4079 EVT Ty = Arg.getValueType();
4081 if (CI->getZExtValue() == 0)
4082 Res = DAG.getConstant(-1ULL, Ty);
4084 Res = DAG.getConstant(0, Ty);
4089 case Intrinsic::var_annotation:
4090 // Discard annotate attributes
4093 case Intrinsic::init_trampoline: {
4094 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4098 Ops[1] = getValue(I.getOperand(1));
4099 Ops[2] = getValue(I.getOperand(2));
4100 Ops[3] = getValue(I.getOperand(3));
4101 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4102 Ops[5] = DAG.getSrcValue(F);
4104 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4105 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4109 DAG.setRoot(Res.getValue(1));
4112 case Intrinsic::gcroot:
4114 Value *Alloca = I.getOperand(1);
4115 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4117 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4118 GFI->addStackRoot(FI->getIndex(), TypeMap);
4121 case Intrinsic::gcread:
4122 case Intrinsic::gcwrite:
4123 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4125 case Intrinsic::flt_rounds:
4126 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4128 case Intrinsic::trap:
4129 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4131 case Intrinsic::uadd_with_overflow:
4132 return implVisitAluOverflow(I, ISD::UADDO);
4133 case Intrinsic::sadd_with_overflow:
4134 return implVisitAluOverflow(I, ISD::SADDO);
4135 case Intrinsic::usub_with_overflow:
4136 return implVisitAluOverflow(I, ISD::USUBO);
4137 case Intrinsic::ssub_with_overflow:
4138 return implVisitAluOverflow(I, ISD::SSUBO);
4139 case Intrinsic::umul_with_overflow:
4140 return implVisitAluOverflow(I, ISD::UMULO);
4141 case Intrinsic::smul_with_overflow:
4142 return implVisitAluOverflow(I, ISD::SMULO);
4144 case Intrinsic::prefetch: {
4147 Ops[1] = getValue(I.getOperand(1));
4148 Ops[2] = getValue(I.getOperand(2));
4149 Ops[3] = getValue(I.getOperand(3));
4150 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4154 case Intrinsic::memory_barrier: {
4157 for (int x = 1; x < 6; ++x)
4158 Ops[x] = getValue(I.getOperand(x));
4160 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4163 case Intrinsic::atomic_cmp_swap: {
4164 SDValue Root = getRoot();
4166 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4167 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4169 getValue(I.getOperand(1)),
4170 getValue(I.getOperand(2)),
4171 getValue(I.getOperand(3)),
4174 DAG.setRoot(L.getValue(1));
4177 case Intrinsic::atomic_load_add:
4178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4179 case Intrinsic::atomic_load_sub:
4180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4181 case Intrinsic::atomic_load_or:
4182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4183 case Intrinsic::atomic_load_xor:
4184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4185 case Intrinsic::atomic_load_and:
4186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4187 case Intrinsic::atomic_load_nand:
4188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4189 case Intrinsic::atomic_load_max:
4190 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4191 case Intrinsic::atomic_load_min:
4192 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4193 case Intrinsic::atomic_load_umin:
4194 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4195 case Intrinsic::atomic_load_umax:
4196 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4197 case Intrinsic::atomic_swap:
4198 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4200 case Intrinsic::invariant_start:
4201 case Intrinsic::lifetime_start:
4202 // Discard region information.
4203 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4205 case Intrinsic::invariant_end:
4206 case Intrinsic::lifetime_end:
4207 // Discard region information.
4212 /// Test if the given instruction is in a position to be optimized
4213 /// with a tail-call. This roughly means that it's in a block with
4214 /// a return and there's nothing that needs to be scheduled
4215 /// between it and the return.
4217 /// This function only tests target-independent requirements.
4219 isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
4220 const TargetLowering &TLI) {
4221 const Instruction *I = CS.getInstruction();
4222 const BasicBlock *ExitBB = I->getParent();
4223 const TerminatorInst *Term = ExitBB->getTerminator();
4224 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4225 const Function *F = ExitBB->getParent();
4227 // The block must end in a return statement or unreachable.
4229 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4230 // an unreachable, for now. The way tailcall optimization is currently
4231 // implemented means it will add an epilogue followed by a jump. That is
4232 // not profitable. Also, if the callee is a special function (e.g.
4233 // longjmp on x86), it can end up causing miscompilation that has not
4234 // been fully understood.
4236 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
4238 // If I will have a chain, make sure no other instruction that will have a
4239 // chain interposes between I and the return.
4240 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4241 !I->isSafeToSpeculativelyExecute())
4242 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4246 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4247 !BBI->isSafeToSpeculativelyExecute())
4251 // If the block ends with a void return or unreachable, it doesn't matter
4252 // what the call's return type is.
4253 if (!Ret || Ret->getNumOperands() == 0) return true;
4255 // If the return value is undef, it doesn't matter what the call's
4257 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4259 // Conservatively require the attributes of the call to match those of
4260 // the return. Ignore noalias because it doesn't affect the call sequence.
4261 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4262 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4265 // It's not safe to eliminate the sign / zero extension of the return value.
4266 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4269 // Otherwise, make sure the unmodified return value of I is the return value.
4270 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4271 U = dyn_cast<Instruction>(U->getOperand(0))) {
4274 if (!U->hasOneUse())
4278 // Check for a truly no-op truncate.
4279 if (isa<TruncInst>(U) &&
4280 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4282 // Check for a truly no-op bitcast.
4283 if (isa<BitCastInst>(U) &&
4284 (U->getOperand(0)->getType() == U->getType() ||
4285 (isa<PointerType>(U->getOperand(0)->getType()) &&
4286 isa<PointerType>(U->getType()))))
4288 // Otherwise it's not a true no-op.
4295 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4297 MachineBasicBlock *LandingPad) {
4298 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4299 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4300 const Type *RetTy = FTy->getReturnType();
4301 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4302 unsigned BeginLabel = 0, EndLabel = 0;
4304 TargetLowering::ArgListTy Args;
4305 TargetLowering::ArgListEntry Entry;
4306 Args.reserve(CS.arg_size());
4308 // Check whether the function can return without sret-demotion.
4309 SmallVector<EVT, 4> OutVTs;
4310 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4311 SmallVector<uint64_t, 4> Offsets;
4312 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4313 OutVTs, OutsFlags, TLI, &Offsets);
4315 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4316 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4318 SDValue DemoteStackSlot;
4320 if (!CanLowerReturn) {
4321 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4322 FTy->getReturnType());
4323 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4324 FTy->getReturnType());
4325 MachineFunction &MF = DAG.getMachineFunction();
4326 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4327 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4329 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4330 Entry.Node = DemoteStackSlot;
4331 Entry.Ty = StackSlotPtrType;
4332 Entry.isSExt = false;
4333 Entry.isZExt = false;
4334 Entry.isInReg = false;
4335 Entry.isSRet = true;
4336 Entry.isNest = false;
4337 Entry.isByVal = false;
4338 Entry.Alignment = Align;
4339 Args.push_back(Entry);
4340 RetTy = Type::getVoidTy(FTy->getContext());
4343 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4345 SDValue ArgNode = getValue(*i);
4346 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4348 unsigned attrInd = i - CS.arg_begin() + 1;
4349 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4350 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4351 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4352 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4353 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4354 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4355 Entry.Alignment = CS.getParamAlignment(attrInd);
4356 Args.push_back(Entry);
4359 if (LandingPad && MMI) {
4360 // Insert a label before the invoke call to mark the try range. This can be
4361 // used to detect deletion of the invoke via the MachineModuleInfo.
4362 BeginLabel = MMI->NextLabelID();
4364 // For SjLj, keep track of which landing pads go with which invokes
4365 // so as to maintain the ordering of pads in the LSDA.
4366 unsigned CallSiteIndex = MMI->getCurrentCallSite();
4367 if (CallSiteIndex) {
4368 MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4369 // Now that the call site is handled, stop tracking it.
4370 MMI->setCurrentCallSite(0);
4373 // Both PendingLoads and PendingExports must be flushed here;
4374 // this call might not return.
4376 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4377 getControlRoot(), BeginLabel));
4380 // Check if target-independent constraints permit a tail call here.
4381 // Target-dependent constraints are checked within TLI.LowerCallTo.
4383 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4386 std::pair<SDValue,SDValue> Result =
4387 TLI.LowerCallTo(getRoot(), RetTy,
4388 CS.paramHasAttr(0, Attribute::SExt),
4389 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4390 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4391 CS.getCallingConv(),
4393 !CS.getInstruction()->use_empty(),
4394 Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder);
4395 assert((isTailCall || Result.second.getNode()) &&
4396 "Non-null chain expected with non-tail call!");
4397 assert((Result.second.getNode() || !Result.first.getNode()) &&
4398 "Null value expected with tail call!");
4399 if (Result.first.getNode()) {
4400 setValue(CS.getInstruction(), Result.first);
4401 } else if (!CanLowerReturn && Result.second.getNode()) {
4402 // The instruction result is the result of loading from the
4403 // hidden sret parameter.
4404 SmallVector<EVT, 1> PVTs;
4405 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4407 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4408 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4409 EVT PtrVT = PVTs[0];
4410 unsigned NumValues = OutVTs.size();
4411 SmallVector<SDValue, 4> Values(NumValues);
4412 SmallVector<SDValue, 4> Chains(NumValues);
4414 for (unsigned i = 0; i < NumValues; ++i) {
4415 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4417 DAG.getConstant(Offsets[i], PtrVT));
4418 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4419 Add, NULL, Offsets[i], false, 1);
4421 Chains[i] = L.getValue(1);
4424 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4425 MVT::Other, &Chains[0], NumValues);
4426 PendingLoads.push_back(Chain);
4428 // Collect the legal value parts into potentially illegal values
4429 // that correspond to the original function's return values.
4430 SmallVector<EVT, 4> RetTys;
4431 RetTy = FTy->getReturnType();
4432 ComputeValueVTs(TLI, RetTy, RetTys);
4433 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4434 SmallVector<SDValue, 4> ReturnValues;
4435 unsigned CurReg = 0;
4436 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4438 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4439 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4441 SDValue ReturnValue =
4442 getCopyFromParts(DAG, getCurDebugLoc(), SDNodeOrder, &Values[CurReg], NumRegs,
4443 RegisterVT, VT, AssertOp);
4444 ReturnValues.push_back(ReturnValue);
4448 setValue(CS.getInstruction(),
4449 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4450 DAG.getVTList(&RetTys[0], RetTys.size()),
4451 &ReturnValues[0], ReturnValues.size()));
4455 // As a special case, a null chain means that a tail call has been emitted and
4456 // the DAG root is already updated.
4457 if (Result.second.getNode())
4458 DAG.setRoot(Result.second);
4462 if (LandingPad && MMI) {
4463 // Insert a label at the end of the invoke call to mark the try range. This
4464 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4465 EndLabel = MMI->NextLabelID();
4466 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4467 getRoot(), EndLabel));
4469 // Inform MachineModuleInfo of range.
4470 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4474 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4475 /// value is equal or not-equal to zero.
4476 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
4477 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
4479 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4480 if (IC->isEquality())
4481 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4482 if (C->isNullValue())
4484 // Unknown instruction.
4490 static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
4491 SelectionDAGBuilder &Builder) {
4493 // Check to see if this load can be trivially constant folded, e.g. if the
4494 // input is from a string literal.
4495 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4496 // Cast pointer to the type we really want to load.
4497 LoadInput = ConstantExpr::getBitCast(LoadInput,
4498 PointerType::getUnqual(LoadTy));
4500 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
4501 return Builder.getValue(LoadCst);
4504 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4505 // still constant memory, the input chain can be the entry node.
4507 bool ConstantMemory = false;
4509 // Do not serialize (non-volatile) loads of constant memory with anything.
4510 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4511 Root = Builder.DAG.getEntryNode();
4512 ConstantMemory = true;
4514 // Do not serialize non-volatile loads against each other.
4515 Root = Builder.DAG.getRoot();
4518 SDValue Ptr = Builder.getValue(PtrVal);
4519 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4520 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4521 false /*volatile*/, 1 /* align=1 */);
4523 if (!ConstantMemory)
4524 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4529 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4530 /// If so, return true and lower it, otherwise return false and it will be
4531 /// lowered like a normal call.
4532 bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
4533 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4534 if (I.getNumOperands() != 4)
4537 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
4538 if (!isa<PointerType>(LHS->getType()) || !isa<PointerType>(RHS->getType()) ||
4539 !isa<IntegerType>(I.getOperand(3)->getType()) ||
4540 !isa<IntegerType>(I.getType()))
4543 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
4545 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4546 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
4547 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4548 bool ActuallyDoIt = true;
4551 switch (Size->getZExtValue()) {
4553 LoadVT = MVT::Other;
4555 ActuallyDoIt = false;
4559 LoadTy = Type::getInt16Ty(Size->getContext());
4563 LoadTy = Type::getInt32Ty(Size->getContext());
4567 LoadTy = Type::getInt64Ty(Size->getContext());
4571 LoadVT = MVT::v4i32;
4572 LoadTy = Type::getInt32Ty(Size->getContext());
4573 LoadTy = VectorType::get(LoadTy, 4);
4578 // This turns into unaligned loads. We only do this if the target natively
4579 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4580 // we'll only produce a small number of byte loads.
4582 // Require that we can find a legal MVT, and only do this if the target
4583 // supports unaligned loads of that type. Expanding into byte loads would
4585 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4586 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4587 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4588 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4589 ActuallyDoIt = false;
4593 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4594 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
4596 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4598 EVT CallVT = TLI.getValueType(I.getType(), true);
4599 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4609 void SelectionDAGBuilder::visitCall(CallInst &I) {
4610 const char *RenameFn = 0;
4611 if (Function *F = I.getCalledFunction()) {
4612 if (F->isDeclaration()) {
4613 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4615 if (unsigned IID = II->getIntrinsicID(F)) {
4616 RenameFn = visitIntrinsicCall(I, IID);
4621 if (unsigned IID = F->getIntrinsicID()) {
4622 RenameFn = visitIntrinsicCall(I, IID);
4628 // Check for well-known libc/libm calls. If the function is internal, it
4629 // can't be a library call.
4630 if (!F->hasLocalLinkage() && F->hasName()) {
4631 StringRef Name = F->getName();
4632 if (Name == "copysign" || Name == "copysignf") {
4633 if (I.getNumOperands() == 3 && // Basic sanity checks.
4634 I.getOperand(1)->getType()->isFloatingPointTy() &&
4635 I.getType() == I.getOperand(1)->getType() &&
4636 I.getType() == I.getOperand(2)->getType()) {
4637 SDValue LHS = getValue(I.getOperand(1));
4638 SDValue RHS = getValue(I.getOperand(2));
4639 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4640 LHS.getValueType(), LHS, RHS));
4643 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4644 if (I.getNumOperands() == 2 && // Basic sanity checks.
4645 I.getOperand(1)->getType()->isFloatingPointTy() &&
4646 I.getType() == I.getOperand(1)->getType()) {
4647 SDValue Tmp = getValue(I.getOperand(1));
4648 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4649 Tmp.getValueType(), Tmp));
4652 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4653 if (I.getNumOperands() == 2 && // Basic sanity checks.
4654 I.getOperand(1)->getType()->isFloatingPointTy() &&
4655 I.getType() == I.getOperand(1)->getType() &&
4656 I.onlyReadsMemory()) {
4657 SDValue Tmp = getValue(I.getOperand(1));
4658 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4659 Tmp.getValueType(), Tmp));
4662 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4663 if (I.getNumOperands() == 2 && // Basic sanity checks.
4664 I.getOperand(1)->getType()->isFloatingPointTy() &&
4665 I.getType() == I.getOperand(1)->getType() &&
4666 I.onlyReadsMemory()) {
4667 SDValue Tmp = getValue(I.getOperand(1));
4668 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4669 Tmp.getValueType(), Tmp));
4672 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4673 if (I.getNumOperands() == 2 && // Basic sanity checks.
4674 I.getOperand(1)->getType()->isFloatingPointTy() &&
4675 I.getType() == I.getOperand(1)->getType() &&
4676 I.onlyReadsMemory()) {
4677 SDValue Tmp = getValue(I.getOperand(1));
4678 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4679 Tmp.getValueType(), Tmp));
4682 } else if (Name == "memcmp") {
4683 if (visitMemCmpCall(I))
4687 } else if (isa<InlineAsm>(I.getOperand(0))) {
4694 Callee = getValue(I.getOperand(0));
4696 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4698 // Check if we can potentially perform a tail call. More detailed checking is
4699 // be done within LowerCallTo, after more information about the call is known.
4700 LowerCallTo(&I, Callee, I.isTailCall());
4703 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4704 /// this value and returns the result as a ValueVT value. This uses
4705 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4706 /// If the Flag pointer is NULL, no flag is used.
4707 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4708 unsigned Order, SDValue &Chain,
4709 SDValue *Flag) const {
4710 // Assemble the legal parts into the final values.
4711 SmallVector<SDValue, 4> Values(ValueVTs.size());
4712 SmallVector<SDValue, 8> Parts;
4713 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4714 // Copy the legal parts from the registers.
4715 EVT ValueVT = ValueVTs[Value];
4716 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4717 EVT RegisterVT = RegVTs[Value];
4719 Parts.resize(NumRegs);
4720 for (unsigned i = 0; i != NumRegs; ++i) {
4723 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4725 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4726 *Flag = P.getValue(2);
4729 Chain = P.getValue(1);
4731 // If the source register was virtual and if we know something about it,
4732 // add an assert node.
4733 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4734 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4735 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4736 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4737 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4738 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4740 unsigned RegSize = RegisterVT.getSizeInBits();
4741 unsigned NumSignBits = LOI.NumSignBits;
4742 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4744 // FIXME: We capture more information than the dag can represent. For
4745 // now, just use the tightest assertzext/assertsext possible.
4747 EVT FromVT(MVT::Other);
4748 if (NumSignBits == RegSize)
4749 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4750 else if (NumZeroBits >= RegSize-1)
4751 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4752 else if (NumSignBits > RegSize-8)
4753 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4754 else if (NumZeroBits >= RegSize-8)
4755 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4756 else if (NumSignBits > RegSize-16)
4757 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4758 else if (NumZeroBits >= RegSize-16)
4759 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4760 else if (NumSignBits > RegSize-32)
4761 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4762 else if (NumZeroBits >= RegSize-32)
4763 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4765 if (FromVT != MVT::Other)
4766 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4767 RegisterVT, P, DAG.getValueType(FromVT));
4774 Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(),
4775 NumRegs, RegisterVT, ValueVT);
4780 return DAG.getNode(ISD::MERGE_VALUES, dl,
4781 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4782 &Values[0], ValueVTs.size());
4785 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4786 /// specified value into the registers specified by this object. This uses
4787 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4788 /// If the Flag pointer is NULL, no flag is used.
4789 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4790 unsigned Order, SDValue &Chain,
4791 SDValue *Flag) const {
4792 // Get the list of the values's legal parts.
4793 unsigned NumRegs = Regs.size();
4794 SmallVector<SDValue, 8> Parts(NumRegs);
4795 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4796 EVT ValueVT = ValueVTs[Value];
4797 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4798 EVT RegisterVT = RegVTs[Value];
4800 getCopyToParts(DAG, dl, Order,
4801 Val.getValue(Val.getResNo() + Value),
4802 &Parts[Part], NumParts, RegisterVT);
4806 // Copy the parts into the registers.
4807 SmallVector<SDValue, 8> Chains(NumRegs);
4808 for (unsigned i = 0; i != NumRegs; ++i) {
4811 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4813 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4814 *Flag = Part.getValue(1);
4817 Chains[i] = Part.getValue(0);
4820 if (NumRegs == 1 || Flag)
4821 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4822 // flagged to it. That is the CopyToReg nodes and the user are considered
4823 // a single scheduling unit. If we create a TokenFactor and return it as
4824 // chain, then the TokenFactor is both a predecessor (operand) of the
4825 // user as well as a successor (the TF operands are flagged to the user).
4826 // c1, f1 = CopyToReg
4827 // c2, f2 = CopyToReg
4828 // c3 = TokenFactor c1, c2
4831 Chain = Chains[NumRegs-1];
4833 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4836 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4837 /// operand list. This adds the code marker and includes the number of
4838 /// values added into it.
4839 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4840 bool HasMatching,unsigned MatchingIdx,
4841 SelectionDAG &DAG, unsigned Order,
4842 std::vector<SDValue> &Ops) const {
4843 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4844 unsigned Flag = Code | (Regs.size() << 3);
4846 Flag |= 0x80000000 | (MatchingIdx << 16);
4847 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
4850 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4851 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4852 EVT RegisterVT = RegVTs[Value];
4853 for (unsigned i = 0; i != NumRegs; ++i) {
4854 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4855 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4860 /// isAllocatableRegister - If the specified register is safe to allocate,
4861 /// i.e. it isn't a stack pointer or some other special register, return the
4862 /// register class for the register. Otherwise, return null.
4863 static const TargetRegisterClass *
4864 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4865 const TargetLowering &TLI,
4866 const TargetRegisterInfo *TRI) {
4867 EVT FoundVT = MVT::Other;
4868 const TargetRegisterClass *FoundRC = 0;
4869 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4870 E = TRI->regclass_end(); RCI != E; ++RCI) {
4871 EVT ThisVT = MVT::Other;
4873 const TargetRegisterClass *RC = *RCI;
4874 // If none of the value types for this register class are valid, we
4875 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4876 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4878 if (TLI.isTypeLegal(*I)) {
4879 // If we have already found this register in a different register class,
4880 // choose the one with the largest VT specified. For example, on
4881 // PowerPC, we favor f64 register classes over f32.
4882 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4889 if (ThisVT == MVT::Other) continue;
4891 // NOTE: This isn't ideal. In particular, this might allocate the
4892 // frame pointer in functions that need it (due to them not being taken
4893 // out of allocation, because a variable sized allocation hasn't been seen
4894 // yet). This is a slight code pessimization, but should still work.
4895 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4896 E = RC->allocation_order_end(MF); I != E; ++I)
4898 // We found a matching register class. Keep looking at others in case
4899 // we find one with larger registers that this physreg is also in.
4910 /// AsmOperandInfo - This contains information for each constraint that we are
4912 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4913 public TargetLowering::AsmOperandInfo {
4915 /// CallOperand - If this is the result output operand or a clobber
4916 /// this is null, otherwise it is the incoming operand to the CallInst.
4917 /// This gets modified as the asm is processed.
4918 SDValue CallOperand;
4920 /// AssignedRegs - If this is a register or register class operand, this
4921 /// contains the set of register corresponding to the operand.
4922 RegsForValue AssignedRegs;
4924 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4925 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4928 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4929 /// busy in OutputRegs/InputRegs.
4930 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4931 std::set<unsigned> &OutputRegs,
4932 std::set<unsigned> &InputRegs,
4933 const TargetRegisterInfo &TRI) const {
4935 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4936 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4939 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4940 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4944 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4945 /// corresponds to. If there is no Value* for this operand, it returns
4947 EVT getCallOperandValEVT(LLVMContext &Context,
4948 const TargetLowering &TLI,
4949 const TargetData *TD) const {
4950 if (CallOperandVal == 0) return MVT::Other;
4952 if (isa<BasicBlock>(CallOperandVal))
4953 return TLI.getPointerTy();
4955 const llvm::Type *OpTy = CallOperandVal->getType();
4957 // If this is an indirect operand, the operand is a pointer to the
4960 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4962 llvm_report_error("Indirect operand for inline asm not a pointer!");
4963 OpTy = PtrTy->getElementType();
4966 // If OpTy is not a single value, it may be a struct/union that we
4967 // can tile with integers.
4968 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4969 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4978 OpTy = IntegerType::get(Context, BitSize);
4983 return TLI.getValueType(OpTy, true);
4987 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4989 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4990 const TargetRegisterInfo &TRI) {
4991 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4993 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4994 for (; *Aliases; ++Aliases)
4995 Regs.insert(*Aliases);
4998 } // end llvm namespace.
5001 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5002 /// specified operand. We prefer to assign virtual registers, to allow the
5003 /// register allocator to handle the assignment process. However, if the asm
5004 /// uses features that we can't model on machineinstrs, we have SDISel do the
5005 /// allocation. This produces generally horrible, but correct, code.
5007 /// OpInfo describes the operand.
5008 /// Input and OutputRegs are the set of already allocated physical registers.
5010 void SelectionDAGBuilder::
5011 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5012 std::set<unsigned> &OutputRegs,
5013 std::set<unsigned> &InputRegs) {
5014 LLVMContext &Context = FuncInfo.Fn->getContext();
5016 // Compute whether this value requires an input register, an output register,
5018 bool isOutReg = false;
5019 bool isInReg = false;
5020 switch (OpInfo.Type) {
5021 case InlineAsm::isOutput:
5024 // If there is an input constraint that matches this, we need to reserve
5025 // the input register so no other inputs allocate to it.
5026 isInReg = OpInfo.hasMatchingInput();
5028 case InlineAsm::isInput:
5032 case InlineAsm::isClobber:
5039 MachineFunction &MF = DAG.getMachineFunction();
5040 SmallVector<unsigned, 4> Regs;
5042 // If this is a constraint for a single physreg, or a constraint for a
5043 // register class, find it.
5044 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5045 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5046 OpInfo.ConstraintVT);
5048 unsigned NumRegs = 1;
5049 if (OpInfo.ConstraintVT != MVT::Other) {
5050 // If this is a FP input in an integer register (or visa versa) insert a bit
5051 // cast of the input value. More generally, handle any case where the input
5052 // value disagrees with the register class we plan to stick this in.
5053 if (OpInfo.Type == InlineAsm::isInput &&
5054 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5055 // Try to convert to the first EVT that the reg class contains. If the
5056 // types are identical size, use a bitcast to convert (e.g. two differing
5058 EVT RegVT = *PhysReg.second->vt_begin();
5059 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5060 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5061 RegVT, OpInfo.CallOperand);
5062 OpInfo.ConstraintVT = RegVT;
5063 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5064 // If the input is a FP value and we want it in FP registers, do a
5065 // bitcast to the corresponding integer type. This turns an f64 value
5066 // into i64, which can be passed with two i32 values on a 32-bit
5068 RegVT = EVT::getIntegerVT(Context,
5069 OpInfo.ConstraintVT.getSizeInBits());
5070 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5071 RegVT, OpInfo.CallOperand);
5072 OpInfo.ConstraintVT = RegVT;
5076 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5080 EVT ValueVT = OpInfo.ConstraintVT;
5082 // If this is a constraint for a specific physical register, like {r17},
5084 if (unsigned AssignedReg = PhysReg.first) {
5085 const TargetRegisterClass *RC = PhysReg.second;
5086 if (OpInfo.ConstraintVT == MVT::Other)
5087 ValueVT = *RC->vt_begin();
5089 // Get the actual register value type. This is important, because the user
5090 // may have asked for (e.g.) the AX register in i32 type. We need to
5091 // remember that AX is actually i16 to get the right extension.
5092 RegVT = *RC->vt_begin();
5094 // This is a explicit reference to a physical register.
5095 Regs.push_back(AssignedReg);
5097 // If this is an expanded reference, add the rest of the regs to Regs.
5099 TargetRegisterClass::iterator I = RC->begin();
5100 for (; *I != AssignedReg; ++I)
5101 assert(I != RC->end() && "Didn't find reg!");
5103 // Already added the first reg.
5105 for (; NumRegs; --NumRegs, ++I) {
5106 assert(I != RC->end() && "Ran out of registers to allocate!");
5111 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5112 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5113 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5117 // Otherwise, if this was a reference to an LLVM register class, create vregs
5118 // for this reference.
5119 if (const TargetRegisterClass *RC = PhysReg.second) {
5120 RegVT = *RC->vt_begin();
5121 if (OpInfo.ConstraintVT == MVT::Other)
5124 // Create the appropriate number of virtual registers.
5125 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5126 for (; NumRegs; --NumRegs)
5127 Regs.push_back(RegInfo.createVirtualRegister(RC));
5129 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5133 // This is a reference to a register class that doesn't directly correspond
5134 // to an LLVM register class. Allocate NumRegs consecutive, available,
5135 // registers from the class.
5136 std::vector<unsigned> RegClassRegs
5137 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5138 OpInfo.ConstraintVT);
5140 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5141 unsigned NumAllocated = 0;
5142 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5143 unsigned Reg = RegClassRegs[i];
5144 // See if this register is available.
5145 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5146 (isInReg && InputRegs.count(Reg))) { // Already used.
5147 // Make sure we find consecutive registers.
5152 // Check to see if this register is allocatable (i.e. don't give out the
5154 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5155 if (!RC) { // Couldn't allocate this register.
5156 // Reset NumAllocated to make sure we return consecutive registers.
5161 // Okay, this register is good, we can use it.
5164 // If we allocated enough consecutive registers, succeed.
5165 if (NumAllocated == NumRegs) {
5166 unsigned RegStart = (i-NumAllocated)+1;
5167 unsigned RegEnd = i+1;
5168 // Mark all of the allocated registers used.
5169 for (unsigned i = RegStart; i != RegEnd; ++i)
5170 Regs.push_back(RegClassRegs[i]);
5172 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5173 OpInfo.ConstraintVT);
5174 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5179 // Otherwise, we couldn't allocate enough registers for this.
5182 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5183 /// processed uses a memory 'm' constraint.
5185 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5186 const TargetLowering &TLI) {
5187 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5188 InlineAsm::ConstraintInfo &CI = CInfos[i];
5189 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5190 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5191 if (CType == TargetLowering::C_Memory)
5195 // Indirect operand accesses access memory.
5203 /// visitInlineAsm - Handle a call to an InlineAsm object.
5205 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
5206 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5208 /// ConstraintOperands - Information about all of the constraints.
5209 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5211 std::set<unsigned> OutputRegs, InputRegs;
5213 // Do a prepass over the constraints, canonicalizing them, and building up the
5214 // ConstraintOperands list.
5215 std::vector<InlineAsm::ConstraintInfo>
5216 ConstraintInfos = IA->ParseConstraints();
5218 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5220 SDValue Chain, Flag;
5222 // We won't need to flush pending loads if this asm doesn't touch
5223 // memory and is nonvolatile.
5224 if (hasMemory || IA->hasSideEffects())
5227 Chain = DAG.getRoot();
5229 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5230 unsigned ResNo = 0; // ResNo - The result number of the next output.
5231 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5232 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5233 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5235 EVT OpVT = MVT::Other;
5237 // Compute the value type for each operand.
5238 switch (OpInfo.Type) {
5239 case InlineAsm::isOutput:
5240 // Indirect outputs just consume an argument.
5241 if (OpInfo.isIndirect) {
5242 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5246 // The return value of the call is this value. As such, there is no
5247 // corresponding argument.
5248 assert(!CS.getType()->isVoidTy() &&
5250 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5251 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5253 assert(ResNo == 0 && "Asm only has one result!");
5254 OpVT = TLI.getValueType(CS.getType());
5258 case InlineAsm::isInput:
5259 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5261 case InlineAsm::isClobber:
5266 // If this is an input or an indirect output, process the call argument.
5267 // BasicBlocks are labels, currently appearing only in asm's.
5268 if (OpInfo.CallOperandVal) {
5269 // Strip bitcasts, if any. This mostly comes up for functions.
5270 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5272 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5273 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5275 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5278 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5281 OpInfo.ConstraintVT = OpVT;
5284 // Second pass over the constraints: compute which constraint option to use
5285 // and assign registers to constraints that want a specific physreg.
5286 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5287 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5289 // If this is an output operand with a matching input operand, look up the
5290 // matching input. If their types mismatch, e.g. one is an integer, the
5291 // other is floating point, or their sizes are different, flag it as an
5293 if (OpInfo.hasMatchingInput()) {
5294 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5295 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5296 if ((OpInfo.ConstraintVT.isInteger() !=
5297 Input.ConstraintVT.isInteger()) ||
5298 (OpInfo.ConstraintVT.getSizeInBits() !=
5299 Input.ConstraintVT.getSizeInBits())) {
5300 llvm_report_error("Unsupported asm: input constraint"
5301 " with a matching output constraint of incompatible"
5304 Input.ConstraintVT = OpInfo.ConstraintVT;
5308 // Compute the constraint code and ConstraintType to use.
5309 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5311 // If this is a memory input, and if the operand is not indirect, do what we
5312 // need to to provide an address for the memory input.
5313 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5314 !OpInfo.isIndirect) {
5315 assert(OpInfo.Type == InlineAsm::isInput &&
5316 "Can only indirectify direct input operands!");
5318 // Memory operands really want the address of the value. If we don't have
5319 // an indirect input, put it in the constpool if we can, otherwise spill
5320 // it to a stack slot.
5322 // If the operand is a float, integer, or vector constant, spill to a
5323 // constant pool entry to get its address.
5324 Value *OpVal = OpInfo.CallOperandVal;
5325 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5326 isa<ConstantVector>(OpVal)) {
5327 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5328 TLI.getPointerTy());
5330 // Otherwise, create a stack slot and emit a store to it before the
5332 const Type *Ty = OpVal->getType();
5333 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5334 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5335 MachineFunction &MF = DAG.getMachineFunction();
5336 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5337 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5338 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5339 OpInfo.CallOperand, StackSlot, NULL, 0);
5340 OpInfo.CallOperand = StackSlot;
5343 // There is no longer a Value* corresponding to this operand.
5344 OpInfo.CallOperandVal = 0;
5346 // It is now an indirect operand.
5347 OpInfo.isIndirect = true;
5350 // If this constraint is for a specific register, allocate it before
5352 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5353 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5356 ConstraintInfos.clear();
5358 // Second pass - Loop over all of the operands, assigning virtual or physregs
5359 // to register class operands.
5360 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5361 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5363 // C_Register operands have already been allocated, Other/Memory don't need
5365 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5366 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5369 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5370 std::vector<SDValue> AsmNodeOperands;
5371 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5372 AsmNodeOperands.push_back(
5373 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5374 TLI.getPointerTy()));
5377 // Loop over all of the inputs, copying the operand values into the
5378 // appropriate registers and processing the output regs.
5379 RegsForValue RetValRegs;
5381 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5382 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5384 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5385 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5387 switch (OpInfo.Type) {
5388 case InlineAsm::isOutput: {
5389 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5390 OpInfo.ConstraintType != TargetLowering::C_Register) {
5391 // Memory output, or 'other' output (e.g. 'X' constraint).
5392 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5394 // Add information to the INLINEASM node to know about this output.
5395 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5396 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5397 TLI.getPointerTy()));
5398 AsmNodeOperands.push_back(OpInfo.CallOperand);
5402 // Otherwise, this is a register or register class output.
5404 // Copy the output from the appropriate register. Find a register that
5406 if (OpInfo.AssignedRegs.Regs.empty()) {
5407 llvm_report_error("Couldn't allocate output reg for"
5408 " constraint '" + OpInfo.ConstraintCode + "'!");
5411 // If this is an indirect operand, store through the pointer after the
5413 if (OpInfo.isIndirect) {
5414 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5415 OpInfo.CallOperandVal));
5417 // This is the result value of the call.
5418 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5419 // Concatenate this output onto the outputs list.
5420 RetValRegs.append(OpInfo.AssignedRegs);
5423 // Add information to the INLINEASM node to know that this register is
5425 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5426 6 /* EARLYCLOBBER REGDEF */ :
5434 case InlineAsm::isInput: {
5435 SDValue InOperandVal = OpInfo.CallOperand;
5437 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5438 // If this is required to match an output register we have already set,
5439 // just use its register.
5440 unsigned OperandNo = OpInfo.getMatchedOperand();
5442 // Scan until we find the definition we already emitted of this operand.
5443 // When we find it, create a RegsForValue operand.
5444 unsigned CurOp = 2; // The first operand.
5445 for (; OperandNo; --OperandNo) {
5446 // Advance to the next operand.
5448 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5449 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5450 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5451 (OpFlag & 7) == 4 /*MEM*/) &&
5452 "Skipped past definitions?");
5453 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5457 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5458 if ((OpFlag & 7) == 2 /*REGDEF*/
5459 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5460 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5461 if (OpInfo.isIndirect) {
5462 llvm_report_error("Don't know how to handle tied indirect "
5463 "register inputs yet!");
5465 RegsForValue MatchedRegs;
5466 MatchedRegs.TLI = &TLI;
5467 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5468 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5469 MatchedRegs.RegVTs.push_back(RegVT);
5470 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5471 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5473 MatchedRegs.Regs.push_back
5474 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5476 // Use the produced MatchedRegs object to
5477 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5478 SDNodeOrder, Chain, &Flag);
5479 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5480 true, OpInfo.getMatchedOperand(),
5481 DAG, SDNodeOrder, AsmNodeOperands);
5484 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5485 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5486 "Unexpected number of operands");
5487 // Add information to the INLINEASM node to know about this input.
5488 // See InlineAsm.h isUseOperandTiedToDef.
5489 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5490 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5491 TLI.getPointerTy()));
5492 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5497 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5498 assert(!OpInfo.isIndirect &&
5499 "Don't know how to handle indirect other inputs yet!");
5501 std::vector<SDValue> Ops;
5502 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5503 hasMemory, Ops, DAG);
5505 llvm_report_error("Invalid operand for inline asm"
5506 " constraint '" + OpInfo.ConstraintCode + "'!");
5509 // Add information to the INLINEASM node to know about this input.
5510 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5511 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5512 TLI.getPointerTy()));
5513 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5515 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5516 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5517 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5518 "Memory operands expect pointer values");
5520 // Add information to the INLINEASM node to know about this input.
5521 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5522 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5523 TLI.getPointerTy()));
5524 AsmNodeOperands.push_back(InOperandVal);
5528 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5529 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5530 "Unknown constraint type!");
5531 assert(!OpInfo.isIndirect &&
5532 "Don't know how to handle indirect register inputs yet!");
5534 // Copy the input into the appropriate registers.
5535 if (OpInfo.AssignedRegs.Regs.empty() ||
5536 !OpInfo.AssignedRegs.areValueTypesLegal()) {
5537 llvm_report_error("Couldn't allocate input reg for"
5538 " constraint '"+ OpInfo.ConstraintCode +"'!");
5541 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5542 SDNodeOrder, Chain, &Flag);
5544 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5549 case InlineAsm::isClobber: {
5550 // Add the clobbered value to the operand list, so that the register
5551 // allocator is aware that the physreg got clobbered.
5552 if (!OpInfo.AssignedRegs.Regs.empty())
5553 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5554 false, 0, DAG, SDNodeOrder,
5561 // Finish up input operands.
5562 AsmNodeOperands[0] = Chain;
5563 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5565 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5566 DAG.getVTList(MVT::Other, MVT::Flag),
5567 &AsmNodeOperands[0], AsmNodeOperands.size());
5568 Flag = Chain.getValue(1);
5570 // If this asm returns a register value, copy the result from that register
5571 // and set it as the value of the call.
5572 if (!RetValRegs.Regs.empty()) {
5573 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5574 SDNodeOrder, Chain, &Flag);
5576 // FIXME: Why don't we do this for inline asms with MRVs?
5577 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5578 EVT ResultType = TLI.getValueType(CS.getType());
5580 // If any of the results of the inline asm is a vector, it may have the
5581 // wrong width/num elts. This can happen for register classes that can
5582 // contain multiple different value types. The preg or vreg allocated may
5583 // not have the same VT as was expected. Convert it to the right type
5584 // with bit_convert.
5585 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5586 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5589 } else if (ResultType != Val.getValueType() &&
5590 ResultType.isInteger() && Val.getValueType().isInteger()) {
5591 // If a result value was tied to an input value, the computed result may
5592 // have a wider width than the expected result. Extract the relevant
5594 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5597 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5600 setValue(CS.getInstruction(), Val);
5601 // Don't need to use this as a chain in this case.
5602 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5606 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5608 // Process indirect outputs, first output all of the flagged copies out of
5610 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5611 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5612 Value *Ptr = IndirectStoresToEmit[i].second;
5613 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5614 SDNodeOrder, Chain, &Flag);
5615 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5619 // Emit the non-flagged stores from the physregs.
5620 SmallVector<SDValue, 8> OutChains;
5621 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5622 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5623 StoresToEmit[i].first,
5624 getValue(StoresToEmit[i].second),
5625 StoresToEmit[i].second, 0);
5626 OutChains.push_back(Val);
5629 if (!OutChains.empty())
5630 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5631 &OutChains[0], OutChains.size());
5636 void SelectionDAGBuilder::visitVAStart(CallInst &I) {
5637 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5638 MVT::Other, getRoot(),
5639 getValue(I.getOperand(1)),
5640 DAG.getSrcValue(I.getOperand(1))));
5643 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
5644 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5645 getRoot(), getValue(I.getOperand(0)),
5646 DAG.getSrcValue(I.getOperand(0)));
5648 DAG.setRoot(V.getValue(1));
5651 void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
5652 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5653 MVT::Other, getRoot(),
5654 getValue(I.getOperand(1)),
5655 DAG.getSrcValue(I.getOperand(1))));
5658 void SelectionDAGBuilder::visitVACopy(CallInst &I) {
5659 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5660 MVT::Other, getRoot(),
5661 getValue(I.getOperand(1)),
5662 getValue(I.getOperand(2)),
5663 DAG.getSrcValue(I.getOperand(1)),
5664 DAG.getSrcValue(I.getOperand(2))));
5667 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5668 /// implementation, which just calls LowerCall.
5669 /// FIXME: When all targets are
5670 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5671 std::pair<SDValue, SDValue>
5672 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5673 bool RetSExt, bool RetZExt, bool isVarArg,
5674 bool isInreg, unsigned NumFixedArgs,
5675 CallingConv::ID CallConv, bool isTailCall,
5676 bool isReturnValueUsed,
5678 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl,
5680 // Handle all of the outgoing arguments.
5681 SmallVector<ISD::OutputArg, 32> Outs;
5682 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5683 SmallVector<EVT, 4> ValueVTs;
5684 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5685 for (unsigned Value = 0, NumValues = ValueVTs.size();
5686 Value != NumValues; ++Value) {
5687 EVT VT = ValueVTs[Value];
5688 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5689 SDValue Op = SDValue(Args[i].Node.getNode(),
5690 Args[i].Node.getResNo() + Value);
5691 ISD::ArgFlagsTy Flags;
5692 unsigned OriginalAlignment =
5693 getTargetData()->getABITypeAlignment(ArgTy);
5699 if (Args[i].isInReg)
5703 if (Args[i].isByVal) {
5705 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5706 const Type *ElementTy = Ty->getElementType();
5707 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5708 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5709 // For ByVal, alignment should come from FE. BE will guess if this
5710 // info is not there but there are cases it cannot get right.
5711 if (Args[i].Alignment)
5712 FrameAlign = Args[i].Alignment;
5713 Flags.setByValAlign(FrameAlign);
5714 Flags.setByValSize(FrameSize);
5718 Flags.setOrigAlign(OriginalAlignment);
5720 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5721 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5722 SmallVector<SDValue, 4> Parts(NumParts);
5723 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5726 ExtendKind = ISD::SIGN_EXTEND;
5727 else if (Args[i].isZExt)
5728 ExtendKind = ISD::ZERO_EXTEND;
5730 getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts,
5731 PartVT, ExtendKind);
5733 for (unsigned j = 0; j != NumParts; ++j) {
5734 // if it isn't first piece, alignment must be 1
5735 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5736 if (NumParts > 1 && j == 0)
5737 MyFlags.Flags.setSplit();
5739 MyFlags.Flags.setOrigAlign(1);
5741 Outs.push_back(MyFlags);
5746 // Handle the incoming return values from the call.
5747 SmallVector<ISD::InputArg, 32> Ins;
5748 SmallVector<EVT, 4> RetTys;
5749 ComputeValueVTs(*this, RetTy, RetTys);
5750 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5752 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5753 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5754 for (unsigned i = 0; i != NumRegs; ++i) {
5755 ISD::InputArg MyFlags;
5756 MyFlags.VT = RegisterVT;
5757 MyFlags.Used = isReturnValueUsed;
5759 MyFlags.Flags.setSExt();
5761 MyFlags.Flags.setZExt();
5763 MyFlags.Flags.setInReg();
5764 Ins.push_back(MyFlags);
5768 SmallVector<SDValue, 4> InVals;
5769 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5770 Outs, Ins, dl, DAG, InVals);
5772 // Verify that the target's LowerCall behaved as expected.
5773 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5774 "LowerCall didn't return a valid chain!");
5775 assert((!isTailCall || InVals.empty()) &&
5776 "LowerCall emitted a return value for a tail call!");
5777 assert((isTailCall || InVals.size() == Ins.size()) &&
5778 "LowerCall didn't emit the correct number of values!");
5779 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5780 assert(InVals[i].getNode() &&
5781 "LowerCall emitted a null value!");
5782 assert(Ins[i].VT == InVals[i].getValueType() &&
5783 "LowerCall emitted a value with the wrong type!");
5786 // For a tail call, the return value is merely live-out and there aren't
5787 // any nodes in the DAG representing it. Return a special value to
5788 // indicate that a tail call has been emitted and no more Instructions
5789 // should be processed in the current block.
5792 return std::make_pair(SDValue(), SDValue());
5795 // Collect the legal value parts into potentially illegal values
5796 // that correspond to the original function's return values.
5797 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5799 AssertOp = ISD::AssertSext;
5801 AssertOp = ISD::AssertZext;
5802 SmallVector<SDValue, 4> ReturnValues;
5803 unsigned CurReg = 0;
5804 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5806 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5807 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5809 ReturnValues.push_back(getCopyFromParts(DAG, dl, Order, &InVals[CurReg],
5810 NumRegs, RegisterVT, VT,
5815 // For a function returning void, there is no return value. We can't create
5816 // such a node, so we just return a null return value in that case. In
5817 // that case, nothing will actualy look at the value.
5818 if (ReturnValues.empty())
5819 return std::make_pair(SDValue(), Chain);
5821 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5822 DAG.getVTList(&RetTys[0], RetTys.size()),
5823 &ReturnValues[0], ReturnValues.size());
5824 return std::make_pair(Res, Chain);
5827 void TargetLowering::LowerOperationWrapper(SDNode *N,
5828 SmallVectorImpl<SDValue> &Results,
5829 SelectionDAG &DAG) {
5830 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5832 Results.push_back(Res);
5835 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5836 llvm_unreachable("LowerOperation not implemented for this target!");
5840 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5841 SDValue Op = getValue(V);
5842 assert((Op.getOpcode() != ISD::CopyFromReg ||
5843 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5844 "Copy from a reg to the same reg!");
5845 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5847 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5848 SDValue Chain = DAG.getEntryNode();
5849 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
5850 PendingExports.push_back(Chain);
5853 #include "llvm/CodeGen/SelectionDAGISel.h"
5855 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
5856 // If this is the entry block, emit arguments.
5857 Function &F = *LLVMBB->getParent();
5858 SelectionDAG &DAG = SDB->DAG;
5859 SDValue OldRoot = DAG.getRoot();
5860 DebugLoc dl = SDB->getCurDebugLoc();
5861 const TargetData *TD = TLI.getTargetData();
5862 SmallVector<ISD::InputArg, 16> Ins;
5864 // Check whether the function can return without sret-demotion.
5865 SmallVector<EVT, 4> OutVTs;
5866 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5867 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5868 OutVTs, OutsFlags, TLI);
5869 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5871 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5872 OutVTs, OutsFlags, DAG);
5873 if (!FLI.CanLowerReturn) {
5874 // Put in an sret pointer parameter before all the other parameters.
5875 SmallVector<EVT, 1> ValueVTs;
5876 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5878 // NOTE: Assuming that a pointer will never break down to more than one VT
5880 ISD::ArgFlagsTy Flags;
5882 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5883 ISD::InputArg RetArg(Flags, RegisterVT, true);
5884 Ins.push_back(RetArg);
5887 // Set up the incoming argument description vector.
5889 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5890 I != E; ++I, ++Idx) {
5891 SmallVector<EVT, 4> ValueVTs;
5892 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5893 bool isArgValueUsed = !I->use_empty();
5894 for (unsigned Value = 0, NumValues = ValueVTs.size();
5895 Value != NumValues; ++Value) {
5896 EVT VT = ValueVTs[Value];
5897 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5898 ISD::ArgFlagsTy Flags;
5899 unsigned OriginalAlignment =
5900 TD->getABITypeAlignment(ArgTy);
5902 if (F.paramHasAttr(Idx, Attribute::ZExt))
5904 if (F.paramHasAttr(Idx, Attribute::SExt))
5906 if (F.paramHasAttr(Idx, Attribute::InReg))
5908 if (F.paramHasAttr(Idx, Attribute::StructRet))
5910 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5912 const PointerType *Ty = cast<PointerType>(I->getType());
5913 const Type *ElementTy = Ty->getElementType();
5914 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5915 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5916 // For ByVal, alignment should be passed from FE. BE will guess if
5917 // this info is not there but there are cases it cannot get right.
5918 if (F.getParamAlignment(Idx))
5919 FrameAlign = F.getParamAlignment(Idx);
5920 Flags.setByValAlign(FrameAlign);
5921 Flags.setByValSize(FrameSize);
5923 if (F.paramHasAttr(Idx, Attribute::Nest))
5925 Flags.setOrigAlign(OriginalAlignment);
5927 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5928 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5929 for (unsigned i = 0; i != NumRegs; ++i) {
5930 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5931 if (NumRegs > 1 && i == 0)
5932 MyFlags.Flags.setSplit();
5933 // if it isn't first piece, alignment must be 1
5935 MyFlags.Flags.setOrigAlign(1);
5936 Ins.push_back(MyFlags);
5941 // Call the target to set up the argument values.
5942 SmallVector<SDValue, 8> InVals;
5943 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5947 // Verify that the target's LowerFormalArguments behaved as expected.
5948 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5949 "LowerFormalArguments didn't return a valid chain!");
5950 assert(InVals.size() == Ins.size() &&
5951 "LowerFormalArguments didn't emit the correct number of values!");
5953 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5954 assert(InVals[i].getNode() &&
5955 "LowerFormalArguments emitted a null value!");
5956 assert(Ins[i].VT == InVals[i].getValueType() &&
5957 "LowerFormalArguments emitted a value with the wrong type!");
5961 // Update the DAG with the new chain value resulting from argument lowering.
5962 DAG.setRoot(NewRoot);
5964 // Set up the argument values.
5967 if (!FLI.CanLowerReturn) {
5968 // Create a virtual register for the sret pointer, and put in a copy
5969 // from the sret argument into it.
5970 SmallVector<EVT, 1> ValueVTs;
5971 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5972 EVT VT = ValueVTs[0];
5973 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5974 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5975 SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1,
5976 RegVT, VT, AssertOp);
5978 MachineFunction& MF = SDB->DAG.getMachineFunction();
5979 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5980 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5981 FLI.DemoteRegister = SRetReg;
5982 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
5984 DAG.setRoot(NewRoot);
5986 // i indexes lowered arguments. Bump it past the hidden sret argument.
5987 // Idx indexes LLVM arguments. Don't touch it.
5991 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5993 SmallVector<SDValue, 4> ArgValues;
5994 SmallVector<EVT, 4> ValueVTs;
5995 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5996 unsigned NumValues = ValueVTs.size();
5997 for (unsigned Value = 0; Value != NumValues; ++Value) {
5998 EVT VT = ValueVTs[Value];
5999 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6000 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6002 if (!I->use_empty()) {
6003 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6004 if (F.paramHasAttr(Idx, Attribute::SExt))
6005 AssertOp = ISD::AssertSext;
6006 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6007 AssertOp = ISD::AssertZext;
6009 ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i],
6010 NumParts, PartVT, VT,
6017 if (!I->use_empty()) {
6018 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6019 SDB->getCurDebugLoc());
6020 SDB->setValue(I, Res);
6022 // If this argument is live outside of the entry block, insert a copy from
6023 // whereever we got it to the vreg that other BB's will reference it as.
6024 SDB->CopyToExportRegsIfNeeded(I);
6028 assert(i == InVals.size() && "Argument register count mismatch!");
6030 // Finally, if the target has anything special to do, allow it to do so.
6031 // FIXME: this should insert code into the DAG!
6032 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
6035 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6036 /// ensure constants are generated when needed. Remember the virtual registers
6037 /// that need to be added to the Machine PHI nodes as input. We cannot just
6038 /// directly add them, because expansion might result in multiple MBB's for one
6039 /// BB. As such, the start of the BB might correspond to a different MBB than
6043 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6044 TerminatorInst *TI = LLVMBB->getTerminator();
6046 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6048 // Check successor nodes' PHI nodes that expect a constant to be available
6050 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6051 BasicBlock *SuccBB = TI->getSuccessor(succ);
6052 if (!isa<PHINode>(SuccBB->begin())) continue;
6053 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6055 // If this terminator has multiple identical successors (common for
6056 // switches), only handle each succ once.
6057 if (!SuccsHandled.insert(SuccMBB)) continue;
6059 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6062 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6063 // nodes and Machine PHI nodes, but the incoming operands have not been
6065 for (BasicBlock::iterator I = SuccBB->begin();
6066 (PN = dyn_cast<PHINode>(I)); ++I) {
6067 // Ignore dead phi's.
6068 if (PN->use_empty()) continue;
6071 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6073 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6074 unsigned &RegOut = SDB->ConstantsOut[C];
6076 RegOut = FuncInfo->CreateRegForValue(C);
6077 SDB->CopyValueToVirtualRegister(C, RegOut);
6081 Reg = FuncInfo->ValueMap[PHIOp];
6083 assert(isa<AllocaInst>(PHIOp) &&
6084 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6085 "Didn't codegen value into a register!??");
6086 Reg = FuncInfo->CreateRegForValue(PHIOp);
6087 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6091 // Remember that this register needs to added to the machine PHI node as
6092 // the input for this MBB.
6093 SmallVector<EVT, 4> ValueVTs;
6094 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6095 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6096 EVT VT = ValueVTs[vti];
6097 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6098 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6099 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6100 Reg += NumRegisters;
6104 SDB->ConstantsOut.clear();
6107 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6108 /// supports legal types, and it emits MachineInstrs directly instead of
6109 /// creating SelectionDAG nodes.
6112 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6114 TerminatorInst *TI = LLVMBB->getTerminator();
6116 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6117 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6119 // Check successor nodes' PHI nodes that expect a constant to be available
6121 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6122 BasicBlock *SuccBB = TI->getSuccessor(succ);
6123 if (!isa<PHINode>(SuccBB->begin())) continue;
6124 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6126 // If this terminator has multiple identical successors (common for
6127 // switches), only handle each succ once.
6128 if (!SuccsHandled.insert(SuccMBB)) continue;
6130 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6133 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6134 // nodes and Machine PHI nodes, but the incoming operands have not been
6136 for (BasicBlock::iterator I = SuccBB->begin();
6137 (PN = dyn_cast<PHINode>(I)); ++I) {
6138 // Ignore dead phi's.
6139 if (PN->use_empty()) continue;
6141 // Only handle legal types. Two interesting things to note here. First,
6142 // by bailing out early, we may leave behind some dead instructions,
6143 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6144 // own moves. Second, this check is necessary becuase FastISel doesn't
6145 // use CreateRegForValue to create registers, so it always creates
6146 // exactly one register for each non-void instruction.
6147 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6148 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6151 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6153 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6158 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6160 unsigned Reg = F->getRegForValue(PHIOp);
6162 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6165 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));