1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SDNodeDbgValue.h"
16 #include "SelectionDAGBuilder.h"
17 #include "FunctionLoweringInfo.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/IntrinsicInst.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/Module.h"
33 #include "llvm/CodeGen/FastISel.h"
34 #include "llvm/CodeGen/GCStrategy.h"
35 #include "llvm/CodeGen/GCMetadata.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineJumpTableInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/PseudoSourceValue.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/Analysis/DebugInfo.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Target/TargetFrameInfo.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetIntrinsicInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/raw_ostream.h"
61 /// LimitFloatPrecision - Generate low-precision inline sequences for
62 /// some float libcalls (6, 8 or 12 bits).
63 static unsigned LimitFloatPrecision;
65 static cl::opt<unsigned, true>
66 LimitFPPrecision("limit-float-precision",
67 cl::desc("Generate low-precision inline sequences "
68 "for some float libcalls"),
69 cl::location(LimitFloatPrecision),
73 /// RegsForValue - This struct represents the registers (physical or virtual)
74 /// that a particular set of values is assigned, and the type information
75 /// about the value. The most common situation is to represent one value at a
76 /// time, but struct or array values are handled element-wise as multiple
77 /// values. The splitting of aggregates is performed recursively, so that we
78 /// never have aggregate-typed registers. The values at this point do not
79 /// necessarily have legal types, so each value may require one or more
80 /// registers of some legal type.
83 /// TLI - The TargetLowering object.
85 const TargetLowering *TLI;
87 /// ValueVTs - The value types of the values, which may not be legal, and
88 /// may need be promoted or synthesized from one or more registers.
90 SmallVector<EVT, 4> ValueVTs;
92 /// RegVTs - The value types of the registers. This is the same size as
93 /// ValueVTs and it records, for each value, what the type of the assigned
94 /// register or registers are. (Individual values are never synthesized
95 /// from more than one type of register.)
97 /// With virtual registers, the contents of RegVTs is redundant with TLI's
98 /// getRegisterType member function, however when with physical registers
99 /// it is necessary to have a separate record of the types.
101 SmallVector<EVT, 4> RegVTs;
103 /// Regs - This list holds the registers assigned to the values.
104 /// Each legal or promoted value requires one register, and each
105 /// expanded value requires multiple registers.
107 SmallVector<unsigned, 4> Regs;
109 RegsForValue() : TLI(0) {}
111 RegsForValue(const TargetLowering &tli,
112 const SmallVector<unsigned, 4> ®s,
113 EVT regvt, EVT valuevt)
114 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
115 RegsForValue(const TargetLowering &tli,
116 const SmallVector<unsigned, 4> ®s,
117 const SmallVector<EVT, 4> ®vts,
118 const SmallVector<EVT, 4> &valuevts)
119 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
120 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
121 unsigned Reg, const Type *Ty) : TLI(&tli) {
122 ComputeValueVTs(tli, Ty, ValueVTs);
124 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
125 EVT ValueVT = ValueVTs[Value];
126 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
127 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
128 for (unsigned i = 0; i != NumRegs; ++i)
129 Regs.push_back(Reg + i);
130 RegVTs.push_back(RegisterVT);
135 /// areValueTypesLegal - Return true if types of all the values are legal.
136 bool areValueTypesLegal() {
137 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
138 EVT RegisterVT = RegVTs[Value];
139 if (!TLI->isTypeLegal(RegisterVT))
146 /// append - Add the specified values to this one.
147 void append(const RegsForValue &RHS) {
149 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
150 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
151 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
155 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
156 /// this value and returns the result as a ValueVTs value. This uses
157 /// Chain/Flag as the input and updates them for the output Chain/Flag.
158 /// If the Flag pointer is NULL, no flag is used.
159 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
160 SDValue &Chain, SDValue *Flag) const;
162 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
163 /// specified value into the registers specified by this object. This uses
164 /// Chain/Flag as the input and updates them for the output Chain/Flag.
165 /// If the Flag pointer is NULL, no flag is used.
166 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
167 SDValue &Chain, SDValue *Flag) const;
169 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
170 /// operand list. This adds the code marker, matching input operand index
171 /// (if applicable), and includes the number of values added into it.
172 void AddInlineAsmOperands(unsigned Kind,
173 bool HasMatching, unsigned MatchingIdx,
175 std::vector<SDValue> &Ops) const;
179 /// getCopyFromParts - Create a value that contains the specified legal parts
180 /// combined into the value they represent. If the parts combine to a type
181 /// larger then ValueVT then AssertOp can be used to specify whether the extra
182 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
183 /// (ISD::AssertSext).
184 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
185 const SDValue *Parts,
186 unsigned NumParts, EVT PartVT, EVT ValueVT,
187 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
188 assert(NumParts > 0 && "No parts to assemble!");
189 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
190 SDValue Val = Parts[0];
193 // Assemble the value from multiple parts.
194 if (!ValueVT.isVector() && ValueVT.isInteger()) {
195 unsigned PartBits = PartVT.getSizeInBits();
196 unsigned ValueBits = ValueVT.getSizeInBits();
198 // Assemble the power of 2 part.
199 unsigned RoundParts = NumParts & (NumParts - 1) ?
200 1 << Log2_32(NumParts) : NumParts;
201 unsigned RoundBits = PartBits * RoundParts;
202 EVT RoundVT = RoundBits == ValueBits ?
203 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
206 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
208 if (RoundParts > 2) {
209 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts / 2,
211 Hi = getCopyFromParts(DAG, dl, Parts + RoundParts / 2,
212 RoundParts / 2, PartVT, HalfVT);
214 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
215 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
218 if (TLI.isBigEndian())
221 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
223 if (RoundParts < NumParts) {
224 // Assemble the trailing non-power-of-2 part.
225 unsigned OddParts = NumParts - RoundParts;
226 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
227 Hi = getCopyFromParts(DAG, dl,
228 Parts + RoundParts, OddParts, PartVT, OddVT);
230 // Combine the round and odd parts.
232 if (TLI.isBigEndian())
234 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
235 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
236 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
237 DAG.getConstant(Lo.getValueType().getSizeInBits(),
238 TLI.getPointerTy()));
239 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
240 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
242 } else if (ValueVT.isVector()) {
243 // Handle a multi-element vector.
244 EVT IntermediateVT, RegisterVT;
245 unsigned NumIntermediates;
247 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
248 NumIntermediates, RegisterVT);
249 assert(NumRegs == NumParts
250 && "Part count doesn't match vector breakdown!");
251 NumParts = NumRegs; // Silence a compiler warning.
252 assert(RegisterVT == PartVT
253 && "Part type doesn't match vector breakdown!");
254 assert(RegisterVT == Parts[0].getValueType() &&
255 "Part type doesn't match part!");
257 // Assemble the parts into intermediate operands.
258 SmallVector<SDValue, 8> Ops(NumIntermediates);
259 if (NumIntermediates == NumParts) {
260 // If the register was not expanded, truncate or copy the value,
262 for (unsigned i = 0; i != NumParts; ++i)
263 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
264 PartVT, IntermediateVT);
265 } else if (NumParts > 0) {
266 // If the intermediate type was expanded, build the intermediate
267 // operands from the parts.
268 assert(NumParts % NumIntermediates == 0 &&
269 "Must expand into a divisible number of parts!");
270 unsigned Factor = NumParts / NumIntermediates;
271 for (unsigned i = 0; i != NumIntermediates; ++i)
272 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
273 PartVT, IntermediateVT);
276 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
277 // intermediate operands.
278 Val = DAG.getNode(IntermediateVT.isVector() ?
279 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
280 ValueVT, &Ops[0], NumIntermediates);
281 } else if (PartVT.isFloatingPoint()) {
282 // FP split into multiple FP parts (for ppcf128)
283 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
286 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
287 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
288 if (TLI.isBigEndian())
290 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
292 // FP split into integer parts (soft fp)
293 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
294 !PartVT.isVector() && "Unexpected split");
295 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
296 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
300 // There is now one part, held in Val. Correct it to match ValueVT.
301 PartVT = Val.getValueType();
303 if (PartVT == ValueVT)
306 if (PartVT.isVector()) {
307 assert(ValueVT.isVector() && "Unknown vector conversion!");
308 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
311 if (ValueVT.isVector()) {
312 assert(ValueVT.getVectorElementType() == PartVT &&
313 ValueVT.getVectorNumElements() == 1 &&
314 "Only trivial scalar-to-vector conversions should get here!");
315 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
318 if (PartVT.isInteger() &&
319 ValueVT.isInteger()) {
320 if (ValueVT.bitsLT(PartVT)) {
321 // For a truncate, see if we have any information to
322 // indicate whether the truncated bits will always be
323 // zero or sign-extension.
324 if (AssertOp != ISD::DELETED_NODE)
325 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
326 DAG.getValueType(ValueVT));
327 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
329 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
333 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
334 if (ValueVT.bitsLT(Val.getValueType())) {
335 // FP_ROUND's are always exact here.
336 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
337 DAG.getIntPtrConstant(1));
340 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
343 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
344 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
346 llvm_unreachable("Unknown mismatch!");
350 /// getCopyToParts - Create a series of nodes that contain the specified value
351 /// split into legal parts. If the parts contain more bits than Val, then, for
352 /// integers, ExtendKind can be used to specify how to generate the extra bits.
353 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl,
354 SDValue Val, SDValue *Parts, unsigned NumParts,
356 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
358 EVT PtrVT = TLI.getPointerTy();
359 EVT ValueVT = Val.getValueType();
360 unsigned PartBits = PartVT.getSizeInBits();
361 unsigned OrigNumParts = NumParts;
362 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
367 if (!ValueVT.isVector()) {
368 if (PartVT == ValueVT) {
369 assert(NumParts == 1 && "No-op copy with multiple parts!");
374 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
375 // If the parts cover more bits than the value has, promote the value.
376 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
377 assert(NumParts == 1 && "Do not know what to promote to!");
378 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
379 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
380 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
381 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
383 llvm_unreachable("Unknown mismatch!");
385 } else if (PartBits == ValueVT.getSizeInBits()) {
386 // Different types of the same size.
387 assert(NumParts == 1 && PartVT != ValueVT);
388 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
389 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
390 // If the parts cover less bits than value has, truncate the value.
391 if (PartVT.isInteger() && ValueVT.isInteger()) {
392 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
393 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
395 llvm_unreachable("Unknown mismatch!");
399 // The value may have changed - recompute ValueVT.
400 ValueVT = Val.getValueType();
401 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
402 "Failed to tile the value with PartVT!");
405 assert(PartVT == ValueVT && "Type conversion failed!");
410 // Expand the value into multiple parts.
411 if (NumParts & (NumParts - 1)) {
412 // The number of parts is not a power of 2. Split off and copy the tail.
413 assert(PartVT.isInteger() && ValueVT.isInteger() &&
414 "Do not know what to expand to!");
415 unsigned RoundParts = 1 << Log2_32(NumParts);
416 unsigned RoundBits = RoundParts * PartBits;
417 unsigned OddParts = NumParts - RoundParts;
418 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
419 DAG.getConstant(RoundBits,
420 TLI.getPointerTy()));
421 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts,
424 if (TLI.isBigEndian())
425 // The odd parts were reversed by getCopyToParts - unreverse them.
426 std::reverse(Parts + RoundParts, Parts + NumParts);
428 NumParts = RoundParts;
429 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
430 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
433 // The number of parts is a power of 2. Repeatedly bisect the value using
435 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
436 EVT::getIntegerVT(*DAG.getContext(),
437 ValueVT.getSizeInBits()),
440 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
441 for (unsigned i = 0; i < NumParts; i += StepSize) {
442 unsigned ThisBits = StepSize * PartBits / 2;
443 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
444 SDValue &Part0 = Parts[i];
445 SDValue &Part1 = Parts[i+StepSize/2];
447 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
449 DAG.getConstant(1, PtrVT));
450 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
452 DAG.getConstant(0, PtrVT));
454 if (ThisBits == PartBits && ThisVT != PartVT) {
455 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
457 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
463 if (TLI.isBigEndian())
464 std::reverse(Parts, Parts + OrigNumParts);
471 if (PartVT != ValueVT) {
472 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
473 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
475 assert(ValueVT.getVectorElementType() == PartVT &&
476 ValueVT.getVectorNumElements() == 1 &&
477 "Only trivial vector-to-scalar conversions should get here!");
478 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
480 DAG.getConstant(0, PtrVT));
488 // Handle a multi-element vector.
489 EVT IntermediateVT, RegisterVT;
490 unsigned NumIntermediates;
491 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
492 IntermediateVT, NumIntermediates, RegisterVT);
493 unsigned NumElements = ValueVT.getVectorNumElements();
495 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
496 NumParts = NumRegs; // Silence a compiler warning.
497 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
499 // Split the vector into intermediate operands.
500 SmallVector<SDValue, 8> Ops(NumIntermediates);
501 for (unsigned i = 0; i != NumIntermediates; ++i) {
502 if (IntermediateVT.isVector())
503 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
505 DAG.getConstant(i * (NumElements / NumIntermediates),
508 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
510 DAG.getConstant(i, PtrVT));
513 // Split the intermediate operands into legal parts.
514 if (NumParts == NumIntermediates) {
515 // If the register was not expanded, promote or copy the value,
517 for (unsigned i = 0; i != NumParts; ++i)
518 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
519 } else if (NumParts > 0) {
520 // If the intermediate type was expanded, split each the value into
522 assert(NumParts % NumIntermediates == 0 &&
523 "Must expand into a divisible number of parts!");
524 unsigned Factor = NumParts / NumIntermediates;
525 for (unsigned i = 0; i != NumIntermediates; ++i)
526 getCopyToParts(DAG, dl, Ops[i], &Parts[i*Factor], Factor, PartVT);
531 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
534 TD = DAG.getTarget().getTargetData();
537 /// clear - Clear out the current SelectionDAG and the associated
538 /// state and prepare this SelectionDAGBuilder object to be used
539 /// for a new block. This doesn't clear out information about
540 /// additional blocks that are needed to complete switch lowering
541 /// or PHI node updating; that information is cleared out as it is
543 void SelectionDAGBuilder::clear() {
545 PendingLoads.clear();
546 PendingExports.clear();
549 CurDebugLoc = DebugLoc();
553 /// getRoot - Return the current virtual root of the Selection DAG,
554 /// flushing any PendingLoad items. This must be done before emitting
555 /// a store or any other node that may need to be ordered after any
556 /// prior load instructions.
558 SDValue SelectionDAGBuilder::getRoot() {
559 if (PendingLoads.empty())
560 return DAG.getRoot();
562 if (PendingLoads.size() == 1) {
563 SDValue Root = PendingLoads[0];
565 PendingLoads.clear();
569 // Otherwise, we have to make a token factor node.
570 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
571 &PendingLoads[0], PendingLoads.size());
572 PendingLoads.clear();
577 /// getControlRoot - Similar to getRoot, but instead of flushing all the
578 /// PendingLoad items, flush all the PendingExports items. It is necessary
579 /// to do this before emitting a terminator instruction.
581 SDValue SelectionDAGBuilder::getControlRoot() {
582 SDValue Root = DAG.getRoot();
584 if (PendingExports.empty())
587 // Turn all of the CopyToReg chains into one factored node.
588 if (Root.getOpcode() != ISD::EntryToken) {
589 unsigned i = 0, e = PendingExports.size();
590 for (; i != e; ++i) {
591 assert(PendingExports[i].getNode()->getNumOperands() > 1);
592 if (PendingExports[i].getNode()->getOperand(0) == Root)
593 break; // Don't add the root if we already indirectly depend on it.
597 PendingExports.push_back(Root);
600 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
602 PendingExports.size());
603 PendingExports.clear();
608 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
609 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
610 DAG.AssignOrdering(Node, SDNodeOrder);
612 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
613 AssignOrderingToNode(Node->getOperand(I).getNode());
616 void SelectionDAGBuilder::visit(const Instruction &I) {
617 visit(I.getOpcode(), I);
620 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
621 // Note: this doesn't use InstVisitor, because it has to work with
622 // ConstantExpr's in addition to instructions.
624 default: llvm_unreachable("Unknown instruction type encountered!");
625 // Build the switch statement using the Instruction.def file.
626 #define HANDLE_INST(NUM, OPCODE, CLASS) \
627 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
628 #include "llvm/Instruction.def"
631 // Assign the ordering to the freshly created DAG nodes.
632 if (NodeMap.count(&I)) {
634 AssignOrderingToNode(getValue(&I).getNode());
638 SDValue SelectionDAGBuilder::getValue(const Value *V) {
639 SDValue &N = NodeMap[V];
640 if (N.getNode()) return N;
642 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
643 EVT VT = TLI.getValueType(V->getType(), true);
645 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
646 return N = DAG.getConstant(*CI, VT);
648 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
649 return N = DAG.getGlobalAddress(GV, VT);
651 if (isa<ConstantPointerNull>(C))
652 return N = DAG.getConstant(0, TLI.getPointerTy());
654 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
655 return N = DAG.getConstantFP(*CFP, VT);
657 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
658 return N = DAG.getUNDEF(VT);
660 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
661 visit(CE->getOpcode(), *CE);
662 SDValue N1 = NodeMap[V];
663 assert(N1.getNode() && "visit didn't populate the NodeMap!");
667 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
668 SmallVector<SDValue, 4> Constants;
669 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
671 SDNode *Val = getValue(*OI).getNode();
672 // If the operand is an empty aggregate, there are no values.
674 // Add each leaf value from the operand to the Constants list
675 // to form a flattened list of all the values.
676 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
677 Constants.push_back(SDValue(Val, i));
680 return DAG.getMergeValues(&Constants[0], Constants.size(),
684 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
685 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
686 "Unknown struct or array constant!");
688 SmallVector<EVT, 4> ValueVTs;
689 ComputeValueVTs(TLI, C->getType(), ValueVTs);
690 unsigned NumElts = ValueVTs.size();
692 return SDValue(); // empty struct
693 SmallVector<SDValue, 4> Constants(NumElts);
694 for (unsigned i = 0; i != NumElts; ++i) {
695 EVT EltVT = ValueVTs[i];
696 if (isa<UndefValue>(C))
697 Constants[i] = DAG.getUNDEF(EltVT);
698 else if (EltVT.isFloatingPoint())
699 Constants[i] = DAG.getConstantFP(0, EltVT);
701 Constants[i] = DAG.getConstant(0, EltVT);
704 return DAG.getMergeValues(&Constants[0], NumElts,
708 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
709 return DAG.getBlockAddress(BA, VT);
711 const VectorType *VecTy = cast<VectorType>(V->getType());
712 unsigned NumElements = VecTy->getNumElements();
714 // Now that we know the number and type of the elements, get that number of
715 // elements into the Ops array based on what kind of constant it is.
716 SmallVector<SDValue, 16> Ops;
717 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
718 for (unsigned i = 0; i != NumElements; ++i)
719 Ops.push_back(getValue(CP->getOperand(i)));
721 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
722 EVT EltVT = TLI.getValueType(VecTy->getElementType());
725 if (EltVT.isFloatingPoint())
726 Op = DAG.getConstantFP(0, EltVT);
728 Op = DAG.getConstant(0, EltVT);
729 Ops.assign(NumElements, Op);
732 // Create a BUILD_VECTOR node.
733 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
734 VT, &Ops[0], Ops.size());
737 // If this is a static alloca, generate it as the frameindex instead of
739 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
740 DenseMap<const AllocaInst*, int>::iterator SI =
741 FuncInfo.StaticAllocaMap.find(AI);
742 if (SI != FuncInfo.StaticAllocaMap.end())
743 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
746 unsigned InReg = FuncInfo.ValueMap[V];
747 assert(InReg && "Value not in map!");
749 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
750 SDValue Chain = DAG.getEntryNode();
751 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), 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(const 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, false, 0);
850 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
851 MVT::Other, &Chains[0], NumValues);
852 } else if (I.getNumOperands() != 0) {
853 SmallVector<EVT, 4> ValueVTs;
854 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
855 unsigned NumValues = ValueVTs.size();
857 SDValue RetOp = getValue(I.getOperand(0));
858 for (unsigned j = 0, f = NumValues; j != f; ++j) {
859 EVT VT = ValueVTs[j];
861 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
863 const Function *F = I.getParent()->getParent();
864 if (F->paramHasAttr(0, Attribute::SExt))
865 ExtendKind = ISD::SIGN_EXTEND;
866 else if (F->paramHasAttr(0, Attribute::ZExt))
867 ExtendKind = ISD::ZERO_EXTEND;
869 // FIXME: C calling convention requires the return type to be promoted
870 // to at least 32-bit. But this is not necessary for non-C calling
871 // conventions. The frontend should mark functions whose return values
872 // require promoting with signext or zeroext attributes.
873 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
874 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
875 if (VT.bitsLT(MinVT))
879 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
880 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
881 SmallVector<SDValue, 4> Parts(NumParts);
882 getCopyToParts(DAG, getCurDebugLoc(),
883 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
884 &Parts[0], NumParts, PartVT, ExtendKind);
886 // 'inreg' on function refers to return value
887 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
888 if (F->paramHasAttr(0, Attribute::InReg))
891 // Propagate extension type if any
892 if (F->paramHasAttr(0, Attribute::SExt))
894 else if (F->paramHasAttr(0, Attribute::ZExt))
897 for (unsigned i = 0; i < NumParts; ++i)
898 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
903 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
904 CallingConv::ID CallConv =
905 DAG.getMachineFunction().getFunction()->getCallingConv();
906 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
907 Outs, getCurDebugLoc(), DAG);
909 // Verify that the target's LowerReturn behaved as expected.
910 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
911 "LowerReturn didn't return a valid chain!");
913 // Update the DAG with the new chain value resulting from return lowering.
917 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
918 /// created for it, emit nodes to copy the value into the virtual
920 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
921 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
922 if (VMI != FuncInfo.ValueMap.end()) {
923 assert(!V->use_empty() && "Unused value assigned virtual registers!");
924 CopyValueToVirtualRegister(V, VMI->second);
928 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
929 /// the current basic block, add it to ValueMap now so that we'll get a
931 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
932 // No need to export constants.
933 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
936 if (FuncInfo.isExportedInst(V)) return;
938 unsigned Reg = FuncInfo.InitializeRegForValue(V);
939 CopyValueToVirtualRegister(V, Reg);
942 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
943 const BasicBlock *FromBB) {
944 // The operands of the setcc have to be in this block. We don't know
945 // how to export them from some other block.
946 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
947 // Can export from current BB.
948 if (VI->getParent() == FromBB)
951 // Is already exported, noop.
952 return FuncInfo.isExportedInst(V);
955 // If this is an argument, we can export it if the BB is the entry block or
956 // if it is already exported.
957 if (isa<Argument>(V)) {
958 if (FromBB == &FromBB->getParent()->getEntryBlock())
961 // Otherwise, can only export this if it is already exported.
962 return FuncInfo.isExportedInst(V);
965 // Otherwise, constants can always be exported.
969 static bool InBlock(const Value *V, const BasicBlock *BB) {
970 if (const Instruction *I = dyn_cast<Instruction>(V))
971 return I->getParent() == BB;
975 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
976 /// This function emits a branch and is used at the leaves of an OR or an
977 /// AND operator tree.
980 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
981 MachineBasicBlock *TBB,
982 MachineBasicBlock *FBB,
983 MachineBasicBlock *CurBB) {
984 const BasicBlock *BB = CurBB->getBasicBlock();
986 // If the leaf of the tree is a comparison, merge the condition into
988 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
989 // The operands of the cmp have to be in this block. We don't know
990 // how to export them from some other block. If this is the first block
991 // of the sequence, no exporting is needed.
992 if (CurBB == CurMBB ||
993 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
994 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
995 ISD::CondCode Condition;
996 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
997 Condition = getICmpCondCode(IC->getPredicate());
998 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
999 Condition = getFCmpCondCode(FC->getPredicate());
1001 Condition = ISD::SETEQ; // silence warning.
1002 llvm_unreachable("Unknown compare instruction");
1005 CaseBlock CB(Condition, BOp->getOperand(0),
1006 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1007 SwitchCases.push_back(CB);
1012 // Create a CaseBlock record representing this branch.
1013 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1014 NULL, TBB, FBB, CurBB);
1015 SwitchCases.push_back(CB);
1018 /// FindMergedConditions - If Cond is an expression like
1019 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1020 MachineBasicBlock *TBB,
1021 MachineBasicBlock *FBB,
1022 MachineBasicBlock *CurBB,
1024 // If this node is not part of the or/and tree, emit it as a branch.
1025 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1026 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1027 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1028 BOp->getParent() != CurBB->getBasicBlock() ||
1029 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1030 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1031 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1035 // Create TmpBB after CurBB.
1036 MachineFunction::iterator BBI = CurBB;
1037 MachineFunction &MF = DAG.getMachineFunction();
1038 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1039 CurBB->getParent()->insert(++BBI, TmpBB);
1041 if (Opc == Instruction::Or) {
1042 // Codegen X | Y as:
1050 // Emit the LHS condition.
1051 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1053 // Emit the RHS condition into TmpBB.
1054 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1056 assert(Opc == Instruction::And && "Unknown merge op!");
1057 // Codegen X & Y as:
1064 // This requires creation of TmpBB after CurBB.
1066 // Emit the LHS condition.
1067 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1069 // Emit the RHS condition into TmpBB.
1070 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1074 /// If the set of cases should be emitted as a series of branches, return true.
1075 /// If we should emit this as a bunch of and/or'd together conditions, return
1078 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1079 if (Cases.size() != 2) return true;
1081 // If this is two comparisons of the same values or'd or and'd together, they
1082 // will get folded into a single comparison, so don't emit two blocks.
1083 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1084 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1085 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1086 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1090 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1091 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1092 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1093 Cases[0].CC == Cases[1].CC &&
1094 isa<Constant>(Cases[0].CmpRHS) &&
1095 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1096 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1098 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1105 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1106 // Update machine-CFG edges.
1107 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1109 // Figure out which block is immediately after the current one.
1110 MachineBasicBlock *NextBlock = 0;
1111 MachineFunction::iterator BBI = CurMBB;
1112 if (++BBI != FuncInfo.MF->end())
1115 if (I.isUnconditional()) {
1116 // Update machine-CFG edges.
1117 CurMBB->addSuccessor(Succ0MBB);
1119 // If this is not a fall-through branch, emit the branch.
1120 if (Succ0MBB != NextBlock)
1121 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1122 MVT::Other, getControlRoot(),
1123 DAG.getBasicBlock(Succ0MBB)));
1128 // If this condition is one of the special cases we handle, do special stuff
1130 const Value *CondVal = I.getCondition();
1131 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1133 // If this is a series of conditions that are or'd or and'd together, emit
1134 // this as a sequence of branches instead of setcc's with and/or operations.
1135 // For example, instead of something like:
1148 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1149 if (BOp->hasOneUse() &&
1150 (BOp->getOpcode() == Instruction::And ||
1151 BOp->getOpcode() == Instruction::Or)) {
1152 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1153 // If the compares in later blocks need to use values not currently
1154 // exported from this block, export them now. This block should always
1155 // be the first entry.
1156 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1158 // Allow some cases to be rejected.
1159 if (ShouldEmitAsBranches(SwitchCases)) {
1160 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1161 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1162 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1165 // Emit the branch for this block.
1166 visitSwitchCase(SwitchCases[0]);
1167 SwitchCases.erase(SwitchCases.begin());
1171 // Okay, we decided not to do this, remove any inserted MBB's and clear
1173 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1174 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1176 SwitchCases.clear();
1180 // Create a CaseBlock record representing this branch.
1181 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1182 NULL, Succ0MBB, Succ1MBB, CurMBB);
1184 // Use visitSwitchCase to actually insert the fast branch sequence for this
1186 visitSwitchCase(CB);
1189 /// visitSwitchCase - Emits the necessary code to represent a single node in
1190 /// the binary search tree resulting from lowering a switch instruction.
1191 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1193 SDValue CondLHS = getValue(CB.CmpLHS);
1194 DebugLoc dl = getCurDebugLoc();
1196 // Build the setcc now.
1197 if (CB.CmpMHS == NULL) {
1198 // Fold "(X == true)" to X and "(X == false)" to !X to
1199 // handle common cases produced by branch lowering.
1200 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1201 CB.CC == ISD::SETEQ)
1203 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1204 CB.CC == ISD::SETEQ) {
1205 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1206 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1208 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1210 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1212 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1213 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1215 SDValue CmpOp = getValue(CB.CmpMHS);
1216 EVT VT = CmpOp.getValueType();
1218 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1219 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1222 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1223 VT, CmpOp, DAG.getConstant(Low, VT));
1224 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1225 DAG.getConstant(High-Low, VT), ISD::SETULE);
1229 // Update successor info
1230 CurMBB->addSuccessor(CB.TrueBB);
1231 CurMBB->addSuccessor(CB.FalseBB);
1233 // Set NextBlock to be the MBB immediately after the current one, if any.
1234 // This is used to avoid emitting unnecessary branches to the next block.
1235 MachineBasicBlock *NextBlock = 0;
1236 MachineFunction::iterator BBI = CurMBB;
1237 if (++BBI != FuncInfo.MF->end())
1240 // If the lhs block is the next block, invert the condition so that we can
1241 // fall through to the lhs instead of the rhs block.
1242 if (CB.TrueBB == NextBlock) {
1243 std::swap(CB.TrueBB, CB.FalseBB);
1244 SDValue True = DAG.getConstant(1, Cond.getValueType());
1245 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1248 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1249 MVT::Other, getControlRoot(), Cond,
1250 DAG.getBasicBlock(CB.TrueBB));
1252 // If the branch was constant folded, fix up the CFG.
1253 if (BrCond.getOpcode() == ISD::BR) {
1254 CurMBB->removeSuccessor(CB.FalseBB);
1256 // Otherwise, go ahead and insert the false branch.
1257 if (BrCond == getControlRoot())
1258 CurMBB->removeSuccessor(CB.TrueBB);
1260 if (CB.FalseBB != NextBlock)
1261 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1262 DAG.getBasicBlock(CB.FalseBB));
1265 DAG.setRoot(BrCond);
1268 /// visitJumpTable - Emit JumpTable node in the current MBB
1269 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1270 // Emit the code for the jump table
1271 assert(JT.Reg != -1U && "Should lower JT Header first!");
1272 EVT PTy = TLI.getPointerTy();
1273 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1275 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1276 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1277 MVT::Other, Index.getValue(1),
1279 DAG.setRoot(BrJumpTable);
1282 /// visitJumpTableHeader - This function emits necessary code to produce index
1283 /// in the JumpTable from switch case.
1284 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1285 JumpTableHeader &JTH) {
1286 // Subtract the lowest switch case value from the value being switched on and
1287 // conditional branch to default mbb if the result is greater than the
1288 // difference between smallest and largest cases.
1289 SDValue SwitchOp = getValue(JTH.SValue);
1290 EVT VT = SwitchOp.getValueType();
1291 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1292 DAG.getConstant(JTH.First, VT));
1294 // The SDNode we just created, which holds the value being switched on minus
1295 // the smallest case value, needs to be copied to a virtual register so it
1296 // can be used as an index into the jump table in a subsequent basic block.
1297 // This value may be smaller or larger than the target's pointer type, and
1298 // therefore require extension or truncating.
1299 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1301 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1302 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1303 JumpTableReg, SwitchOp);
1304 JT.Reg = JumpTableReg;
1306 // Emit the range check for the jump table, and branch to the default block
1307 // for the switch statement if the value being switched on exceeds the largest
1308 // case in the switch.
1309 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1310 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1311 DAG.getConstant(JTH.Last-JTH.First,VT),
1314 // Set NextBlock to be the MBB immediately after the current one, if any.
1315 // This is used to avoid emitting unnecessary branches to the next block.
1316 MachineBasicBlock *NextBlock = 0;
1317 MachineFunction::iterator BBI = CurMBB;
1319 if (++BBI != FuncInfo.MF->end())
1322 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1323 MVT::Other, CopyTo, CMP,
1324 DAG.getBasicBlock(JT.Default));
1326 if (JT.MBB != NextBlock)
1327 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1328 DAG.getBasicBlock(JT.MBB));
1330 DAG.setRoot(BrCond);
1333 /// visitBitTestHeader - This function emits necessary code to produce value
1334 /// suitable for "bit tests"
1335 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1336 // Subtract the minimum value
1337 SDValue SwitchOp = getValue(B.SValue);
1338 EVT VT = SwitchOp.getValueType();
1339 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1340 DAG.getConstant(B.First, VT));
1343 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1344 TLI.getSetCCResultType(Sub.getValueType()),
1345 Sub, DAG.getConstant(B.Range, VT),
1348 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1349 TLI.getPointerTy());
1351 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1352 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1355 // Set NextBlock to be the MBB immediately after the current one, if any.
1356 // This is used to avoid emitting unnecessary branches to the next block.
1357 MachineBasicBlock *NextBlock = 0;
1358 MachineFunction::iterator BBI = CurMBB;
1359 if (++BBI != FuncInfo.MF->end())
1362 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1364 CurMBB->addSuccessor(B.Default);
1365 CurMBB->addSuccessor(MBB);
1367 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1368 MVT::Other, CopyTo, RangeCmp,
1369 DAG.getBasicBlock(B.Default));
1371 if (MBB != NextBlock)
1372 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1373 DAG.getBasicBlock(MBB));
1375 DAG.setRoot(BrRange);
1378 /// visitBitTestCase - this function produces one "bit test"
1379 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1382 // Make desired shift
1383 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1384 TLI.getPointerTy());
1385 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1387 DAG.getConstant(1, TLI.getPointerTy()),
1390 // Emit bit tests and jumps
1391 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1392 TLI.getPointerTy(), SwitchVal,
1393 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1394 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1395 TLI.getSetCCResultType(AndOp.getValueType()),
1396 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1399 CurMBB->addSuccessor(B.TargetBB);
1400 CurMBB->addSuccessor(NextMBB);
1402 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1403 MVT::Other, getControlRoot(),
1404 AndCmp, DAG.getBasicBlock(B.TargetBB));
1406 // Set NextBlock to be the MBB immediately after the current one, if any.
1407 // This is used to avoid emitting unnecessary branches to the next block.
1408 MachineBasicBlock *NextBlock = 0;
1409 MachineFunction::iterator BBI = CurMBB;
1410 if (++BBI != FuncInfo.MF->end())
1413 if (NextMBB != NextBlock)
1414 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1415 DAG.getBasicBlock(NextMBB));
1420 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1421 // Retrieve successors.
1422 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1423 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1425 const Value *Callee(I.getCalledValue());
1426 if (isa<InlineAsm>(Callee))
1429 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1431 // If the value of the invoke is used outside of its defining block, make it
1432 // available as a virtual register.
1433 CopyToExportRegsIfNeeded(&I);
1435 // Update successor info
1436 CurMBB->addSuccessor(Return);
1437 CurMBB->addSuccessor(LandingPad);
1439 // Drop into normal successor.
1440 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1441 MVT::Other, getControlRoot(),
1442 DAG.getBasicBlock(Return)));
1445 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1448 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1449 /// small case ranges).
1450 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1451 CaseRecVector& WorkList,
1453 MachineBasicBlock* Default) {
1454 Case& BackCase = *(CR.Range.second-1);
1456 // Size is the number of Cases represented by this range.
1457 size_t Size = CR.Range.second - CR.Range.first;
1461 // Get the MachineFunction which holds the current MBB. This is used when
1462 // inserting any additional MBBs necessary to represent the switch.
1463 MachineFunction *CurMF = FuncInfo.MF;
1465 // Figure out which block is immediately after the current one.
1466 MachineBasicBlock *NextBlock = 0;
1467 MachineFunction::iterator BBI = CR.CaseBB;
1469 if (++BBI != FuncInfo.MF->end())
1472 // TODO: If any two of the cases has the same destination, and if one value
1473 // is the same as the other, but has one bit unset that the other has set,
1474 // use bit manipulation to do two compares at once. For example:
1475 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1477 // Rearrange the case blocks so that the last one falls through if possible.
1478 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1479 // The last case block won't fall through into 'NextBlock' if we emit the
1480 // branches in this order. See if rearranging a case value would help.
1481 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1482 if (I->BB == NextBlock) {
1483 std::swap(*I, BackCase);
1489 // Create a CaseBlock record representing a conditional branch to
1490 // the Case's target mbb if the value being switched on SV is equal
1492 MachineBasicBlock *CurBlock = CR.CaseBB;
1493 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1494 MachineBasicBlock *FallThrough;
1496 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1497 CurMF->insert(BBI, FallThrough);
1499 // Put SV in a virtual register to make it available from the new blocks.
1500 ExportFromCurrentBlock(SV);
1502 // If the last case doesn't match, go to the default block.
1503 FallThrough = Default;
1506 const Value *RHS, *LHS, *MHS;
1508 if (I->High == I->Low) {
1509 // This is just small small case range :) containing exactly 1 case
1511 LHS = SV; RHS = I->High; MHS = NULL;
1514 LHS = I->Low; MHS = SV; RHS = I->High;
1516 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1518 // If emitting the first comparison, just call visitSwitchCase to emit the
1519 // code into the current block. Otherwise, push the CaseBlock onto the
1520 // vector to be later processed by SDISel, and insert the node's MBB
1521 // before the next MBB.
1522 if (CurBlock == CurMBB)
1523 visitSwitchCase(CB);
1525 SwitchCases.push_back(CB);
1527 CurBlock = FallThrough;
1533 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1534 return !DisableJumpTables &&
1535 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1536 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1539 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1540 APInt LastExt(Last), FirstExt(First);
1541 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1542 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1543 return (LastExt - FirstExt + 1ULL);
1546 /// handleJTSwitchCase - Emit jumptable for current switch case range
1547 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1548 CaseRecVector& WorkList,
1550 MachineBasicBlock* Default) {
1551 Case& FrontCase = *CR.Range.first;
1552 Case& BackCase = *(CR.Range.second-1);
1554 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1555 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1557 APInt TSize(First.getBitWidth(), 0);
1558 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1562 if (!areJTsAllowed(TLI) || TSize.ult(4))
1565 APInt Range = ComputeRange(First, Last);
1566 double Density = TSize.roundToDouble() / Range.roundToDouble();
1570 DEBUG(dbgs() << "Lowering jump table\n"
1571 << "First entry: " << First << ". Last entry: " << Last << '\n'
1572 << "Range: " << Range
1573 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1575 // Get the MachineFunction which holds the current MBB. This is used when
1576 // inserting any additional MBBs necessary to represent the switch.
1577 MachineFunction *CurMF = FuncInfo.MF;
1579 // Figure out which block is immediately after the current one.
1580 MachineFunction::iterator BBI = CR.CaseBB;
1583 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1585 // Create a new basic block to hold the code for loading the address
1586 // of the jump table, and jumping to it. Update successor information;
1587 // we will either branch to the default case for the switch, or the jump
1589 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1590 CurMF->insert(BBI, JumpTableBB);
1591 CR.CaseBB->addSuccessor(Default);
1592 CR.CaseBB->addSuccessor(JumpTableBB);
1594 // Build a vector of destination BBs, corresponding to each target
1595 // of the jump table. If the value of the jump table slot corresponds to
1596 // a case statement, push the case's BB onto the vector, otherwise, push
1598 std::vector<MachineBasicBlock*> DestBBs;
1600 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1601 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1602 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1604 if (Low.sle(TEI) && TEI.sle(High)) {
1605 DestBBs.push_back(I->BB);
1609 DestBBs.push_back(Default);
1613 // Update successor info. Add one edge to each unique successor.
1614 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1615 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1616 E = DestBBs.end(); I != E; ++I) {
1617 if (!SuccsHandled[(*I)->getNumber()]) {
1618 SuccsHandled[(*I)->getNumber()] = true;
1619 JumpTableBB->addSuccessor(*I);
1623 // Create a jump table index for this jump table.
1624 unsigned JTEncoding = TLI.getJumpTableEncoding();
1625 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1626 ->createJumpTableIndex(DestBBs);
1628 // Set the jump table information so that we can codegen it as a second
1629 // MachineBasicBlock
1630 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1631 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1632 if (CR.CaseBB == CurMBB)
1633 visitJumpTableHeader(JT, JTH);
1635 JTCases.push_back(JumpTableBlock(JTH, JT));
1640 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1642 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1643 CaseRecVector& WorkList,
1645 MachineBasicBlock* Default) {
1646 // Get the MachineFunction which holds the current MBB. This is used when
1647 // inserting any additional MBBs necessary to represent the switch.
1648 MachineFunction *CurMF = FuncInfo.MF;
1650 // Figure out which block is immediately after the current one.
1651 MachineFunction::iterator BBI = CR.CaseBB;
1654 Case& FrontCase = *CR.Range.first;
1655 Case& BackCase = *(CR.Range.second-1);
1656 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1658 // Size is the number of Cases represented by this range.
1659 unsigned Size = CR.Range.second - CR.Range.first;
1661 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1662 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1664 CaseItr Pivot = CR.Range.first + Size/2;
1666 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1667 // (heuristically) allow us to emit JumpTable's later.
1668 APInt TSize(First.getBitWidth(), 0);
1669 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1673 APInt LSize = FrontCase.size();
1674 APInt RSize = TSize-LSize;
1675 DEBUG(dbgs() << "Selecting best pivot: \n"
1676 << "First: " << First << ", Last: " << Last <<'\n'
1677 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1678 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1680 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1681 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1682 APInt Range = ComputeRange(LEnd, RBegin);
1683 assert((Range - 2ULL).isNonNegative() &&
1684 "Invalid case distance");
1685 double LDensity = (double)LSize.roundToDouble() /
1686 (LEnd - First + 1ULL).roundToDouble();
1687 double RDensity = (double)RSize.roundToDouble() /
1688 (Last - RBegin + 1ULL).roundToDouble();
1689 double Metric = Range.logBase2()*(LDensity+RDensity);
1690 // Should always split in some non-trivial place
1691 DEBUG(dbgs() <<"=>Step\n"
1692 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1693 << "LDensity: " << LDensity
1694 << ", RDensity: " << RDensity << '\n'
1695 << "Metric: " << Metric << '\n');
1696 if (FMetric < Metric) {
1699 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
1705 if (areJTsAllowed(TLI)) {
1706 // If our case is dense we *really* should handle it earlier!
1707 assert((FMetric > 0) && "Should handle dense range earlier!");
1709 Pivot = CR.Range.first + Size/2;
1712 CaseRange LHSR(CR.Range.first, Pivot);
1713 CaseRange RHSR(Pivot, CR.Range.second);
1714 Constant *C = Pivot->Low;
1715 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1717 // We know that we branch to the LHS if the Value being switched on is
1718 // less than the Pivot value, C. We use this to optimize our binary
1719 // tree a bit, by recognizing that if SV is greater than or equal to the
1720 // LHS's Case Value, and that Case Value is exactly one less than the
1721 // Pivot's Value, then we can branch directly to the LHS's Target,
1722 // rather than creating a leaf node for it.
1723 if ((LHSR.second - LHSR.first) == 1 &&
1724 LHSR.first->High == CR.GE &&
1725 cast<ConstantInt>(C)->getValue() ==
1726 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1727 TrueBB = LHSR.first->BB;
1729 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1730 CurMF->insert(BBI, TrueBB);
1731 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1733 // Put SV in a virtual register to make it available from the new blocks.
1734 ExportFromCurrentBlock(SV);
1737 // Similar to the optimization above, if the Value being switched on is
1738 // known to be less than the Constant CR.LT, and the current Case Value
1739 // is CR.LT - 1, then we can branch directly to the target block for
1740 // the current Case Value, rather than emitting a RHS leaf node for it.
1741 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1742 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1743 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1744 FalseBB = RHSR.first->BB;
1746 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1747 CurMF->insert(BBI, FalseBB);
1748 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1750 // Put SV in a virtual register to make it available from the new blocks.
1751 ExportFromCurrentBlock(SV);
1754 // Create a CaseBlock record representing a conditional branch to
1755 // the LHS node if the value being switched on SV is less than C.
1756 // Otherwise, branch to LHS.
1757 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1759 if (CR.CaseBB == CurMBB)
1760 visitSwitchCase(CB);
1762 SwitchCases.push_back(CB);
1767 /// handleBitTestsSwitchCase - if current case range has few destination and
1768 /// range span less, than machine word bitwidth, encode case range into series
1769 /// of masks and emit bit tests with these masks.
1770 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1771 CaseRecVector& WorkList,
1773 MachineBasicBlock* Default){
1774 EVT PTy = TLI.getPointerTy();
1775 unsigned IntPtrBits = PTy.getSizeInBits();
1777 Case& FrontCase = *CR.Range.first;
1778 Case& BackCase = *(CR.Range.second-1);
1780 // Get the MachineFunction which holds the current MBB. This is used when
1781 // inserting any additional MBBs necessary to represent the switch.
1782 MachineFunction *CurMF = FuncInfo.MF;
1784 // If target does not have legal shift left, do not emit bit tests at all.
1785 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1789 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1791 // Single case counts one, case range - two.
1792 numCmps += (I->Low == I->High ? 1 : 2);
1795 // Count unique destinations
1796 SmallSet<MachineBasicBlock*, 4> Dests;
1797 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1798 Dests.insert(I->BB);
1799 if (Dests.size() > 3)
1800 // Don't bother the code below, if there are too much unique destinations
1803 DEBUG(dbgs() << "Total number of unique destinations: "
1804 << Dests.size() << '\n'
1805 << "Total number of comparisons: " << numCmps << '\n');
1807 // Compute span of values.
1808 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1809 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1810 APInt cmpRange = maxValue - minValue;
1812 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
1813 << "Low bound: " << minValue << '\n'
1814 << "High bound: " << maxValue << '\n');
1816 if (cmpRange.uge(IntPtrBits) ||
1817 (!(Dests.size() == 1 && numCmps >= 3) &&
1818 !(Dests.size() == 2 && numCmps >= 5) &&
1819 !(Dests.size() >= 3 && numCmps >= 6)))
1822 DEBUG(dbgs() << "Emitting bit tests\n");
1823 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1825 // Optimize the case where all the case values fit in a
1826 // word without having to subtract minValue. In this case,
1827 // we can optimize away the subtraction.
1828 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
1829 cmpRange = maxValue;
1831 lowBound = minValue;
1834 CaseBitsVector CasesBits;
1835 unsigned i, count = 0;
1837 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1838 MachineBasicBlock* Dest = I->BB;
1839 for (i = 0; i < count; ++i)
1840 if (Dest == CasesBits[i].BB)
1844 assert((count < 3) && "Too much destinations to test!");
1845 CasesBits.push_back(CaseBits(0, Dest, 0));
1849 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1850 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1852 uint64_t lo = (lowValue - lowBound).getZExtValue();
1853 uint64_t hi = (highValue - lowBound).getZExtValue();
1855 for (uint64_t j = lo; j <= hi; j++) {
1856 CasesBits[i].Mask |= 1ULL << j;
1857 CasesBits[i].Bits++;
1861 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1865 // Figure out which block is immediately after the current one.
1866 MachineFunction::iterator BBI = CR.CaseBB;
1869 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1871 DEBUG(dbgs() << "Cases:\n");
1872 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1873 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
1874 << ", Bits: " << CasesBits[i].Bits
1875 << ", BB: " << CasesBits[i].BB << '\n');
1877 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1878 CurMF->insert(BBI, CaseBB);
1879 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1883 // Put SV in a virtual register to make it available from the new blocks.
1884 ExportFromCurrentBlock(SV);
1887 BitTestBlock BTB(lowBound, cmpRange, SV,
1888 -1U, (CR.CaseBB == CurMBB),
1889 CR.CaseBB, Default, BTC);
1891 if (CR.CaseBB == CurMBB)
1892 visitBitTestHeader(BTB);
1894 BitTestCases.push_back(BTB);
1899 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1900 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1901 const SwitchInst& SI) {
1904 // Start with "simple" cases
1905 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1906 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1907 Cases.push_back(Case(SI.getSuccessorValue(i),
1908 SI.getSuccessorValue(i),
1911 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1913 // Merge case into clusters
1914 if (Cases.size() >= 2)
1915 // Must recompute end() each iteration because it may be
1916 // invalidated by erase if we hold on to it
1917 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1918 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1919 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1920 MachineBasicBlock* nextBB = J->BB;
1921 MachineBasicBlock* currentBB = I->BB;
1923 // If the two neighboring cases go to the same destination, merge them
1924 // into a single case.
1925 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1933 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1934 if (I->Low != I->High)
1935 // A range counts double, since it requires two compares.
1942 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
1943 // Figure out which block is immediately after the current one.
1944 MachineBasicBlock *NextBlock = 0;
1945 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1947 // If there is only the default destination, branch to it if it is not the
1948 // next basic block. Otherwise, just fall through.
1949 if (SI.getNumOperands() == 2) {
1950 // Update machine-CFG edges.
1952 // If this is not a fall-through branch, emit the branch.
1953 CurMBB->addSuccessor(Default);
1954 if (Default != NextBlock)
1955 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1956 MVT::Other, getControlRoot(),
1957 DAG.getBasicBlock(Default)));
1962 // If there are any non-default case statements, create a vector of Cases
1963 // representing each one, and sort the vector so that we can efficiently
1964 // create a binary search tree from them.
1966 size_t numCmps = Clusterify(Cases, SI);
1967 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
1968 << ". Total compares: " << numCmps << '\n');
1971 // Get the Value to be switched on and default basic blocks, which will be
1972 // inserted into CaseBlock records, representing basic blocks in the binary
1974 const Value *SV = SI.getOperand(0);
1976 // Push the initial CaseRec onto the worklist
1977 CaseRecVector WorkList;
1978 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1980 while (!WorkList.empty()) {
1981 // Grab a record representing a case range to process off the worklist
1982 CaseRec CR = WorkList.back();
1983 WorkList.pop_back();
1985 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1988 // If the range has few cases (two or less) emit a series of specific
1990 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1993 // If the switch has more than 5 blocks, and at least 40% dense, and the
1994 // target supports indirect branches, then emit a jump table rather than
1995 // lowering the switch to a binary tree of conditional branches.
1996 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1999 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2000 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2001 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2005 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2006 // Update machine-CFG edges with unique successors.
2007 SmallVector<BasicBlock*, 32> succs;
2008 succs.reserve(I.getNumSuccessors());
2009 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2010 succs.push_back(I.getSuccessor(i));
2011 array_pod_sort(succs.begin(), succs.end());
2012 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2013 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2014 CurMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2016 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2017 MVT::Other, getControlRoot(),
2018 getValue(I.getAddress())));
2021 void SelectionDAGBuilder::visitFSub(const User &I) {
2022 // -0.0 - X --> fneg
2023 const Type *Ty = I.getType();
2024 if (Ty->isVectorTy()) {
2025 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2026 const VectorType *DestTy = cast<VectorType>(I.getType());
2027 const Type *ElTy = DestTy->getElementType();
2028 unsigned VL = DestTy->getNumElements();
2029 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2030 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2032 SDValue Op2 = getValue(I.getOperand(1));
2033 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2034 Op2.getValueType(), Op2));
2040 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2041 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2042 SDValue Op2 = getValue(I.getOperand(1));
2043 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2044 Op2.getValueType(), Op2));
2048 visitBinary(I, ISD::FSUB);
2051 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2052 SDValue Op1 = getValue(I.getOperand(0));
2053 SDValue Op2 = getValue(I.getOperand(1));
2054 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2055 Op1.getValueType(), Op1, Op2));
2058 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2059 SDValue Op1 = getValue(I.getOperand(0));
2060 SDValue Op2 = getValue(I.getOperand(1));
2061 if (!I.getType()->isVectorTy() &&
2062 Op2.getValueType() != TLI.getShiftAmountTy()) {
2063 // If the operand is smaller than the shift count type, promote it.
2064 EVT PTy = TLI.getPointerTy();
2065 EVT STy = TLI.getShiftAmountTy();
2066 if (STy.bitsGT(Op2.getValueType()))
2067 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2068 TLI.getShiftAmountTy(), Op2);
2069 // If the operand is larger than the shift count type but the shift
2070 // count type has enough bits to represent any shift value, truncate
2071 // it now. This is a common case and it exposes the truncate to
2072 // optimization early.
2073 else if (STy.getSizeInBits() >=
2074 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2075 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2076 TLI.getShiftAmountTy(), Op2);
2077 // Otherwise we'll need to temporarily settle for some other
2078 // convenient type; type legalization will make adjustments as
2080 else if (PTy.bitsLT(Op2.getValueType()))
2081 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2082 TLI.getPointerTy(), Op2);
2083 else if (PTy.bitsGT(Op2.getValueType()))
2084 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2085 TLI.getPointerTy(), Op2);
2088 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2089 Op1.getValueType(), Op1, Op2));
2092 void SelectionDAGBuilder::visitICmp(const User &I) {
2093 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2094 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2095 predicate = IC->getPredicate();
2096 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2097 predicate = ICmpInst::Predicate(IC->getPredicate());
2098 SDValue Op1 = getValue(I.getOperand(0));
2099 SDValue Op2 = getValue(I.getOperand(1));
2100 ISD::CondCode Opcode = getICmpCondCode(predicate);
2102 EVT DestVT = TLI.getValueType(I.getType());
2103 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2106 void SelectionDAGBuilder::visitFCmp(const User &I) {
2107 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2108 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2109 predicate = FC->getPredicate();
2110 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2111 predicate = FCmpInst::Predicate(FC->getPredicate());
2112 SDValue Op1 = getValue(I.getOperand(0));
2113 SDValue Op2 = getValue(I.getOperand(1));
2114 ISD::CondCode Condition = getFCmpCondCode(predicate);
2115 EVT DestVT = TLI.getValueType(I.getType());
2116 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2119 void SelectionDAGBuilder::visitSelect(const User &I) {
2120 SmallVector<EVT, 4> ValueVTs;
2121 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2122 unsigned NumValues = ValueVTs.size();
2123 if (NumValues == 0) return;
2125 SmallVector<SDValue, 4> Values(NumValues);
2126 SDValue Cond = getValue(I.getOperand(0));
2127 SDValue TrueVal = getValue(I.getOperand(1));
2128 SDValue FalseVal = getValue(I.getOperand(2));
2130 for (unsigned i = 0; i != NumValues; ++i)
2131 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2132 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2134 SDValue(TrueVal.getNode(),
2135 TrueVal.getResNo() + i),
2136 SDValue(FalseVal.getNode(),
2137 FalseVal.getResNo() + i));
2139 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2140 DAG.getVTList(&ValueVTs[0], NumValues),
2141 &Values[0], NumValues));
2144 void SelectionDAGBuilder::visitTrunc(const User &I) {
2145 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2146 SDValue N = getValue(I.getOperand(0));
2147 EVT DestVT = TLI.getValueType(I.getType());
2148 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2151 void SelectionDAGBuilder::visitZExt(const User &I) {
2152 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2153 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2154 SDValue N = getValue(I.getOperand(0));
2155 EVT DestVT = TLI.getValueType(I.getType());
2156 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2159 void SelectionDAGBuilder::visitSExt(const User &I) {
2160 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2161 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2162 SDValue N = getValue(I.getOperand(0));
2163 EVT DestVT = TLI.getValueType(I.getType());
2164 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2167 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2168 // FPTrunc is never a no-op cast, no need to check
2169 SDValue N = getValue(I.getOperand(0));
2170 EVT DestVT = TLI.getValueType(I.getType());
2171 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2172 DestVT, N, DAG.getIntPtrConstant(0)));
2175 void SelectionDAGBuilder::visitFPExt(const User &I){
2176 // FPTrunc is never a no-op cast, no need to check
2177 SDValue N = getValue(I.getOperand(0));
2178 EVT DestVT = TLI.getValueType(I.getType());
2179 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2182 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2183 // FPToUI is never a no-op cast, no need to check
2184 SDValue N = getValue(I.getOperand(0));
2185 EVT DestVT = TLI.getValueType(I.getType());
2186 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2189 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2190 // FPToSI is never a no-op cast, no need to check
2191 SDValue N = getValue(I.getOperand(0));
2192 EVT DestVT = TLI.getValueType(I.getType());
2193 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2196 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2197 // UIToFP is never a no-op cast, no need to check
2198 SDValue N = getValue(I.getOperand(0));
2199 EVT DestVT = TLI.getValueType(I.getType());
2200 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2203 void SelectionDAGBuilder::visitSIToFP(const User &I){
2204 // SIToFP is never a no-op cast, no need to check
2205 SDValue N = getValue(I.getOperand(0));
2206 EVT DestVT = TLI.getValueType(I.getType());
2207 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2210 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2211 // What to do depends on the size of the integer and the size of the pointer.
2212 // We can either truncate, zero extend, or no-op, accordingly.
2213 SDValue N = getValue(I.getOperand(0));
2214 EVT SrcVT = N.getValueType();
2215 EVT DestVT = TLI.getValueType(I.getType());
2216 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2219 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2220 // What to do depends on the size of the integer and the size of the pointer.
2221 // We can either truncate, zero extend, or no-op, accordingly.
2222 SDValue N = getValue(I.getOperand(0));
2223 EVT SrcVT = N.getValueType();
2224 EVT DestVT = TLI.getValueType(I.getType());
2225 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2228 void SelectionDAGBuilder::visitBitCast(const User &I) {
2229 SDValue N = getValue(I.getOperand(0));
2230 EVT DestVT = TLI.getValueType(I.getType());
2232 // BitCast assures us that source and destination are the same size so this is
2233 // either a BIT_CONVERT or a no-op.
2234 if (DestVT != N.getValueType())
2235 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2236 DestVT, N)); // convert types.
2238 setValue(&I, N); // noop cast.
2241 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2242 SDValue InVec = getValue(I.getOperand(0));
2243 SDValue InVal = getValue(I.getOperand(1));
2244 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2246 getValue(I.getOperand(2)));
2247 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2248 TLI.getValueType(I.getType()),
2249 InVec, InVal, InIdx));
2252 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2253 SDValue InVec = getValue(I.getOperand(0));
2254 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2256 getValue(I.getOperand(1)));
2257 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2258 TLI.getValueType(I.getType()), InVec, InIdx));
2261 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2262 // from SIndx and increasing to the element length (undefs are allowed).
2263 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2264 unsigned MaskNumElts = Mask.size();
2265 for (unsigned i = 0; i != MaskNumElts; ++i)
2266 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2271 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2272 SmallVector<int, 8> Mask;
2273 SDValue Src1 = getValue(I.getOperand(0));
2274 SDValue Src2 = getValue(I.getOperand(1));
2276 // Convert the ConstantVector mask operand into an array of ints, with -1
2277 // representing undef values.
2278 SmallVector<Constant*, 8> MaskElts;
2279 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2280 unsigned MaskNumElts = MaskElts.size();
2281 for (unsigned i = 0; i != MaskNumElts; ++i) {
2282 if (isa<UndefValue>(MaskElts[i]))
2285 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2288 EVT VT = TLI.getValueType(I.getType());
2289 EVT SrcVT = Src1.getValueType();
2290 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2292 if (SrcNumElts == MaskNumElts) {
2293 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2298 // Normalize the shuffle vector since mask and vector length don't match.
2299 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2300 // Mask is longer than the source vectors and is a multiple of the source
2301 // vectors. We can use concatenate vector to make the mask and vectors
2303 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2304 // The shuffle is concatenating two vectors together.
2305 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2310 // Pad both vectors with undefs to make them the same length as the mask.
2311 unsigned NumConcat = MaskNumElts / SrcNumElts;
2312 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2313 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2314 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2316 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2317 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2321 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2322 getCurDebugLoc(), VT,
2323 &MOps1[0], NumConcat);
2324 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2325 getCurDebugLoc(), VT,
2326 &MOps2[0], NumConcat);
2328 // Readjust mask for new input vector length.
2329 SmallVector<int, 8> MappedOps;
2330 for (unsigned i = 0; i != MaskNumElts; ++i) {
2332 if (Idx < (int)SrcNumElts)
2333 MappedOps.push_back(Idx);
2335 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2338 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2343 if (SrcNumElts > MaskNumElts) {
2344 // Analyze the access pattern of the vector to see if we can extract
2345 // two subvectors and do the shuffle. The analysis is done by calculating
2346 // the range of elements the mask access on both vectors.
2347 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2348 int MaxRange[2] = {-1, -1};
2350 for (unsigned i = 0; i != MaskNumElts; ++i) {
2356 if (Idx >= (int)SrcNumElts) {
2360 if (Idx > MaxRange[Input])
2361 MaxRange[Input] = Idx;
2362 if (Idx < MinRange[Input])
2363 MinRange[Input] = Idx;
2366 // Check if the access is smaller than the vector size and can we find
2367 // a reasonable extract index.
2368 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2370 int StartIdx[2]; // StartIdx to extract from
2371 for (int Input=0; Input < 2; ++Input) {
2372 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2373 RangeUse[Input] = 0; // Unused
2374 StartIdx[Input] = 0;
2375 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2376 // Fits within range but we should see if we can find a good
2377 // start index that is a multiple of the mask length.
2378 if (MaxRange[Input] < (int)MaskNumElts) {
2379 RangeUse[Input] = 1; // Extract from beginning of the vector
2380 StartIdx[Input] = 0;
2382 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2383 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2384 StartIdx[Input] + MaskNumElts < SrcNumElts)
2385 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2390 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2391 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2394 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2395 // Extract appropriate subvector and generate a vector shuffle
2396 for (int Input=0; Input < 2; ++Input) {
2397 SDValue &Src = Input == 0 ? Src1 : Src2;
2398 if (RangeUse[Input] == 0)
2399 Src = DAG.getUNDEF(VT);
2401 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2402 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2405 // Calculate new mask.
2406 SmallVector<int, 8> MappedOps;
2407 for (unsigned i = 0; i != MaskNumElts; ++i) {
2410 MappedOps.push_back(Idx);
2411 else if (Idx < (int)SrcNumElts)
2412 MappedOps.push_back(Idx - StartIdx[0]);
2414 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2417 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2423 // We can't use either concat vectors or extract subvectors so fall back to
2424 // replacing the shuffle with extract and build vector.
2425 // to insert and build vector.
2426 EVT EltVT = VT.getVectorElementType();
2427 EVT PtrVT = TLI.getPointerTy();
2428 SmallVector<SDValue,8> Ops;
2429 for (unsigned i = 0; i != MaskNumElts; ++i) {
2431 Ops.push_back(DAG.getUNDEF(EltVT));
2436 if (Idx < (int)SrcNumElts)
2437 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2438 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2440 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2442 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2448 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2449 VT, &Ops[0], Ops.size()));
2452 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2453 const Value *Op0 = I.getOperand(0);
2454 const Value *Op1 = I.getOperand(1);
2455 const Type *AggTy = I.getType();
2456 const Type *ValTy = Op1->getType();
2457 bool IntoUndef = isa<UndefValue>(Op0);
2458 bool FromUndef = isa<UndefValue>(Op1);
2460 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2461 I.idx_begin(), I.idx_end());
2463 SmallVector<EVT, 4> AggValueVTs;
2464 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2465 SmallVector<EVT, 4> ValValueVTs;
2466 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2468 unsigned NumAggValues = AggValueVTs.size();
2469 unsigned NumValValues = ValValueVTs.size();
2470 SmallVector<SDValue, 4> Values(NumAggValues);
2472 SDValue Agg = getValue(Op0);
2473 SDValue Val = getValue(Op1);
2475 // Copy the beginning value(s) from the original aggregate.
2476 for (; i != LinearIndex; ++i)
2477 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2478 SDValue(Agg.getNode(), Agg.getResNo() + i);
2479 // Copy values from the inserted value(s).
2480 for (; i != LinearIndex + NumValValues; ++i)
2481 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2482 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2483 // Copy remaining value(s) from the original aggregate.
2484 for (; i != NumAggValues; ++i)
2485 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2486 SDValue(Agg.getNode(), Agg.getResNo() + i);
2488 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2489 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2490 &Values[0], NumAggValues));
2493 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2494 const Value *Op0 = I.getOperand(0);
2495 const Type *AggTy = Op0->getType();
2496 const Type *ValTy = I.getType();
2497 bool OutOfUndef = isa<UndefValue>(Op0);
2499 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2500 I.idx_begin(), I.idx_end());
2502 SmallVector<EVT, 4> ValValueVTs;
2503 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2505 unsigned NumValValues = ValValueVTs.size();
2506 SmallVector<SDValue, 4> Values(NumValValues);
2508 SDValue Agg = getValue(Op0);
2509 // Copy out the selected value(s).
2510 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2511 Values[i - LinearIndex] =
2513 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2514 SDValue(Agg.getNode(), Agg.getResNo() + i);
2516 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2517 DAG.getVTList(&ValValueVTs[0], NumValValues),
2518 &Values[0], NumValValues));
2521 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2522 SDValue N = getValue(I.getOperand(0));
2523 const Type *Ty = I.getOperand(0)->getType();
2525 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2527 const Value *Idx = *OI;
2528 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2529 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2532 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2533 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2534 DAG.getIntPtrConstant(Offset));
2537 Ty = StTy->getElementType(Field);
2538 } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) {
2539 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2541 // Offset canonically 0 for unions, but type changes
2542 Ty = UnTy->getElementType(Field);
2544 Ty = cast<SequentialType>(Ty)->getElementType();
2546 // If this is a constant subscript, handle it quickly.
2547 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2548 if (CI->getZExtValue() == 0) continue;
2550 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2552 EVT PTy = TLI.getPointerTy();
2553 unsigned PtrBits = PTy.getSizeInBits();
2555 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2557 DAG.getConstant(Offs, MVT::i64));
2559 OffsVal = DAG.getIntPtrConstant(Offs);
2561 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2566 // N = N + Idx * ElementSize;
2567 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2568 TD->getTypeAllocSize(Ty));
2569 SDValue IdxN = getValue(Idx);
2571 // If the index is smaller or larger than intptr_t, truncate or extend
2573 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2575 // If this is a multiply by a power of two, turn it into a shl
2576 // immediately. This is a very common case.
2577 if (ElementSize != 1) {
2578 if (ElementSize.isPowerOf2()) {
2579 unsigned Amt = ElementSize.logBase2();
2580 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2581 N.getValueType(), IdxN,
2582 DAG.getConstant(Amt, TLI.getPointerTy()));
2584 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2585 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2586 N.getValueType(), IdxN, Scale);
2590 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2591 N.getValueType(), N, IdxN);
2598 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2599 // If this is a fixed sized alloca in the entry block of the function,
2600 // allocate it statically on the stack.
2601 if (FuncInfo.StaticAllocaMap.count(&I))
2602 return; // getValue will auto-populate this.
2604 const Type *Ty = I.getAllocatedType();
2605 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2607 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2610 SDValue AllocSize = getValue(I.getArraySize());
2612 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2614 DAG.getConstant(TySize, AllocSize.getValueType()));
2616 EVT IntPtr = TLI.getPointerTy();
2617 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2619 // Handle alignment. If the requested alignment is less than or equal to
2620 // the stack alignment, ignore it. If the size is greater than or equal to
2621 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2622 unsigned StackAlign =
2623 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2624 if (Align <= StackAlign)
2627 // Round the size of the allocation up to the stack alignment size
2628 // by add SA-1 to the size.
2629 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2630 AllocSize.getValueType(), AllocSize,
2631 DAG.getIntPtrConstant(StackAlign-1));
2633 // Mask out the low bits for alignment purposes.
2634 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2635 AllocSize.getValueType(), AllocSize,
2636 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2638 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2639 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2640 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2643 DAG.setRoot(DSA.getValue(1));
2645 // Inform the Frame Information that we have just allocated a variable-sized
2647 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2650 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
2651 const Value *SV = I.getOperand(0);
2652 SDValue Ptr = getValue(SV);
2654 const Type *Ty = I.getType();
2656 bool isVolatile = I.isVolatile();
2657 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2658 unsigned Alignment = I.getAlignment();
2660 SmallVector<EVT, 4> ValueVTs;
2661 SmallVector<uint64_t, 4> Offsets;
2662 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2663 unsigned NumValues = ValueVTs.size();
2668 bool ConstantMemory = false;
2670 // Serialize volatile loads with other side effects.
2672 else if (AA->pointsToConstantMemory(SV)) {
2673 // Do not serialize (non-volatile) loads of constant memory with anything.
2674 Root = DAG.getEntryNode();
2675 ConstantMemory = true;
2677 // Do not serialize non-volatile loads against each other.
2678 Root = DAG.getRoot();
2681 SmallVector<SDValue, 4> Values(NumValues);
2682 SmallVector<SDValue, 4> Chains(NumValues);
2683 EVT PtrVT = Ptr.getValueType();
2684 for (unsigned i = 0; i != NumValues; ++i) {
2685 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2687 DAG.getConstant(Offsets[i], PtrVT));
2688 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2689 A, SV, Offsets[i], isVolatile,
2690 isNonTemporal, Alignment);
2693 Chains[i] = L.getValue(1);
2696 if (!ConstantMemory) {
2697 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2698 MVT::Other, &Chains[0], NumValues);
2702 PendingLoads.push_back(Chain);
2705 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2706 DAG.getVTList(&ValueVTs[0], NumValues),
2707 &Values[0], NumValues));
2710 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
2711 const Value *SrcV = I.getOperand(0);
2712 const Value *PtrV = I.getOperand(1);
2714 SmallVector<EVT, 4> ValueVTs;
2715 SmallVector<uint64_t, 4> Offsets;
2716 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2717 unsigned NumValues = ValueVTs.size();
2721 // Get the lowered operands. Note that we do this after
2722 // checking if NumResults is zero, because with zero results
2723 // the operands won't have values in the map.
2724 SDValue Src = getValue(SrcV);
2725 SDValue Ptr = getValue(PtrV);
2727 SDValue Root = getRoot();
2728 SmallVector<SDValue, 4> Chains(NumValues);
2729 EVT PtrVT = Ptr.getValueType();
2730 bool isVolatile = I.isVolatile();
2731 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2732 unsigned Alignment = I.getAlignment();
2734 for (unsigned i = 0; i != NumValues; ++i) {
2735 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2736 DAG.getConstant(Offsets[i], PtrVT));
2737 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2738 SDValue(Src.getNode(), Src.getResNo() + i),
2739 Add, PtrV, Offsets[i], isVolatile,
2740 isNonTemporal, Alignment);
2743 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2744 MVT::Other, &Chains[0], NumValues));
2747 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2749 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
2750 unsigned Intrinsic) {
2751 bool HasChain = !I.doesNotAccessMemory();
2752 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2754 // Build the operand list.
2755 SmallVector<SDValue, 8> Ops;
2756 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2758 // We don't need to serialize loads against other loads.
2759 Ops.push_back(DAG.getRoot());
2761 Ops.push_back(getRoot());
2765 // Info is set by getTgtMemInstrinsic
2766 TargetLowering::IntrinsicInfo Info;
2767 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2769 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2770 if (!IsTgtIntrinsic)
2771 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2773 // Add all operands of the call to the operand list.
2774 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2775 SDValue Op = getValue(I.getOperand(i));
2776 assert(TLI.isTypeLegal(Op.getValueType()) &&
2777 "Intrinsic uses a non-legal type?");
2781 SmallVector<EVT, 4> ValueVTs;
2782 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2784 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2785 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2786 "Intrinsic uses a non-legal type?");
2791 ValueVTs.push_back(MVT::Other);
2793 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2797 if (IsTgtIntrinsic) {
2798 // This is target intrinsic that touches memory
2799 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2800 VTs, &Ops[0], Ops.size(),
2801 Info.memVT, Info.ptrVal, Info.offset,
2802 Info.align, Info.vol,
2803 Info.readMem, Info.writeMem);
2804 } else if (!HasChain) {
2805 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2806 VTs, &Ops[0], Ops.size());
2807 } else if (!I.getType()->isVoidTy()) {
2808 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2809 VTs, &Ops[0], Ops.size());
2811 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2812 VTs, &Ops[0], Ops.size());
2816 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2818 PendingLoads.push_back(Chain);
2823 if (!I.getType()->isVoidTy()) {
2824 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2825 EVT VT = TLI.getValueType(PTy);
2826 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2829 setValue(&I, Result);
2833 /// GetSignificand - Get the significand and build it into a floating-point
2834 /// number with exponent of 1:
2836 /// Op = (Op & 0x007fffff) | 0x3f800000;
2838 /// where Op is the hexidecimal representation of floating point value.
2840 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
2841 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2842 DAG.getConstant(0x007fffff, MVT::i32));
2843 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2844 DAG.getConstant(0x3f800000, MVT::i32));
2845 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
2848 /// GetExponent - Get the exponent:
2850 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
2852 /// where Op is the hexidecimal representation of floating point value.
2854 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
2856 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2857 DAG.getConstant(0x7f800000, MVT::i32));
2858 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
2859 DAG.getConstant(23, TLI.getPointerTy()));
2860 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2861 DAG.getConstant(127, MVT::i32));
2862 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
2865 /// getF32Constant - Get 32-bit floating point constant.
2867 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2868 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2871 /// Inlined utility function to implement binary input atomic intrinsics for
2872 /// visitIntrinsicCall: I is a call instruction
2873 /// Op is the associated NodeType for I
2875 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
2877 SDValue Root = getRoot();
2879 DAG.getAtomic(Op, getCurDebugLoc(),
2880 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2882 getValue(I.getOperand(1)),
2883 getValue(I.getOperand(2)),
2886 DAG.setRoot(L.getValue(1));
2890 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2892 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
2893 SDValue Op1 = getValue(I.getOperand(1));
2894 SDValue Op2 = getValue(I.getOperand(2));
2896 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
2897 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
2901 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2902 /// limited-precision mode.
2904 SelectionDAGBuilder::visitExp(const CallInst &I) {
2906 DebugLoc dl = getCurDebugLoc();
2908 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2909 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2910 SDValue Op = getValue(I.getOperand(1));
2912 // Put the exponent in the right bit position for later addition to the
2915 // #define LOG2OFe 1.4426950f
2916 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2917 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
2918 getF32Constant(DAG, 0x3fb8aa3b));
2919 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
2921 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2922 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2923 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
2925 // IntegerPartOfX <<= 23;
2926 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
2927 DAG.getConstant(23, TLI.getPointerTy()));
2929 if (LimitFloatPrecision <= 6) {
2930 // For floating-point precision of 6:
2932 // TwoToFractionalPartOfX =
2934 // (0.735607626f + 0.252464424f * x) * x;
2936 // error 0.0144103317, which is 6 bits
2937 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2938 getF32Constant(DAG, 0x3e814304));
2939 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2940 getF32Constant(DAG, 0x3f3c50c8));
2941 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2942 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2943 getF32Constant(DAG, 0x3f7f5e7e));
2944 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
2946 // Add the exponent into the result in integer domain.
2947 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2948 TwoToFracPartOfX, IntegerPartOfX);
2950 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
2951 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2952 // For floating-point precision of 12:
2954 // TwoToFractionalPartOfX =
2957 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2959 // 0.000107046256 error, which is 13 to 14 bits
2960 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2961 getF32Constant(DAG, 0x3da235e3));
2962 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2963 getF32Constant(DAG, 0x3e65b8f3));
2964 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2965 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2966 getF32Constant(DAG, 0x3f324b07));
2967 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
2968 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
2969 getF32Constant(DAG, 0x3f7ff8fd));
2970 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
2972 // Add the exponent into the result in integer domain.
2973 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2974 TwoToFracPartOfX, IntegerPartOfX);
2976 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
2977 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2978 // For floating-point precision of 18:
2980 // TwoToFractionalPartOfX =
2984 // (0.554906021e-1f +
2985 // (0.961591928e-2f +
2986 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2988 // error 2.47208000*10^(-7), which is better than 18 bits
2989 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2990 getF32Constant(DAG, 0x3924b03e));
2991 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2992 getF32Constant(DAG, 0x3ab24b87));
2993 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2994 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2995 getF32Constant(DAG, 0x3c1d8c17));
2996 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
2997 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
2998 getF32Constant(DAG, 0x3d634a1d));
2999 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3000 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3001 getF32Constant(DAG, 0x3e75fe14));
3002 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3003 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3004 getF32Constant(DAG, 0x3f317234));
3005 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3006 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3007 getF32Constant(DAG, 0x3f800000));
3008 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3011 // Add the exponent into the result in integer domain.
3012 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3013 TwoToFracPartOfX, IntegerPartOfX);
3015 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3018 // No special expansion.
3019 result = DAG.getNode(ISD::FEXP, dl,
3020 getValue(I.getOperand(1)).getValueType(),
3021 getValue(I.getOperand(1)));
3024 setValue(&I, result);
3027 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3028 /// limited-precision mode.
3030 SelectionDAGBuilder::visitLog(const CallInst &I) {
3032 DebugLoc dl = getCurDebugLoc();
3034 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3035 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3036 SDValue Op = getValue(I.getOperand(1));
3037 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3039 // Scale the exponent by log(2) [0.69314718f].
3040 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3041 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3042 getF32Constant(DAG, 0x3f317218));
3044 // Get the significand and build it into a floating-point number with
3046 SDValue X = GetSignificand(DAG, Op1, dl);
3048 if (LimitFloatPrecision <= 6) {
3049 // For floating-point precision of 6:
3053 // (1.4034025f - 0.23903021f * x) * x;
3055 // error 0.0034276066, which is better than 8 bits
3056 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3057 getF32Constant(DAG, 0xbe74c456));
3058 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3059 getF32Constant(DAG, 0x3fb3a2b1));
3060 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3061 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3062 getF32Constant(DAG, 0x3f949a29));
3064 result = DAG.getNode(ISD::FADD, dl,
3065 MVT::f32, LogOfExponent, LogOfMantissa);
3066 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3067 // For floating-point precision of 12:
3073 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3075 // error 0.000061011436, which is 14 bits
3076 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3077 getF32Constant(DAG, 0xbd67b6d6));
3078 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3079 getF32Constant(DAG, 0x3ee4f4b8));
3080 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3081 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3082 getF32Constant(DAG, 0x3fbc278b));
3083 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3084 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3085 getF32Constant(DAG, 0x40348e95));
3086 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3087 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3088 getF32Constant(DAG, 0x3fdef31a));
3090 result = DAG.getNode(ISD::FADD, dl,
3091 MVT::f32, LogOfExponent, LogOfMantissa);
3092 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3093 // For floating-point precision of 18:
3101 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3103 // error 0.0000023660568, which is better than 18 bits
3104 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3105 getF32Constant(DAG, 0xbc91e5ac));
3106 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3107 getF32Constant(DAG, 0x3e4350aa));
3108 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3109 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3110 getF32Constant(DAG, 0x3f60d3e3));
3111 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3112 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3113 getF32Constant(DAG, 0x4011cdf0));
3114 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3115 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3116 getF32Constant(DAG, 0x406cfd1c));
3117 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3118 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3119 getF32Constant(DAG, 0x408797cb));
3120 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3121 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3122 getF32Constant(DAG, 0x4006dcab));
3124 result = DAG.getNode(ISD::FADD, dl,
3125 MVT::f32, LogOfExponent, LogOfMantissa);
3128 // No special expansion.
3129 result = DAG.getNode(ISD::FLOG, dl,
3130 getValue(I.getOperand(1)).getValueType(),
3131 getValue(I.getOperand(1)));
3134 setValue(&I, result);
3137 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3138 /// limited-precision mode.
3140 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3142 DebugLoc dl = getCurDebugLoc();
3144 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3145 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3146 SDValue Op = getValue(I.getOperand(1));
3147 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3149 // Get the exponent.
3150 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3152 // Get the significand and build it into a floating-point number with
3154 SDValue X = GetSignificand(DAG, Op1, dl);
3156 // Different possible minimax approximations of significand in
3157 // floating-point for various degrees of accuracy over [1,2].
3158 if (LimitFloatPrecision <= 6) {
3159 // For floating-point precision of 6:
3161 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3163 // error 0.0049451742, which is more than 7 bits
3164 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3165 getF32Constant(DAG, 0xbeb08fe0));
3166 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3167 getF32Constant(DAG, 0x40019463));
3168 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3169 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3170 getF32Constant(DAG, 0x3fd6633d));
3172 result = DAG.getNode(ISD::FADD, dl,
3173 MVT::f32, LogOfExponent, Log2ofMantissa);
3174 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3175 // For floating-point precision of 12:
3181 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3183 // error 0.0000876136000, which is better than 13 bits
3184 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3185 getF32Constant(DAG, 0xbda7262e));
3186 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3187 getF32Constant(DAG, 0x3f25280b));
3188 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3189 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3190 getF32Constant(DAG, 0x4007b923));
3191 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3192 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3193 getF32Constant(DAG, 0x40823e2f));
3194 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3195 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3196 getF32Constant(DAG, 0x4020d29c));
3198 result = DAG.getNode(ISD::FADD, dl,
3199 MVT::f32, LogOfExponent, Log2ofMantissa);
3200 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3201 // For floating-point precision of 18:
3210 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3212 // error 0.0000018516, which is better than 18 bits
3213 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3214 getF32Constant(DAG, 0xbcd2769e));
3215 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3216 getF32Constant(DAG, 0x3e8ce0b9));
3217 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3218 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3219 getF32Constant(DAG, 0x3fa22ae7));
3220 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3221 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3222 getF32Constant(DAG, 0x40525723));
3223 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3224 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3225 getF32Constant(DAG, 0x40aaf200));
3226 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3227 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3228 getF32Constant(DAG, 0x40c39dad));
3229 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3230 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3231 getF32Constant(DAG, 0x4042902c));
3233 result = DAG.getNode(ISD::FADD, dl,
3234 MVT::f32, LogOfExponent, Log2ofMantissa);
3237 // No special expansion.
3238 result = DAG.getNode(ISD::FLOG2, dl,
3239 getValue(I.getOperand(1)).getValueType(),
3240 getValue(I.getOperand(1)));
3243 setValue(&I, result);
3246 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3247 /// limited-precision mode.
3249 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3251 DebugLoc dl = getCurDebugLoc();
3253 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3254 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3255 SDValue Op = getValue(I.getOperand(1));
3256 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3258 // Scale the exponent by log10(2) [0.30102999f].
3259 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3260 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3261 getF32Constant(DAG, 0x3e9a209a));
3263 // Get the significand and build it into a floating-point number with
3265 SDValue X = GetSignificand(DAG, Op1, dl);
3267 if (LimitFloatPrecision <= 6) {
3268 // For floating-point precision of 6:
3270 // Log10ofMantissa =
3272 // (0.60948995f - 0.10380950f * x) * x;
3274 // error 0.0014886165, which is 6 bits
3275 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3276 getF32Constant(DAG, 0xbdd49a13));
3277 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3278 getF32Constant(DAG, 0x3f1c0789));
3279 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3280 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3281 getF32Constant(DAG, 0x3f011300));
3283 result = DAG.getNode(ISD::FADD, dl,
3284 MVT::f32, LogOfExponent, Log10ofMantissa);
3285 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3286 // For floating-point precision of 12:
3288 // Log10ofMantissa =
3291 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3293 // error 0.00019228036, which is better than 12 bits
3294 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3295 getF32Constant(DAG, 0x3d431f31));
3296 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3297 getF32Constant(DAG, 0x3ea21fb2));
3298 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3299 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3300 getF32Constant(DAG, 0x3f6ae232));
3301 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3302 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3303 getF32Constant(DAG, 0x3f25f7c3));
3305 result = DAG.getNode(ISD::FADD, dl,
3306 MVT::f32, LogOfExponent, Log10ofMantissa);
3307 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3308 // For floating-point precision of 18:
3310 // Log10ofMantissa =
3315 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3317 // error 0.0000037995730, which is better than 18 bits
3318 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3319 getF32Constant(DAG, 0x3c5d51ce));
3320 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3321 getF32Constant(DAG, 0x3e00685a));
3322 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3323 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3324 getF32Constant(DAG, 0x3efb6798));
3325 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3326 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3327 getF32Constant(DAG, 0x3f88d192));
3328 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3329 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3330 getF32Constant(DAG, 0x3fc4316c));
3331 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3332 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3333 getF32Constant(DAG, 0x3f57ce70));
3335 result = DAG.getNode(ISD::FADD, dl,
3336 MVT::f32, LogOfExponent, Log10ofMantissa);
3339 // No special expansion.
3340 result = DAG.getNode(ISD::FLOG10, dl,
3341 getValue(I.getOperand(1)).getValueType(),
3342 getValue(I.getOperand(1)));
3345 setValue(&I, result);
3348 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3349 /// limited-precision mode.
3351 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3353 DebugLoc dl = getCurDebugLoc();
3355 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3356 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3357 SDValue Op = getValue(I.getOperand(1));
3359 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3361 // FractionalPartOfX = x - (float)IntegerPartOfX;
3362 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3363 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3365 // IntegerPartOfX <<= 23;
3366 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3367 DAG.getConstant(23, TLI.getPointerTy()));
3369 if (LimitFloatPrecision <= 6) {
3370 // For floating-point precision of 6:
3372 // TwoToFractionalPartOfX =
3374 // (0.735607626f + 0.252464424f * x) * x;
3376 // error 0.0144103317, which is 6 bits
3377 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3378 getF32Constant(DAG, 0x3e814304));
3379 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3380 getF32Constant(DAG, 0x3f3c50c8));
3381 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3382 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3383 getF32Constant(DAG, 0x3f7f5e7e));
3384 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3385 SDValue TwoToFractionalPartOfX =
3386 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3388 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3389 MVT::f32, TwoToFractionalPartOfX);
3390 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3391 // For floating-point precision of 12:
3393 // TwoToFractionalPartOfX =
3396 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3398 // error 0.000107046256, which is 13 to 14 bits
3399 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3400 getF32Constant(DAG, 0x3da235e3));
3401 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3402 getF32Constant(DAG, 0x3e65b8f3));
3403 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3404 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3405 getF32Constant(DAG, 0x3f324b07));
3406 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3407 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3408 getF32Constant(DAG, 0x3f7ff8fd));
3409 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3410 SDValue TwoToFractionalPartOfX =
3411 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3413 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3414 MVT::f32, TwoToFractionalPartOfX);
3415 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3416 // For floating-point precision of 18:
3418 // TwoToFractionalPartOfX =
3422 // (0.554906021e-1f +
3423 // (0.961591928e-2f +
3424 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3425 // error 2.47208000*10^(-7), which is better than 18 bits
3426 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3427 getF32Constant(DAG, 0x3924b03e));
3428 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3429 getF32Constant(DAG, 0x3ab24b87));
3430 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3431 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3432 getF32Constant(DAG, 0x3c1d8c17));
3433 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3434 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3435 getF32Constant(DAG, 0x3d634a1d));
3436 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3437 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3438 getF32Constant(DAG, 0x3e75fe14));
3439 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3440 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3441 getF32Constant(DAG, 0x3f317234));
3442 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3443 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3444 getF32Constant(DAG, 0x3f800000));
3445 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3446 SDValue TwoToFractionalPartOfX =
3447 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3449 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3450 MVT::f32, TwoToFractionalPartOfX);
3453 // No special expansion.
3454 result = DAG.getNode(ISD::FEXP2, dl,
3455 getValue(I.getOperand(1)).getValueType(),
3456 getValue(I.getOperand(1)));
3459 setValue(&I, result);
3462 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3463 /// limited-precision mode with x == 10.0f.
3465 SelectionDAGBuilder::visitPow(const CallInst &I) {
3467 const Value *Val = I.getOperand(1);
3468 DebugLoc dl = getCurDebugLoc();
3469 bool IsExp10 = false;
3471 if (getValue(Val).getValueType() == MVT::f32 &&
3472 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3473 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3474 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3475 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3477 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3482 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3483 SDValue Op = getValue(I.getOperand(2));
3485 // Put the exponent in the right bit position for later addition to the
3488 // #define LOG2OF10 3.3219281f
3489 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3490 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3491 getF32Constant(DAG, 0x40549a78));
3492 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3494 // FractionalPartOfX = x - (float)IntegerPartOfX;
3495 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3496 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3498 // IntegerPartOfX <<= 23;
3499 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3500 DAG.getConstant(23, TLI.getPointerTy()));
3502 if (LimitFloatPrecision <= 6) {
3503 // For floating-point precision of 6:
3505 // twoToFractionalPartOfX =
3507 // (0.735607626f + 0.252464424f * x) * x;
3509 // error 0.0144103317, which is 6 bits
3510 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3511 getF32Constant(DAG, 0x3e814304));
3512 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3513 getF32Constant(DAG, 0x3f3c50c8));
3514 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3515 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3516 getF32Constant(DAG, 0x3f7f5e7e));
3517 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3518 SDValue TwoToFractionalPartOfX =
3519 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3521 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3522 MVT::f32, TwoToFractionalPartOfX);
3523 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3524 // For floating-point precision of 12:
3526 // TwoToFractionalPartOfX =
3529 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3531 // error 0.000107046256, which is 13 to 14 bits
3532 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3533 getF32Constant(DAG, 0x3da235e3));
3534 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3535 getF32Constant(DAG, 0x3e65b8f3));
3536 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3537 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3538 getF32Constant(DAG, 0x3f324b07));
3539 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3540 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3541 getF32Constant(DAG, 0x3f7ff8fd));
3542 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3543 SDValue TwoToFractionalPartOfX =
3544 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3546 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3547 MVT::f32, TwoToFractionalPartOfX);
3548 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3549 // For floating-point precision of 18:
3551 // TwoToFractionalPartOfX =
3555 // (0.554906021e-1f +
3556 // (0.961591928e-2f +
3557 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3558 // error 2.47208000*10^(-7), which is better than 18 bits
3559 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3560 getF32Constant(DAG, 0x3924b03e));
3561 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3562 getF32Constant(DAG, 0x3ab24b87));
3563 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3564 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3565 getF32Constant(DAG, 0x3c1d8c17));
3566 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3567 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3568 getF32Constant(DAG, 0x3d634a1d));
3569 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3570 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3571 getF32Constant(DAG, 0x3e75fe14));
3572 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3573 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3574 getF32Constant(DAG, 0x3f317234));
3575 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3576 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3577 getF32Constant(DAG, 0x3f800000));
3578 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3579 SDValue TwoToFractionalPartOfX =
3580 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3582 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3583 MVT::f32, TwoToFractionalPartOfX);
3586 // No special expansion.
3587 result = DAG.getNode(ISD::FPOW, dl,
3588 getValue(I.getOperand(1)).getValueType(),
3589 getValue(I.getOperand(1)),
3590 getValue(I.getOperand(2)));
3593 setValue(&I, result);
3597 /// ExpandPowI - Expand a llvm.powi intrinsic.
3598 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3599 SelectionDAG &DAG) {
3600 // If RHS is a constant, we can expand this out to a multiplication tree,
3601 // otherwise we end up lowering to a call to __powidf2 (for example). When
3602 // optimizing for size, we only want to do this if the expansion would produce
3603 // a small number of multiplies, otherwise we do the full expansion.
3604 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3605 // Get the exponent as a positive value.
3606 unsigned Val = RHSC->getSExtValue();
3607 if ((int)Val < 0) Val = -Val;
3609 // powi(x, 0) -> 1.0
3611 return DAG.getConstantFP(1.0, LHS.getValueType());
3613 const Function *F = DAG.getMachineFunction().getFunction();
3614 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3615 // If optimizing for size, don't insert too many multiplies. This
3616 // inserts up to 5 multiplies.
3617 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3618 // We use the simple binary decomposition method to generate the multiply
3619 // sequence. There are more optimal ways to do this (for example,
3620 // powi(x,15) generates one more multiply than it should), but this has
3621 // the benefit of being both really simple and much better than a libcall.
3622 SDValue Res; // Logically starts equal to 1.0
3623 SDValue CurSquare = LHS;
3627 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3629 Res = CurSquare; // 1.0*CurSquare.
3632 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3633 CurSquare, CurSquare);
3637 // If the original was negative, invert the result, producing 1/(x*x*x).
3638 if (RHSC->getSExtValue() < 0)
3639 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3640 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3645 // Otherwise, expand to a libcall.
3646 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3650 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3651 /// we want to emit this as a call to a named external function, return the name
3652 /// otherwise lower it and return null.
3654 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
3655 DebugLoc dl = getCurDebugLoc();
3658 switch (Intrinsic) {
3660 // By default, turn this into a target intrinsic node.
3661 visitTargetIntrinsic(I, Intrinsic);
3663 case Intrinsic::vastart: visitVAStart(I); return 0;
3664 case Intrinsic::vaend: visitVAEnd(I); return 0;
3665 case Intrinsic::vacopy: visitVACopy(I); return 0;
3666 case Intrinsic::returnaddress:
3667 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3668 getValue(I.getOperand(1))));
3670 case Intrinsic::frameaddress:
3671 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3672 getValue(I.getOperand(1))));
3674 case Intrinsic::setjmp:
3675 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3676 case Intrinsic::longjmp:
3677 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3678 case Intrinsic::memcpy: {
3679 // Assert for address < 256 since we support only user defined address
3681 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3683 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3685 "Unknown address space");
3686 SDValue Op1 = getValue(I.getOperand(1));
3687 SDValue Op2 = getValue(I.getOperand(2));
3688 SDValue Op3 = getValue(I.getOperand(3));
3689 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3690 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3691 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
3692 I.getOperand(1), 0, I.getOperand(2), 0));
3695 case Intrinsic::memset: {
3696 // Assert for address < 256 since we support only user defined address
3698 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3700 "Unknown address space");
3701 SDValue Op1 = getValue(I.getOperand(1));
3702 SDValue Op2 = getValue(I.getOperand(2));
3703 SDValue Op3 = getValue(I.getOperand(3));
3704 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3705 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3706 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3707 I.getOperand(1), 0));
3710 case Intrinsic::memmove: {
3711 // Assert for address < 256 since we support only user defined address
3713 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3715 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3717 "Unknown address space");
3718 SDValue Op1 = getValue(I.getOperand(1));
3719 SDValue Op2 = getValue(I.getOperand(2));
3720 SDValue Op3 = getValue(I.getOperand(3));
3721 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3722 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3724 // If the source and destination are known to not be aliases, we can
3725 // lower memmove as memcpy.
3726 uint64_t Size = -1ULL;
3727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3728 Size = C->getZExtValue();
3729 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3730 AliasAnalysis::NoAlias) {
3731 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3732 false, I.getOperand(1), 0, I.getOperand(2), 0));
3736 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3737 I.getOperand(1), 0, I.getOperand(2), 0));
3740 case Intrinsic::dbg_declare: {
3741 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3742 // The real handling of this intrinsic is in FastISel.
3743 if (OptLevel != CodeGenOpt::None)
3744 // FIXME: Variable debug info is not supported here.
3746 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3747 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3750 MDNode *Variable = DI.getVariable();
3751 const Value *Address = DI.getAddress();
3754 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3755 Address = BCI->getOperand(0);
3756 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3757 // Don't handle byval struct arguments or VLAs, for example.
3760 DenseMap<const AllocaInst*, int>::iterator SI =
3761 FuncInfo.StaticAllocaMap.find(AI);
3762 if (SI == FuncInfo.StaticAllocaMap.end())
3764 int FI = SI->second;
3766 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3767 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
3768 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
3771 case Intrinsic::dbg_value: {
3772 const DbgValueInst &DI = cast<DbgValueInst>(I);
3773 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3776 MDNode *Variable = DI.getVariable();
3777 uint64_t Offset = DI.getOffset();
3778 const Value *V = DI.getValue();
3782 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
3783 // but do not always have a corresponding SDNode built. The SDNodeOrder
3784 // absolute, but not relative, values are different depending on whether
3785 // debug info exists.
3787 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
3788 DAG.AddDbgValue(DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder));
3790 SDValue &N = NodeMap[V];
3792 DAG.AddDbgValue(DAG.getDbgValue(Variable, N.getNode(),
3793 N.getResNo(), Offset, dl, SDNodeOrder),
3796 // We may expand this to cover more cases. One case where we have no
3797 // data available is an unreferenced parameter; we need this fallback.
3798 DAG.AddDbgValue(DAG.getDbgValue(Variable,
3799 UndefValue::get(V->getType()),
3800 Offset, dl, SDNodeOrder));
3803 // Build a debug info table entry.
3804 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3805 V = BCI->getOperand(0);
3806 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
3807 // Don't handle byval struct arguments or VLAs, for example.
3810 DenseMap<const AllocaInst*, int>::iterator SI =
3811 FuncInfo.StaticAllocaMap.find(AI);
3812 if (SI == FuncInfo.StaticAllocaMap.end())
3814 int FI = SI->second;
3816 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3817 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
3818 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
3821 case Intrinsic::eh_exception: {
3822 // Insert the EXCEPTIONADDR instruction.
3823 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3824 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3826 Ops[0] = DAG.getRoot();
3827 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3829 DAG.setRoot(Op.getValue(1));
3833 case Intrinsic::eh_selector: {
3834 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3835 if (CurMBB->isLandingPad())
3836 AddCatchInfo(I, &MMI, CurMBB);
3839 FuncInfo.CatchInfoLost.insert(&I);
3841 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3842 unsigned Reg = TLI.getExceptionSelectorRegister();
3843 if (Reg) CurMBB->addLiveIn(Reg);
3846 // Insert the EHSELECTION instruction.
3847 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3849 Ops[0] = getValue(I.getOperand(1));
3851 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3852 DAG.setRoot(Op.getValue(1));
3853 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
3857 case Intrinsic::eh_typeid_for: {
3858 // Find the type id for the given typeinfo.
3859 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3860 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
3861 Res = DAG.getConstant(TypeID, MVT::i32);
3866 case Intrinsic::eh_return_i32:
3867 case Intrinsic::eh_return_i64:
3868 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
3869 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3872 getValue(I.getOperand(1)),
3873 getValue(I.getOperand(2))));
3875 case Intrinsic::eh_unwind_init:
3876 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
3878 case Intrinsic::eh_dwarf_cfa: {
3879 EVT VT = getValue(I.getOperand(1)).getValueType();
3880 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3881 TLI.getPointerTy());
3882 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3884 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
3885 TLI.getPointerTy()),
3887 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
3889 DAG.getConstant(0, TLI.getPointerTy()));
3890 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3894 case Intrinsic::eh_sjlj_callsite: {
3895 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3896 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3897 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3898 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
3900 MMI.setCurrentCallSite(CI->getZExtValue());
3904 case Intrinsic::convertff:
3905 case Intrinsic::convertfsi:
3906 case Intrinsic::convertfui:
3907 case Intrinsic::convertsif:
3908 case Intrinsic::convertuif:
3909 case Intrinsic::convertss:
3910 case Intrinsic::convertsu:
3911 case Intrinsic::convertus:
3912 case Intrinsic::convertuu: {
3913 ISD::CvtCode Code = ISD::CVT_INVALID;
3914 switch (Intrinsic) {
3915 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3916 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3917 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3918 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3919 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3920 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3921 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3922 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3923 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3925 EVT DestVT = TLI.getValueType(I.getType());
3926 const Value *Op1 = I.getOperand(1);
3927 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3928 DAG.getValueType(DestVT),
3929 DAG.getValueType(getValue(Op1).getValueType()),
3930 getValue(I.getOperand(2)),
3931 getValue(I.getOperand(3)),
3936 case Intrinsic::sqrt:
3937 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3938 getValue(I.getOperand(1)).getValueType(),
3939 getValue(I.getOperand(1))));
3941 case Intrinsic::powi:
3942 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3943 getValue(I.getOperand(2)), DAG));
3945 case Intrinsic::sin:
3946 setValue(&I, DAG.getNode(ISD::FSIN, dl,
3947 getValue(I.getOperand(1)).getValueType(),
3948 getValue(I.getOperand(1))));
3950 case Intrinsic::cos:
3951 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3952 getValue(I.getOperand(1)).getValueType(),
3953 getValue(I.getOperand(1))));
3955 case Intrinsic::log:
3958 case Intrinsic::log2:
3961 case Intrinsic::log10:
3964 case Intrinsic::exp:
3967 case Intrinsic::exp2:
3970 case Intrinsic::pow:
3973 case Intrinsic::convert_to_fp16:
3974 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
3975 MVT::i16, getValue(I.getOperand(1))));
3977 case Intrinsic::convert_from_fp16:
3978 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
3979 MVT::f32, getValue(I.getOperand(1))));
3981 case Intrinsic::pcmarker: {
3982 SDValue Tmp = getValue(I.getOperand(1));
3983 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
3986 case Intrinsic::readcyclecounter: {
3987 SDValue Op = getRoot();
3988 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
3989 DAG.getVTList(MVT::i64, MVT::Other),
3992 DAG.setRoot(Res.getValue(1));
3995 case Intrinsic::bswap:
3996 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
3997 getValue(I.getOperand(1)).getValueType(),
3998 getValue(I.getOperand(1))));
4000 case Intrinsic::cttz: {
4001 SDValue Arg = getValue(I.getOperand(1));
4002 EVT Ty = Arg.getValueType();
4003 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4006 case Intrinsic::ctlz: {
4007 SDValue Arg = getValue(I.getOperand(1));
4008 EVT Ty = Arg.getValueType();
4009 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4012 case Intrinsic::ctpop: {
4013 SDValue Arg = getValue(I.getOperand(1));
4014 EVT Ty = Arg.getValueType();
4015 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4018 case Intrinsic::stacksave: {
4019 SDValue Op = getRoot();
4020 Res = DAG.getNode(ISD::STACKSAVE, dl,
4021 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4023 DAG.setRoot(Res.getValue(1));
4026 case Intrinsic::stackrestore: {
4027 Res = getValue(I.getOperand(1));
4028 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4031 case Intrinsic::stackprotector: {
4032 // Emit code into the DAG to store the stack guard onto the stack.
4033 MachineFunction &MF = DAG.getMachineFunction();
4034 MachineFrameInfo *MFI = MF.getFrameInfo();
4035 EVT PtrTy = TLI.getPointerTy();
4037 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4038 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4040 int FI = FuncInfo.StaticAllocaMap[Slot];
4041 MFI->setStackProtectorIndex(FI);
4043 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4045 // Store the stack protector onto the stack.
4046 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4047 PseudoSourceValue::getFixedStack(FI),
4053 case Intrinsic::objectsize: {
4054 // If we don't know by now, we're never going to know.
4055 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4057 assert(CI && "Non-constant type in __builtin_object_size?");
4059 SDValue Arg = getValue(I.getOperand(0));
4060 EVT Ty = Arg.getValueType();
4062 if (CI->getZExtValue() == 0)
4063 Res = DAG.getConstant(-1ULL, Ty);
4065 Res = DAG.getConstant(0, Ty);
4070 case Intrinsic::var_annotation:
4071 // Discard annotate attributes
4074 case Intrinsic::init_trampoline: {
4075 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4079 Ops[1] = getValue(I.getOperand(1));
4080 Ops[2] = getValue(I.getOperand(2));
4081 Ops[3] = getValue(I.getOperand(3));
4082 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4083 Ops[5] = DAG.getSrcValue(F);
4085 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4086 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4090 DAG.setRoot(Res.getValue(1));
4093 case Intrinsic::gcroot:
4095 const Value *Alloca = I.getOperand(1);
4096 const Constant *TypeMap = cast<Constant>(I.getOperand(2));
4098 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4099 GFI->addStackRoot(FI->getIndex(), TypeMap);
4102 case Intrinsic::gcread:
4103 case Intrinsic::gcwrite:
4104 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4106 case Intrinsic::flt_rounds:
4107 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4109 case Intrinsic::trap:
4110 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4112 case Intrinsic::uadd_with_overflow:
4113 return implVisitAluOverflow(I, ISD::UADDO);
4114 case Intrinsic::sadd_with_overflow:
4115 return implVisitAluOverflow(I, ISD::SADDO);
4116 case Intrinsic::usub_with_overflow:
4117 return implVisitAluOverflow(I, ISD::USUBO);
4118 case Intrinsic::ssub_with_overflow:
4119 return implVisitAluOverflow(I, ISD::SSUBO);
4120 case Intrinsic::umul_with_overflow:
4121 return implVisitAluOverflow(I, ISD::UMULO);
4122 case Intrinsic::smul_with_overflow:
4123 return implVisitAluOverflow(I, ISD::SMULO);
4125 case Intrinsic::prefetch: {
4128 Ops[1] = getValue(I.getOperand(1));
4129 Ops[2] = getValue(I.getOperand(2));
4130 Ops[3] = getValue(I.getOperand(3));
4131 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4135 case Intrinsic::memory_barrier: {
4138 for (int x = 1; x < 6; ++x)
4139 Ops[x] = getValue(I.getOperand(x));
4141 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4144 case Intrinsic::atomic_cmp_swap: {
4145 SDValue Root = getRoot();
4147 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4148 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4150 getValue(I.getOperand(1)),
4151 getValue(I.getOperand(2)),
4152 getValue(I.getOperand(3)),
4155 DAG.setRoot(L.getValue(1));
4158 case Intrinsic::atomic_load_add:
4159 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4160 case Intrinsic::atomic_load_sub:
4161 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4162 case Intrinsic::atomic_load_or:
4163 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4164 case Intrinsic::atomic_load_xor:
4165 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4166 case Intrinsic::atomic_load_and:
4167 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4168 case Intrinsic::atomic_load_nand:
4169 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4170 case Intrinsic::atomic_load_max:
4171 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4172 case Intrinsic::atomic_load_min:
4173 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4174 case Intrinsic::atomic_load_umin:
4175 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4176 case Intrinsic::atomic_load_umax:
4177 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4178 case Intrinsic::atomic_swap:
4179 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4181 case Intrinsic::invariant_start:
4182 case Intrinsic::lifetime_start:
4183 // Discard region information.
4184 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4186 case Intrinsic::invariant_end:
4187 case Intrinsic::lifetime_end:
4188 // Discard region information.
4193 /// Test if the given instruction is in a position to be optimized
4194 /// with a tail-call. This roughly means that it's in a block with
4195 /// a return and there's nothing that needs to be scheduled
4196 /// between it and the return.
4198 /// This function only tests target-independent requirements.
4200 isInTailCallPosition(ImmutableCallSite CS, Attributes CalleeRetAttr,
4201 const TargetLowering &TLI) {
4202 const Instruction *I = CS.getInstruction();
4203 const BasicBlock *ExitBB = I->getParent();
4204 const TerminatorInst *Term = ExitBB->getTerminator();
4205 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4206 const Function *F = ExitBB->getParent();
4208 // The block must end in a return statement or unreachable.
4210 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4211 // an unreachable, for now. The way tailcall optimization is currently
4212 // implemented means it will add an epilogue followed by a jump. That is
4213 // not profitable. Also, if the callee is a special function (e.g.
4214 // longjmp on x86), it can end up causing miscompilation that has not
4215 // been fully understood.
4217 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
4219 // If I will have a chain, make sure no other instruction that will have a
4220 // chain interposes between I and the return.
4221 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4222 !I->isSafeToSpeculativelyExecute())
4223 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4227 // Debug info intrinsics do not get in the way of tail call optimization.
4228 if (isa<DbgInfoIntrinsic>(BBI))
4230 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4231 !BBI->isSafeToSpeculativelyExecute())
4235 // If the block ends with a void return or unreachable, it doesn't matter
4236 // what the call's return type is.
4237 if (!Ret || Ret->getNumOperands() == 0) return true;
4239 // If the return value is undef, it doesn't matter what the call's
4241 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4243 // Conservatively require the attributes of the call to match those of
4244 // the return. Ignore noalias because it doesn't affect the call sequence.
4245 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4246 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4249 // It's not safe to eliminate the sign / zero extension of the return value.
4250 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4253 // Otherwise, make sure the unmodified return value of I is the return value.
4254 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4255 U = dyn_cast<Instruction>(U->getOperand(0))) {
4258 if (!U->hasOneUse())
4262 // Check for a truly no-op truncate.
4263 if (isa<TruncInst>(U) &&
4264 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4266 // Check for a truly no-op bitcast.
4267 if (isa<BitCastInst>(U) &&
4268 (U->getOperand(0)->getType() == U->getType() ||
4269 (U->getOperand(0)->getType()->isPointerTy() &&
4270 U->getType()->isPointerTy())))
4272 // Otherwise it's not a true no-op.
4279 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4281 MachineBasicBlock *LandingPad) {
4282 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4283 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4284 const Type *RetTy = FTy->getReturnType();
4285 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4286 MCSymbol *BeginLabel = 0;
4288 TargetLowering::ArgListTy Args;
4289 TargetLowering::ArgListEntry Entry;
4290 Args.reserve(CS.arg_size());
4292 // Check whether the function can return without sret-demotion.
4293 SmallVector<EVT, 4> OutVTs;
4294 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4295 SmallVector<uint64_t, 4> Offsets;
4296 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4297 OutVTs, OutsFlags, TLI, &Offsets);
4299 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4300 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4302 SDValue DemoteStackSlot;
4304 if (!CanLowerReturn) {
4305 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4306 FTy->getReturnType());
4307 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4308 FTy->getReturnType());
4309 MachineFunction &MF = DAG.getMachineFunction();
4310 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4311 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4313 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4314 Entry.Node = DemoteStackSlot;
4315 Entry.Ty = StackSlotPtrType;
4316 Entry.isSExt = false;
4317 Entry.isZExt = false;
4318 Entry.isInReg = false;
4319 Entry.isSRet = true;
4320 Entry.isNest = false;
4321 Entry.isByVal = false;
4322 Entry.Alignment = Align;
4323 Args.push_back(Entry);
4324 RetTy = Type::getVoidTy(FTy->getContext());
4327 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4329 SDValue ArgNode = getValue(*i);
4330 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4332 unsigned attrInd = i - CS.arg_begin() + 1;
4333 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4334 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4335 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4336 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4337 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4338 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4339 Entry.Alignment = CS.getParamAlignment(attrInd);
4340 Args.push_back(Entry);
4344 // Insert a label before the invoke call to mark the try range. This can be
4345 // used to detect deletion of the invoke via the MachineModuleInfo.
4346 BeginLabel = MMI.getContext().CreateTempSymbol();
4348 // For SjLj, keep track of which landing pads go with which invokes
4349 // so as to maintain the ordering of pads in the LSDA.
4350 unsigned CallSiteIndex = MMI.getCurrentCallSite();
4351 if (CallSiteIndex) {
4352 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4353 // Now that the call site is handled, stop tracking it.
4354 MMI.setCurrentCallSite(0);
4357 // Both PendingLoads and PendingExports must be flushed here;
4358 // this call might not return.
4360 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4363 // Check if target-independent constraints permit a tail call here.
4364 // Target-dependent constraints are checked within TLI.LowerCallTo.
4366 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4369 std::pair<SDValue,SDValue> Result =
4370 TLI.LowerCallTo(getRoot(), RetTy,
4371 CS.paramHasAttr(0, Attribute::SExt),
4372 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4373 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4374 CS.getCallingConv(),
4376 !CS.getInstruction()->use_empty(),
4377 Callee, Args, DAG, getCurDebugLoc());
4378 assert((isTailCall || Result.second.getNode()) &&
4379 "Non-null chain expected with non-tail call!");
4380 assert((Result.second.getNode() || !Result.first.getNode()) &&
4381 "Null value expected with tail call!");
4382 if (Result.first.getNode()) {
4383 setValue(CS.getInstruction(), Result.first);
4384 } else if (!CanLowerReturn && Result.second.getNode()) {
4385 // The instruction result is the result of loading from the
4386 // hidden sret parameter.
4387 SmallVector<EVT, 1> PVTs;
4388 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4390 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4391 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4392 EVT PtrVT = PVTs[0];
4393 unsigned NumValues = OutVTs.size();
4394 SmallVector<SDValue, 4> Values(NumValues);
4395 SmallVector<SDValue, 4> Chains(NumValues);
4397 for (unsigned i = 0; i < NumValues; ++i) {
4398 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4400 DAG.getConstant(Offsets[i], PtrVT));
4401 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4402 Add, NULL, Offsets[i], false, false, 1);
4404 Chains[i] = L.getValue(1);
4407 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4408 MVT::Other, &Chains[0], NumValues);
4409 PendingLoads.push_back(Chain);
4411 // Collect the legal value parts into potentially illegal values
4412 // that correspond to the original function's return values.
4413 SmallVector<EVT, 4> RetTys;
4414 RetTy = FTy->getReturnType();
4415 ComputeValueVTs(TLI, RetTy, RetTys);
4416 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4417 SmallVector<SDValue, 4> ReturnValues;
4418 unsigned CurReg = 0;
4419 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4421 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4422 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4424 SDValue ReturnValue =
4425 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
4426 RegisterVT, VT, AssertOp);
4427 ReturnValues.push_back(ReturnValue);
4431 setValue(CS.getInstruction(),
4432 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4433 DAG.getVTList(&RetTys[0], RetTys.size()),
4434 &ReturnValues[0], ReturnValues.size()));
4438 // As a special case, a null chain means that a tail call has been emitted and
4439 // the DAG root is already updated.
4440 if (Result.second.getNode())
4441 DAG.setRoot(Result.second);
4446 // Insert a label at the end of the invoke call to mark the try range. This
4447 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4448 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
4449 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
4451 // Inform MachineModuleInfo of range.
4452 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
4456 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4457 /// value is equal or not-equal to zero.
4458 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
4459 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
4461 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4462 if (IC->isEquality())
4463 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4464 if (C->isNullValue())
4466 // Unknown instruction.
4472 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
4474 SelectionDAGBuilder &Builder) {
4476 // Check to see if this load can be trivially constant folded, e.g. if the
4477 // input is from a string literal.
4478 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4479 // Cast pointer to the type we really want to load.
4480 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
4481 PointerType::getUnqual(LoadTy));
4483 if (const Constant *LoadCst =
4484 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
4486 return Builder.getValue(LoadCst);
4489 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4490 // still constant memory, the input chain can be the entry node.
4492 bool ConstantMemory = false;
4494 // Do not serialize (non-volatile) loads of constant memory with anything.
4495 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4496 Root = Builder.DAG.getEntryNode();
4497 ConstantMemory = true;
4499 // Do not serialize non-volatile loads against each other.
4500 Root = Builder.DAG.getRoot();
4503 SDValue Ptr = Builder.getValue(PtrVal);
4504 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4505 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4507 false /*nontemporal*/, 1 /* align=1 */);
4509 if (!ConstantMemory)
4510 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4515 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4516 /// If so, return true and lower it, otherwise return false and it will be
4517 /// lowered like a normal call.
4518 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
4519 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4520 if (I.getNumOperands() != 4)
4523 const Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
4524 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
4525 !I.getOperand(3)->getType()->isIntegerTy() ||
4526 !I.getType()->isIntegerTy())
4529 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
4531 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4532 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
4533 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4534 bool ActuallyDoIt = true;
4537 switch (Size->getZExtValue()) {
4539 LoadVT = MVT::Other;
4541 ActuallyDoIt = false;
4545 LoadTy = Type::getInt16Ty(Size->getContext());
4549 LoadTy = Type::getInt32Ty(Size->getContext());
4553 LoadTy = Type::getInt64Ty(Size->getContext());
4557 LoadVT = MVT::v4i32;
4558 LoadTy = Type::getInt32Ty(Size->getContext());
4559 LoadTy = VectorType::get(LoadTy, 4);
4564 // This turns into unaligned loads. We only do this if the target natively
4565 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4566 // we'll only produce a small number of byte loads.
4568 // Require that we can find a legal MVT, and only do this if the target
4569 // supports unaligned loads of that type. Expanding into byte loads would
4571 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4572 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4573 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4574 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4575 ActuallyDoIt = false;
4579 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4580 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
4582 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4584 EVT CallVT = TLI.getValueType(I.getType(), true);
4585 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4595 void SelectionDAGBuilder::visitCall(const CallInst &I) {
4596 const char *RenameFn = 0;
4597 if (Function *F = I.getCalledFunction()) {
4598 if (F->isDeclaration()) {
4599 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4601 if (unsigned IID = II->getIntrinsicID(F)) {
4602 RenameFn = visitIntrinsicCall(I, IID);
4607 if (unsigned IID = F->getIntrinsicID()) {
4608 RenameFn = visitIntrinsicCall(I, IID);
4614 // Check for well-known libc/libm calls. If the function is internal, it
4615 // can't be a library call.
4616 if (!F->hasLocalLinkage() && F->hasName()) {
4617 StringRef Name = F->getName();
4618 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
4619 if (I.getNumOperands() == 3 && // Basic sanity checks.
4620 I.getOperand(1)->getType()->isFloatingPointTy() &&
4621 I.getType() == I.getOperand(1)->getType() &&
4622 I.getType() == I.getOperand(2)->getType()) {
4623 SDValue LHS = getValue(I.getOperand(1));
4624 SDValue RHS = getValue(I.getOperand(2));
4625 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4626 LHS.getValueType(), LHS, RHS));
4629 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4630 if (I.getNumOperands() == 2 && // Basic sanity checks.
4631 I.getOperand(1)->getType()->isFloatingPointTy() &&
4632 I.getType() == I.getOperand(1)->getType()) {
4633 SDValue Tmp = getValue(I.getOperand(1));
4634 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4635 Tmp.getValueType(), Tmp));
4638 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4639 if (I.getNumOperands() == 2 && // Basic sanity checks.
4640 I.getOperand(1)->getType()->isFloatingPointTy() &&
4641 I.getType() == I.getOperand(1)->getType() &&
4642 I.onlyReadsMemory()) {
4643 SDValue Tmp = getValue(I.getOperand(1));
4644 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4645 Tmp.getValueType(), Tmp));
4648 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4649 if (I.getNumOperands() == 2 && // Basic sanity checks.
4650 I.getOperand(1)->getType()->isFloatingPointTy() &&
4651 I.getType() == I.getOperand(1)->getType() &&
4652 I.onlyReadsMemory()) {
4653 SDValue Tmp = getValue(I.getOperand(1));
4654 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4655 Tmp.getValueType(), Tmp));
4658 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4659 if (I.getNumOperands() == 2 && // Basic sanity checks.
4660 I.getOperand(1)->getType()->isFloatingPointTy() &&
4661 I.getType() == I.getOperand(1)->getType() &&
4662 I.onlyReadsMemory()) {
4663 SDValue Tmp = getValue(I.getOperand(1));
4664 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4665 Tmp.getValueType(), Tmp));
4668 } else if (Name == "memcmp") {
4669 if (visitMemCmpCall(I))
4673 } else if (isa<InlineAsm>(I.getOperand(0))) {
4680 Callee = getValue(I.getOperand(0));
4682 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4684 // Check if we can potentially perform a tail call. More detailed checking is
4685 // be done within LowerCallTo, after more information about the call is known.
4686 LowerCallTo(&I, Callee, I.isTailCall());
4689 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4690 /// this value and returns the result as a ValueVT value. This uses
4691 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4692 /// If the Flag pointer is NULL, no flag is used.
4693 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4694 SDValue &Chain, SDValue *Flag) const {
4695 // Assemble the legal parts into the final values.
4696 SmallVector<SDValue, 4> Values(ValueVTs.size());
4697 SmallVector<SDValue, 8> Parts;
4698 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4699 // Copy the legal parts from the registers.
4700 EVT ValueVT = ValueVTs[Value];
4701 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4702 EVT RegisterVT = RegVTs[Value];
4704 Parts.resize(NumRegs);
4705 for (unsigned i = 0; i != NumRegs; ++i) {
4708 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4710 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4711 *Flag = P.getValue(2);
4714 Chain = P.getValue(1);
4716 // If the source register was virtual and if we know something about it,
4717 // add an assert node.
4718 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4719 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4720 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4721 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4722 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4723 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4725 unsigned RegSize = RegisterVT.getSizeInBits();
4726 unsigned NumSignBits = LOI.NumSignBits;
4727 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4729 // FIXME: We capture more information than the dag can represent. For
4730 // now, just use the tightest assertzext/assertsext possible.
4732 EVT FromVT(MVT::Other);
4733 if (NumSignBits == RegSize)
4734 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4735 else if (NumZeroBits >= RegSize-1)
4736 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4737 else if (NumSignBits > RegSize-8)
4738 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4739 else if (NumZeroBits >= RegSize-8)
4740 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4741 else if (NumSignBits > RegSize-16)
4742 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4743 else if (NumZeroBits >= RegSize-16)
4744 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4745 else if (NumSignBits > RegSize-32)
4746 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4747 else if (NumZeroBits >= RegSize-32)
4748 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4750 if (FromVT != MVT::Other)
4751 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4752 RegisterVT, P, DAG.getValueType(FromVT));
4759 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4760 NumRegs, RegisterVT, ValueVT);
4765 return DAG.getNode(ISD::MERGE_VALUES, dl,
4766 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4767 &Values[0], ValueVTs.size());
4770 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4771 /// specified value into the registers specified by this object. This uses
4772 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4773 /// If the Flag pointer is NULL, no flag is used.
4774 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4775 SDValue &Chain, SDValue *Flag) const {
4776 // Get the list of the values's legal parts.
4777 unsigned NumRegs = Regs.size();
4778 SmallVector<SDValue, 8> Parts(NumRegs);
4779 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4780 EVT ValueVT = ValueVTs[Value];
4781 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4782 EVT RegisterVT = RegVTs[Value];
4784 getCopyToParts(DAG, dl,
4785 Val.getValue(Val.getResNo() + Value),
4786 &Parts[Part], NumParts, RegisterVT);
4790 // Copy the parts into the registers.
4791 SmallVector<SDValue, 8> Chains(NumRegs);
4792 for (unsigned i = 0; i != NumRegs; ++i) {
4795 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4797 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4798 *Flag = Part.getValue(1);
4801 Chains[i] = Part.getValue(0);
4804 if (NumRegs == 1 || Flag)
4805 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4806 // flagged to it. That is the CopyToReg nodes and the user are considered
4807 // a single scheduling unit. If we create a TokenFactor and return it as
4808 // chain, then the TokenFactor is both a predecessor (operand) of the
4809 // user as well as a successor (the TF operands are flagged to the user).
4810 // c1, f1 = CopyToReg
4811 // c2, f2 = CopyToReg
4812 // c3 = TokenFactor c1, c2
4815 Chain = Chains[NumRegs-1];
4817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4820 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4821 /// operand list. This adds the code marker and includes the number of
4822 /// values added into it.
4823 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
4824 unsigned MatchingIdx,
4826 std::vector<SDValue> &Ops) const {
4827 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
4829 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
4830 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
4833 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4834 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4835 EVT RegisterVT = RegVTs[Value];
4836 for (unsigned i = 0; i != NumRegs; ++i) {
4837 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4838 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4843 /// isAllocatableRegister - If the specified register is safe to allocate,
4844 /// i.e. it isn't a stack pointer or some other special register, return the
4845 /// register class for the register. Otherwise, return null.
4846 static const TargetRegisterClass *
4847 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4848 const TargetLowering &TLI,
4849 const TargetRegisterInfo *TRI) {
4850 EVT FoundVT = MVT::Other;
4851 const TargetRegisterClass *FoundRC = 0;
4852 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4853 E = TRI->regclass_end(); RCI != E; ++RCI) {
4854 EVT ThisVT = MVT::Other;
4856 const TargetRegisterClass *RC = *RCI;
4857 // If none of the value types for this register class are valid, we
4858 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4859 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4861 if (TLI.isTypeLegal(*I)) {
4862 // If we have already found this register in a different register class,
4863 // choose the one with the largest VT specified. For example, on
4864 // PowerPC, we favor f64 register classes over f32.
4865 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4872 if (ThisVT == MVT::Other) continue;
4874 // NOTE: This isn't ideal. In particular, this might allocate the
4875 // frame pointer in functions that need it (due to them not being taken
4876 // out of allocation, because a variable sized allocation hasn't been seen
4877 // yet). This is a slight code pessimization, but should still work.
4878 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4879 E = RC->allocation_order_end(MF); I != E; ++I)
4881 // We found a matching register class. Keep looking at others in case
4882 // we find one with larger registers that this physreg is also in.
4893 /// AsmOperandInfo - This contains information for each constraint that we are
4895 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4896 public TargetLowering::AsmOperandInfo {
4898 /// CallOperand - If this is the result output operand or a clobber
4899 /// this is null, otherwise it is the incoming operand to the CallInst.
4900 /// This gets modified as the asm is processed.
4901 SDValue CallOperand;
4903 /// AssignedRegs - If this is a register or register class operand, this
4904 /// contains the set of register corresponding to the operand.
4905 RegsForValue AssignedRegs;
4907 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4908 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4911 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4912 /// busy in OutputRegs/InputRegs.
4913 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4914 std::set<unsigned> &OutputRegs,
4915 std::set<unsigned> &InputRegs,
4916 const TargetRegisterInfo &TRI) const {
4918 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4919 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4922 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4923 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4927 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4928 /// corresponds to. If there is no Value* for this operand, it returns
4930 EVT getCallOperandValEVT(LLVMContext &Context,
4931 const TargetLowering &TLI,
4932 const TargetData *TD) const {
4933 if (CallOperandVal == 0) return MVT::Other;
4935 if (isa<BasicBlock>(CallOperandVal))
4936 return TLI.getPointerTy();
4938 const llvm::Type *OpTy = CallOperandVal->getType();
4940 // If this is an indirect operand, the operand is a pointer to the
4943 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4945 report_fatal_error("Indirect operand for inline asm not a pointer!");
4946 OpTy = PtrTy->getElementType();
4949 // If OpTy is not a single value, it may be a struct/union that we
4950 // can tile with integers.
4951 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4952 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4961 OpTy = IntegerType::get(Context, BitSize);
4966 return TLI.getValueType(OpTy, true);
4970 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4972 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4973 const TargetRegisterInfo &TRI) {
4974 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4976 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4977 for (; *Aliases; ++Aliases)
4978 Regs.insert(*Aliases);
4981 } // end llvm namespace.
4984 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4985 /// specified operand. We prefer to assign virtual registers, to allow the
4986 /// register allocator to handle the assignment process. However, if the asm
4987 /// uses features that we can't model on machineinstrs, we have SDISel do the
4988 /// allocation. This produces generally horrible, but correct, code.
4990 /// OpInfo describes the operand.
4991 /// Input and OutputRegs are the set of already allocated physical registers.
4993 void SelectionDAGBuilder::
4994 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4995 std::set<unsigned> &OutputRegs,
4996 std::set<unsigned> &InputRegs) {
4997 LLVMContext &Context = FuncInfo.Fn->getContext();
4999 // Compute whether this value requires an input register, an output register,
5001 bool isOutReg = false;
5002 bool isInReg = false;
5003 switch (OpInfo.Type) {
5004 case InlineAsm::isOutput:
5007 // If there is an input constraint that matches this, we need to reserve
5008 // the input register so no other inputs allocate to it.
5009 isInReg = OpInfo.hasMatchingInput();
5011 case InlineAsm::isInput:
5015 case InlineAsm::isClobber:
5022 MachineFunction &MF = DAG.getMachineFunction();
5023 SmallVector<unsigned, 4> Regs;
5025 // If this is a constraint for a single physreg, or a constraint for a
5026 // register class, find it.
5027 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5028 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5029 OpInfo.ConstraintVT);
5031 unsigned NumRegs = 1;
5032 if (OpInfo.ConstraintVT != MVT::Other) {
5033 // If this is a FP input in an integer register (or visa versa) insert a bit
5034 // cast of the input value. More generally, handle any case where the input
5035 // value disagrees with the register class we plan to stick this in.
5036 if (OpInfo.Type == InlineAsm::isInput &&
5037 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5038 // Try to convert to the first EVT that the reg class contains. If the
5039 // types are identical size, use a bitcast to convert (e.g. two differing
5041 EVT RegVT = *PhysReg.second->vt_begin();
5042 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5043 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5044 RegVT, OpInfo.CallOperand);
5045 OpInfo.ConstraintVT = RegVT;
5046 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5047 // If the input is a FP value and we want it in FP registers, do a
5048 // bitcast to the corresponding integer type. This turns an f64 value
5049 // into i64, which can be passed with two i32 values on a 32-bit
5051 RegVT = EVT::getIntegerVT(Context,
5052 OpInfo.ConstraintVT.getSizeInBits());
5053 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5054 RegVT, OpInfo.CallOperand);
5055 OpInfo.ConstraintVT = RegVT;
5059 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5063 EVT ValueVT = OpInfo.ConstraintVT;
5065 // If this is a constraint for a specific physical register, like {r17},
5067 if (unsigned AssignedReg = PhysReg.first) {
5068 const TargetRegisterClass *RC = PhysReg.second;
5069 if (OpInfo.ConstraintVT == MVT::Other)
5070 ValueVT = *RC->vt_begin();
5072 // Get the actual register value type. This is important, because the user
5073 // may have asked for (e.g.) the AX register in i32 type. We need to
5074 // remember that AX is actually i16 to get the right extension.
5075 RegVT = *RC->vt_begin();
5077 // This is a explicit reference to a physical register.
5078 Regs.push_back(AssignedReg);
5080 // If this is an expanded reference, add the rest of the regs to Regs.
5082 TargetRegisterClass::iterator I = RC->begin();
5083 for (; *I != AssignedReg; ++I)
5084 assert(I != RC->end() && "Didn't find reg!");
5086 // Already added the first reg.
5088 for (; NumRegs; --NumRegs, ++I) {
5089 assert(I != RC->end() && "Ran out of registers to allocate!");
5094 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5095 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5096 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5100 // Otherwise, if this was a reference to an LLVM register class, create vregs
5101 // for this reference.
5102 if (const TargetRegisterClass *RC = PhysReg.second) {
5103 RegVT = *RC->vt_begin();
5104 if (OpInfo.ConstraintVT == MVT::Other)
5107 // Create the appropriate number of virtual registers.
5108 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5109 for (; NumRegs; --NumRegs)
5110 Regs.push_back(RegInfo.createVirtualRegister(RC));
5112 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5116 // This is a reference to a register class that doesn't directly correspond
5117 // to an LLVM register class. Allocate NumRegs consecutive, available,
5118 // registers from the class.
5119 std::vector<unsigned> RegClassRegs
5120 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5121 OpInfo.ConstraintVT);
5123 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5124 unsigned NumAllocated = 0;
5125 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5126 unsigned Reg = RegClassRegs[i];
5127 // See if this register is available.
5128 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5129 (isInReg && InputRegs.count(Reg))) { // Already used.
5130 // Make sure we find consecutive registers.
5135 // Check to see if this register is allocatable (i.e. don't give out the
5137 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5138 if (!RC) { // Couldn't allocate this register.
5139 // Reset NumAllocated to make sure we return consecutive registers.
5144 // Okay, this register is good, we can use it.
5147 // If we allocated enough consecutive registers, succeed.
5148 if (NumAllocated == NumRegs) {
5149 unsigned RegStart = (i-NumAllocated)+1;
5150 unsigned RegEnd = i+1;
5151 // Mark all of the allocated registers used.
5152 for (unsigned i = RegStart; i != RegEnd; ++i)
5153 Regs.push_back(RegClassRegs[i]);
5155 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5156 OpInfo.ConstraintVT);
5157 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5162 // Otherwise, we couldn't allocate enough registers for this.
5165 /// visitInlineAsm - Handle a call to an InlineAsm object.
5167 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5168 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5170 /// ConstraintOperands - Information about all of the constraints.
5171 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5173 std::set<unsigned> OutputRegs, InputRegs;
5175 // Do a prepass over the constraints, canonicalizing them, and building up the
5176 // ConstraintOperands list.
5177 std::vector<InlineAsm::ConstraintInfo>
5178 ConstraintInfos = IA->ParseConstraints();
5180 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5182 SDValue Chain, Flag;
5184 // We won't need to flush pending loads if this asm doesn't touch
5185 // memory and is nonvolatile.
5186 if (hasMemory || IA->hasSideEffects())
5189 Chain = DAG.getRoot();
5191 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5192 unsigned ResNo = 0; // ResNo - The result number of the next output.
5193 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5194 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5195 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5197 EVT OpVT = MVT::Other;
5199 // Compute the value type for each operand.
5200 switch (OpInfo.Type) {
5201 case InlineAsm::isOutput:
5202 // Indirect outputs just consume an argument.
5203 if (OpInfo.isIndirect) {
5204 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5208 // The return value of the call is this value. As such, there is no
5209 // corresponding argument.
5210 assert(!CS.getType()->isVoidTy() &&
5212 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5213 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5215 assert(ResNo == 0 && "Asm only has one result!");
5216 OpVT = TLI.getValueType(CS.getType());
5220 case InlineAsm::isInput:
5221 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5223 case InlineAsm::isClobber:
5228 // If this is an input or an indirect output, process the call argument.
5229 // BasicBlocks are labels, currently appearing only in asm's.
5230 if (OpInfo.CallOperandVal) {
5231 // Strip bitcasts, if any. This mostly comes up for functions.
5232 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5234 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5235 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5237 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5240 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5243 OpInfo.ConstraintVT = OpVT;
5246 // Second pass over the constraints: compute which constraint option to use
5247 // and assign registers to constraints that want a specific physreg.
5248 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5249 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5251 // If this is an output operand with a matching input operand, look up the
5252 // matching input. If their types mismatch, e.g. one is an integer, the
5253 // other is floating point, or their sizes are different, flag it as an
5255 if (OpInfo.hasMatchingInput()) {
5256 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5258 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5259 if ((OpInfo.ConstraintVT.isInteger() !=
5260 Input.ConstraintVT.isInteger()) ||
5261 (OpInfo.ConstraintVT.getSizeInBits() !=
5262 Input.ConstraintVT.getSizeInBits())) {
5263 report_fatal_error("Unsupported asm: input constraint"
5264 " with a matching output constraint of"
5265 " incompatible type!");
5267 Input.ConstraintVT = OpInfo.ConstraintVT;
5271 // Compute the constraint code and ConstraintType to use.
5272 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5274 // If this is a memory input, and if the operand is not indirect, do what we
5275 // need to to provide an address for the memory input.
5276 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5277 !OpInfo.isIndirect) {
5278 assert(OpInfo.Type == InlineAsm::isInput &&
5279 "Can only indirectify direct input operands!");
5281 // Memory operands really want the address of the value. If we don't have
5282 // an indirect input, put it in the constpool if we can, otherwise spill
5283 // it to a stack slot.
5285 // If the operand is a float, integer, or vector constant, spill to a
5286 // constant pool entry to get its address.
5287 const Value *OpVal = OpInfo.CallOperandVal;
5288 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5289 isa<ConstantVector>(OpVal)) {
5290 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5291 TLI.getPointerTy());
5293 // Otherwise, create a stack slot and emit a store to it before the
5295 const Type *Ty = OpVal->getType();
5296 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5297 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5298 MachineFunction &MF = DAG.getMachineFunction();
5299 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5300 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5301 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5302 OpInfo.CallOperand, StackSlot, NULL, 0,
5304 OpInfo.CallOperand = StackSlot;
5307 // There is no longer a Value* corresponding to this operand.
5308 OpInfo.CallOperandVal = 0;
5310 // It is now an indirect operand.
5311 OpInfo.isIndirect = true;
5314 // If this constraint is for a specific register, allocate it before
5316 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5317 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5320 ConstraintInfos.clear();
5322 // Second pass - Loop over all of the operands, assigning virtual or physregs
5323 // to register class operands.
5324 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5325 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5327 // C_Register operands have already been allocated, Other/Memory don't need
5329 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5330 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5333 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5334 std::vector<SDValue> AsmNodeOperands;
5335 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5336 AsmNodeOperands.push_back(
5337 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5338 TLI.getPointerTy()));
5340 // If we have a !srcloc metadata node associated with it, we want to attach
5341 // this to the ultimately generated inline asm machineinstr. To do this, we
5342 // pass in the third operand as this (potentially null) inline asm MDNode.
5343 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5344 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5346 // Loop over all of the inputs, copying the operand values into the
5347 // appropriate registers and processing the output regs.
5348 RegsForValue RetValRegs;
5350 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5351 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5353 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5354 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5356 switch (OpInfo.Type) {
5357 case InlineAsm::isOutput: {
5358 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5359 OpInfo.ConstraintType != TargetLowering::C_Register) {
5360 // Memory output, or 'other' output (e.g. 'X' constraint).
5361 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5363 // Add information to the INLINEASM node to know about this output.
5364 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5365 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5366 TLI.getPointerTy()));
5367 AsmNodeOperands.push_back(OpInfo.CallOperand);
5371 // Otherwise, this is a register or register class output.
5373 // Copy the output from the appropriate register. Find a register that
5375 if (OpInfo.AssignedRegs.Regs.empty())
5376 report_fatal_error("Couldn't allocate output reg for constraint '" +
5377 Twine(OpInfo.ConstraintCode) + "'!");
5379 // If this is an indirect operand, store through the pointer after the
5381 if (OpInfo.isIndirect) {
5382 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5383 OpInfo.CallOperandVal));
5385 // This is the result value of the call.
5386 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5387 // Concatenate this output onto the outputs list.
5388 RetValRegs.append(OpInfo.AssignedRegs);
5391 // Add information to the INLINEASM node to know that this register is
5393 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5394 InlineAsm::Kind_RegDefEarlyClobber :
5395 InlineAsm::Kind_RegDef,
5402 case InlineAsm::isInput: {
5403 SDValue InOperandVal = OpInfo.CallOperand;
5405 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5406 // If this is required to match an output register we have already set,
5407 // just use its register.
5408 unsigned OperandNo = OpInfo.getMatchedOperand();
5410 // Scan until we find the definition we already emitted of this operand.
5411 // When we find it, create a RegsForValue operand.
5412 unsigned CurOp = InlineAsm::Op_FirstOperand;
5413 for (; OperandNo; --OperandNo) {
5414 // Advance to the next operand.
5416 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5417 assert((InlineAsm::isRegDefKind(OpFlag) ||
5418 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5419 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5420 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5424 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5425 if (InlineAsm::isRegDefKind(OpFlag) ||
5426 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5427 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5428 if (OpInfo.isIndirect) {
5429 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5430 LLVMContext &Ctx = CurMBB->getParent()->getFunction()->getContext();
5431 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5432 " don't know how to handle tied "
5433 "indirect register inputs");
5436 RegsForValue MatchedRegs;
5437 MatchedRegs.TLI = &TLI;
5438 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5439 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5440 MatchedRegs.RegVTs.push_back(RegVT);
5441 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5442 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5444 MatchedRegs.Regs.push_back
5445 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5447 // Use the produced MatchedRegs object to
5448 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5450 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5451 true, OpInfo.getMatchedOperand(),
5452 DAG, AsmNodeOperands);
5456 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5457 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5458 "Unexpected number of operands");
5459 // Add information to the INLINEASM node to know about this input.
5460 // See InlineAsm.h isUseOperandTiedToDef.
5461 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5462 OpInfo.getMatchedOperand());
5463 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5464 TLI.getPointerTy()));
5465 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5469 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5470 assert(!OpInfo.isIndirect &&
5471 "Don't know how to handle indirect other inputs yet!");
5473 std::vector<SDValue> Ops;
5474 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5475 hasMemory, Ops, DAG);
5477 report_fatal_error("Invalid operand for inline asm constraint '" +
5478 Twine(OpInfo.ConstraintCode) + "'!");
5480 // Add information to the INLINEASM node to know about this input.
5481 unsigned ResOpType =
5482 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5483 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5484 TLI.getPointerTy()));
5485 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5489 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5490 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5491 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5492 "Memory operands expect pointer values");
5494 // Add information to the INLINEASM node to know about this input.
5495 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5496 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5497 TLI.getPointerTy()));
5498 AsmNodeOperands.push_back(InOperandVal);
5502 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5503 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5504 "Unknown constraint type!");
5505 assert(!OpInfo.isIndirect &&
5506 "Don't know how to handle indirect register inputs yet!");
5508 // Copy the input into the appropriate registers.
5509 if (OpInfo.AssignedRegs.Regs.empty() ||
5510 !OpInfo.AssignedRegs.areValueTypesLegal())
5511 report_fatal_error("Couldn't allocate input reg for constraint '" +
5512 Twine(OpInfo.ConstraintCode) + "'!");
5514 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5517 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
5518 DAG, AsmNodeOperands);
5521 case InlineAsm::isClobber: {
5522 // Add the clobbered value to the operand list, so that the register
5523 // allocator is aware that the physreg got clobbered.
5524 if (!OpInfo.AssignedRegs.Regs.empty())
5525 OpInfo.AssignedRegs.AddInlineAsmOperands(
5526 InlineAsm::Kind_RegDefEarlyClobber,
5534 // Finish up input operands. Set the input chain and add the flag last.
5535 AsmNodeOperands[0] = Chain;
5536 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5538 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5539 DAG.getVTList(MVT::Other, MVT::Flag),
5540 &AsmNodeOperands[0], AsmNodeOperands.size());
5541 Flag = Chain.getValue(1);
5543 // If this asm returns a register value, copy the result from that register
5544 // and set it as the value of the call.
5545 if (!RetValRegs.Regs.empty()) {
5546 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5549 // FIXME: Why don't we do this for inline asms with MRVs?
5550 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5551 EVT ResultType = TLI.getValueType(CS.getType());
5553 // If any of the results of the inline asm is a vector, it may have the
5554 // wrong width/num elts. This can happen for register classes that can
5555 // contain multiple different value types. The preg or vreg allocated may
5556 // not have the same VT as was expected. Convert it to the right type
5557 // with bit_convert.
5558 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5559 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5562 } else if (ResultType != Val.getValueType() &&
5563 ResultType.isInteger() && Val.getValueType().isInteger()) {
5564 // If a result value was tied to an input value, the computed result may
5565 // have a wider width than the expected result. Extract the relevant
5567 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5570 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5573 setValue(CS.getInstruction(), Val);
5574 // Don't need to use this as a chain in this case.
5575 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5579 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
5581 // Process indirect outputs, first output all of the flagged copies out of
5583 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5584 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5585 const Value *Ptr = IndirectStoresToEmit[i].second;
5586 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5588 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5591 // Emit the non-flagged stores from the physregs.
5592 SmallVector<SDValue, 8> OutChains;
5593 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5594 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5595 StoresToEmit[i].first,
5596 getValue(StoresToEmit[i].second),
5597 StoresToEmit[i].second, 0,
5599 OutChains.push_back(Val);
5602 if (!OutChains.empty())
5603 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5604 &OutChains[0], OutChains.size());
5609 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
5610 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5611 MVT::Other, getRoot(),
5612 getValue(I.getOperand(1)),
5613 DAG.getSrcValue(I.getOperand(1))));
5616 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
5617 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5618 getRoot(), getValue(I.getOperand(0)),
5619 DAG.getSrcValue(I.getOperand(0)));
5621 DAG.setRoot(V.getValue(1));
5624 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
5625 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5626 MVT::Other, getRoot(),
5627 getValue(I.getOperand(1)),
5628 DAG.getSrcValue(I.getOperand(1))));
5631 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
5632 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5633 MVT::Other, getRoot(),
5634 getValue(I.getOperand(1)),
5635 getValue(I.getOperand(2)),
5636 DAG.getSrcValue(I.getOperand(1)),
5637 DAG.getSrcValue(I.getOperand(2))));
5640 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5641 /// implementation, which just calls LowerCall.
5642 /// FIXME: When all targets are
5643 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5644 std::pair<SDValue, SDValue>
5645 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5646 bool RetSExt, bool RetZExt, bool isVarArg,
5647 bool isInreg, unsigned NumFixedArgs,
5648 CallingConv::ID CallConv, bool isTailCall,
5649 bool isReturnValueUsed,
5651 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5652 // Handle all of the outgoing arguments.
5653 SmallVector<ISD::OutputArg, 32> Outs;
5654 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5655 SmallVector<EVT, 4> ValueVTs;
5656 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5657 for (unsigned Value = 0, NumValues = ValueVTs.size();
5658 Value != NumValues; ++Value) {
5659 EVT VT = ValueVTs[Value];
5660 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5661 SDValue Op = SDValue(Args[i].Node.getNode(),
5662 Args[i].Node.getResNo() + Value);
5663 ISD::ArgFlagsTy Flags;
5664 unsigned OriginalAlignment =
5665 getTargetData()->getABITypeAlignment(ArgTy);
5671 if (Args[i].isInReg)
5675 if (Args[i].isByVal) {
5677 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5678 const Type *ElementTy = Ty->getElementType();
5679 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5680 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5681 // For ByVal, alignment should come from FE. BE will guess if this
5682 // info is not there but there are cases it cannot get right.
5683 if (Args[i].Alignment)
5684 FrameAlign = Args[i].Alignment;
5685 Flags.setByValAlign(FrameAlign);
5686 Flags.setByValSize(FrameSize);
5690 Flags.setOrigAlign(OriginalAlignment);
5692 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5693 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5694 SmallVector<SDValue, 4> Parts(NumParts);
5695 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5698 ExtendKind = ISD::SIGN_EXTEND;
5699 else if (Args[i].isZExt)
5700 ExtendKind = ISD::ZERO_EXTEND;
5702 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
5703 PartVT, ExtendKind);
5705 for (unsigned j = 0; j != NumParts; ++j) {
5706 // if it isn't first piece, alignment must be 1
5707 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5708 if (NumParts > 1 && j == 0)
5709 MyFlags.Flags.setSplit();
5711 MyFlags.Flags.setOrigAlign(1);
5713 Outs.push_back(MyFlags);
5718 // Handle the incoming return values from the call.
5719 SmallVector<ISD::InputArg, 32> Ins;
5720 SmallVector<EVT, 4> RetTys;
5721 ComputeValueVTs(*this, RetTy, RetTys);
5722 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5724 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5725 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5726 for (unsigned i = 0; i != NumRegs; ++i) {
5727 ISD::InputArg MyFlags;
5728 MyFlags.VT = RegisterVT;
5729 MyFlags.Used = isReturnValueUsed;
5731 MyFlags.Flags.setSExt();
5733 MyFlags.Flags.setZExt();
5735 MyFlags.Flags.setInReg();
5736 Ins.push_back(MyFlags);
5740 SmallVector<SDValue, 4> InVals;
5741 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5742 Outs, Ins, dl, DAG, InVals);
5744 // Verify that the target's LowerCall behaved as expected.
5745 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5746 "LowerCall didn't return a valid chain!");
5747 assert((!isTailCall || InVals.empty()) &&
5748 "LowerCall emitted a return value for a tail call!");
5749 assert((isTailCall || InVals.size() == Ins.size()) &&
5750 "LowerCall didn't emit the correct number of values!");
5752 // For a tail call, the return value is merely live-out and there aren't
5753 // any nodes in the DAG representing it. Return a special value to
5754 // indicate that a tail call has been emitted and no more Instructions
5755 // should be processed in the current block.
5758 return std::make_pair(SDValue(), SDValue());
5761 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5762 assert(InVals[i].getNode() &&
5763 "LowerCall emitted a null value!");
5764 assert(Ins[i].VT == InVals[i].getValueType() &&
5765 "LowerCall emitted a value with the wrong type!");
5768 // Collect the legal value parts into potentially illegal values
5769 // that correspond to the original function's return values.
5770 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5772 AssertOp = ISD::AssertSext;
5774 AssertOp = ISD::AssertZext;
5775 SmallVector<SDValue, 4> ReturnValues;
5776 unsigned CurReg = 0;
5777 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5779 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5780 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5782 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
5783 NumRegs, RegisterVT, VT,
5788 // For a function returning void, there is no return value. We can't create
5789 // such a node, so we just return a null return value in that case. In
5790 // that case, nothing will actualy look at the value.
5791 if (ReturnValues.empty())
5792 return std::make_pair(SDValue(), Chain);
5794 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5795 DAG.getVTList(&RetTys[0], RetTys.size()),
5796 &ReturnValues[0], ReturnValues.size());
5797 return std::make_pair(Res, Chain);
5800 void TargetLowering::LowerOperationWrapper(SDNode *N,
5801 SmallVectorImpl<SDValue> &Results,
5802 SelectionDAG &DAG) {
5803 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5805 Results.push_back(Res);
5808 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5809 llvm_unreachable("LowerOperation not implemented for this target!");
5814 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
5815 SDValue Op = getValue(V);
5816 assert((Op.getOpcode() != ISD::CopyFromReg ||
5817 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5818 "Copy from a reg to the same reg!");
5819 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5821 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5822 SDValue Chain = DAG.getEntryNode();
5823 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5824 PendingExports.push_back(Chain);
5827 #include "llvm/CodeGen/SelectionDAGISel.h"
5829 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
5830 // If this is the entry block, emit arguments.
5831 const Function &F = *LLVMBB->getParent();
5832 SelectionDAG &DAG = SDB->DAG;
5833 SDValue OldRoot = DAG.getRoot();
5834 DebugLoc dl = SDB->getCurDebugLoc();
5835 const TargetData *TD = TLI.getTargetData();
5836 SmallVector<ISD::InputArg, 16> Ins;
5838 // Check whether the function can return without sret-demotion.
5839 SmallVector<EVT, 4> OutVTs;
5840 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5841 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5842 OutVTs, OutsFlags, TLI);
5843 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5845 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5846 OutVTs, OutsFlags, DAG);
5847 if (!FLI.CanLowerReturn) {
5848 // Put in an sret pointer parameter before all the other parameters.
5849 SmallVector<EVT, 1> ValueVTs;
5850 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5852 // NOTE: Assuming that a pointer will never break down to more than one VT
5854 ISD::ArgFlagsTy Flags;
5856 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5857 ISD::InputArg RetArg(Flags, RegisterVT, true);
5858 Ins.push_back(RetArg);
5861 // Set up the incoming argument description vector.
5863 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
5864 I != E; ++I, ++Idx) {
5865 SmallVector<EVT, 4> ValueVTs;
5866 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5867 bool isArgValueUsed = !I->use_empty();
5868 for (unsigned Value = 0, NumValues = ValueVTs.size();
5869 Value != NumValues; ++Value) {
5870 EVT VT = ValueVTs[Value];
5871 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5872 ISD::ArgFlagsTy Flags;
5873 unsigned OriginalAlignment =
5874 TD->getABITypeAlignment(ArgTy);
5876 if (F.paramHasAttr(Idx, Attribute::ZExt))
5878 if (F.paramHasAttr(Idx, Attribute::SExt))
5880 if (F.paramHasAttr(Idx, Attribute::InReg))
5882 if (F.paramHasAttr(Idx, Attribute::StructRet))
5884 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5886 const PointerType *Ty = cast<PointerType>(I->getType());
5887 const Type *ElementTy = Ty->getElementType();
5888 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5889 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5890 // For ByVal, alignment should be passed from FE. BE will guess if
5891 // this info is not there but there are cases it cannot get right.
5892 if (F.getParamAlignment(Idx))
5893 FrameAlign = F.getParamAlignment(Idx);
5894 Flags.setByValAlign(FrameAlign);
5895 Flags.setByValSize(FrameSize);
5897 if (F.paramHasAttr(Idx, Attribute::Nest))
5899 Flags.setOrigAlign(OriginalAlignment);
5901 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5902 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5903 for (unsigned i = 0; i != NumRegs; ++i) {
5904 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5905 if (NumRegs > 1 && i == 0)
5906 MyFlags.Flags.setSplit();
5907 // if it isn't first piece, alignment must be 1
5909 MyFlags.Flags.setOrigAlign(1);
5910 Ins.push_back(MyFlags);
5915 // Call the target to set up the argument values.
5916 SmallVector<SDValue, 8> InVals;
5917 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5921 // Verify that the target's LowerFormalArguments behaved as expected.
5922 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5923 "LowerFormalArguments didn't return a valid chain!");
5924 assert(InVals.size() == Ins.size() &&
5925 "LowerFormalArguments didn't emit the correct number of values!");
5927 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5928 assert(InVals[i].getNode() &&
5929 "LowerFormalArguments emitted a null value!");
5930 assert(Ins[i].VT == InVals[i].getValueType() &&
5931 "LowerFormalArguments emitted a value with the wrong type!");
5935 // Update the DAG with the new chain value resulting from argument lowering.
5936 DAG.setRoot(NewRoot);
5938 // Set up the argument values.
5941 if (!FLI.CanLowerReturn) {
5942 // Create a virtual register for the sret pointer, and put in a copy
5943 // from the sret argument into it.
5944 SmallVector<EVT, 1> ValueVTs;
5945 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5946 EVT VT = ValueVTs[0];
5947 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5948 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5949 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
5950 RegVT, VT, AssertOp);
5952 MachineFunction& MF = SDB->DAG.getMachineFunction();
5953 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5954 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5955 FLI.DemoteRegister = SRetReg;
5956 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
5958 DAG.setRoot(NewRoot);
5960 // i indexes lowered arguments. Bump it past the hidden sret argument.
5961 // Idx indexes LLVM arguments. Don't touch it.
5965 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5967 SmallVector<SDValue, 4> ArgValues;
5968 SmallVector<EVT, 4> ValueVTs;
5969 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5970 unsigned NumValues = ValueVTs.size();
5971 for (unsigned Value = 0; Value != NumValues; ++Value) {
5972 EVT VT = ValueVTs[Value];
5973 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5974 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5976 if (!I->use_empty()) {
5977 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5978 if (F.paramHasAttr(Idx, Attribute::SExt))
5979 AssertOp = ISD::AssertSext;
5980 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5981 AssertOp = ISD::AssertZext;
5983 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
5984 NumParts, PartVT, VT,
5991 if (!I->use_empty()) {
5993 if (!ArgValues.empty())
5994 Res = DAG.getMergeValues(&ArgValues[0], NumValues,
5995 SDB->getCurDebugLoc());
5996 SDB->setValue(I, Res);
5998 // If this argument is live outside of the entry block, insert a copy from
5999 // whereever we got it to the vreg that other BB's will reference it as.
6000 SDB->CopyToExportRegsIfNeeded(I);
6004 assert(i == InVals.size() && "Argument register count mismatch!");
6006 // Finally, if the target has anything special to do, allow it to do so.
6007 // FIXME: this should insert code into the DAG!
6008 EmitFunctionEntryCode();
6011 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6012 /// ensure constants are generated when needed. Remember the virtual registers
6013 /// that need to be added to the Machine PHI nodes as input. We cannot just
6014 /// directly add them, because expansion might result in multiple MBB's for one
6015 /// BB. As such, the start of the BB might correspond to a different MBB than
6019 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6020 const TerminatorInst *TI = LLVMBB->getTerminator();
6022 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6024 // Check successor nodes' PHI nodes that expect a constant to be available
6026 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6027 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6028 if (!isa<PHINode>(SuccBB->begin())) continue;
6029 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6031 // If this terminator has multiple identical successors (common for
6032 // switches), only handle each succ once.
6033 if (!SuccsHandled.insert(SuccMBB)) continue;
6035 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6037 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6038 // nodes and Machine PHI nodes, but the incoming operands have not been
6040 for (BasicBlock::const_iterator I = SuccBB->begin();
6041 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6042 // Ignore dead phi's.
6043 if (PN->use_empty()) continue;
6046 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6048 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6049 unsigned &RegOut = SDB->ConstantsOut[C];
6051 RegOut = FuncInfo->CreateRegForValue(C);
6052 SDB->CopyValueToVirtualRegister(C, RegOut);
6056 Reg = FuncInfo->ValueMap[PHIOp];
6058 assert(isa<AllocaInst>(PHIOp) &&
6059 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6060 "Didn't codegen value into a register!??");
6061 Reg = FuncInfo->CreateRegForValue(PHIOp);
6062 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6066 // Remember that this register needs to added to the machine PHI node as
6067 // the input for this MBB.
6068 SmallVector<EVT, 4> ValueVTs;
6069 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6070 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6071 EVT VT = ValueVTs[vti];
6072 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6073 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6074 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6075 Reg += NumRegisters;
6079 SDB->ConstantsOut.clear();
6082 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6083 /// supports legal types, and it emits MachineInstrs directly instead of
6084 /// creating SelectionDAG nodes.
6087 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(const BasicBlock *LLVMBB,
6089 const TerminatorInst *TI = LLVMBB->getTerminator();
6091 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6092 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6094 // Check successor nodes' PHI nodes that expect a constant to be available
6096 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6097 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6098 if (!isa<PHINode>(SuccBB->begin())) continue;
6099 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6101 // If this terminator has multiple identical successors (common for
6102 // switches), only handle each succ once.
6103 if (!SuccsHandled.insert(SuccMBB)) continue;
6105 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6107 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6108 // nodes and Machine PHI nodes, but the incoming operands have not been
6110 for (BasicBlock::const_iterator I = SuccBB->begin();
6111 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6112 // Ignore dead phi's.
6113 if (PN->use_empty()) continue;
6115 // Only handle legal types. Two interesting things to note here. First,
6116 // by bailing out early, we may leave behind some dead instructions,
6117 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6118 // own moves. Second, this check is necessary becuase FastISel doesn't
6119 // use CreateRegForValue to create registers, so it always creates
6120 // exactly one register for each non-void instruction.
6121 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6122 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6125 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6127 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6132 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6134 unsigned Reg = F->getRegForValue(PHIOp);
6136 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6139 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));