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/Module.h"
32 #include "llvm/CodeGen/FastISel.h"
33 #include "llvm/CodeGen/GCStrategy.h"
34 #include "llvm/CodeGen/GCMetadata.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineJumpTableInfo.h"
39 #include "llvm/CodeGen/MachineModuleInfo.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/PseudoSourceValue.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/DwarfWriter.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 Code,
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 curret 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::getUnknownLoc();
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(Instruction &I) {
617 visit(I.getOpcode(), I);
620 void SelectionDAGBuilder::visit(unsigned Opcode, 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 ValueMap!");
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(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(Value *V) {
921 if (!V->use_empty()) {
922 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
923 if (VMI != FuncInfo.ValueMap.end())
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(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(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 (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 /// getFCmpCondCode - Return the ISD condition code corresponding to
976 /// the given LLVM IR floating-point condition code. This includes
977 /// consideration of global floating-point math flags.
979 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
980 ISD::CondCode FPC, FOC;
982 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
983 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
984 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
985 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
986 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
987 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
988 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
989 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
990 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
991 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
992 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
993 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
994 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
995 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
996 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
997 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
999 llvm_unreachable("Invalid FCmp predicate opcode!");
1000 FOC = FPC = ISD::SETFALSE;
1003 if (FiniteOnlyFPMath())
1009 /// getICmpCondCode - Return the ISD condition code corresponding to
1010 /// the given LLVM IR integer condition code.
1012 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1014 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1015 case ICmpInst::ICMP_NE: return ISD::SETNE;
1016 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1017 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1018 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1019 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1020 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1021 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1022 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1023 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1025 llvm_unreachable("Invalid ICmp predicate opcode!");
1030 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1031 /// This function emits a branch and is used at the leaves of an OR or an
1032 /// AND operator tree.
1035 SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1036 MachineBasicBlock *TBB,
1037 MachineBasicBlock *FBB,
1038 MachineBasicBlock *CurBB) {
1039 const BasicBlock *BB = CurBB->getBasicBlock();
1041 // If the leaf of the tree is a comparison, merge the condition into
1043 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1044 // The operands of the cmp have to be in this block. We don't know
1045 // how to export them from some other block. If this is the first block
1046 // of the sequence, no exporting is needed.
1047 if (CurBB == CurMBB ||
1048 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1049 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1050 ISD::CondCode Condition;
1051 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1052 Condition = getICmpCondCode(IC->getPredicate());
1053 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1054 Condition = getFCmpCondCode(FC->getPredicate());
1056 Condition = ISD::SETEQ; // silence warning.
1057 llvm_unreachable("Unknown compare instruction");
1060 CaseBlock CB(Condition, BOp->getOperand(0),
1061 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1062 SwitchCases.push_back(CB);
1067 // Create a CaseBlock record representing this branch.
1068 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1069 NULL, TBB, FBB, CurBB);
1070 SwitchCases.push_back(CB);
1073 /// FindMergedConditions - If Cond is an expression like
1074 void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1075 MachineBasicBlock *TBB,
1076 MachineBasicBlock *FBB,
1077 MachineBasicBlock *CurBB,
1079 // If this node is not part of the or/and tree, emit it as a branch.
1080 Instruction *BOp = dyn_cast<Instruction>(Cond);
1081 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1082 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1083 BOp->getParent() != CurBB->getBasicBlock() ||
1084 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1085 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1086 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1090 // Create TmpBB after CurBB.
1091 MachineFunction::iterator BBI = CurBB;
1092 MachineFunction &MF = DAG.getMachineFunction();
1093 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1094 CurBB->getParent()->insert(++BBI, TmpBB);
1096 if (Opc == Instruction::Or) {
1097 // Codegen X | Y as:
1105 // Emit the LHS condition.
1106 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1108 // Emit the RHS condition into TmpBB.
1109 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1111 assert(Opc == Instruction::And && "Unknown merge op!");
1112 // Codegen X & Y as:
1119 // This requires creation of TmpBB after CurBB.
1121 // Emit the LHS condition.
1122 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1124 // Emit the RHS condition into TmpBB.
1125 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1129 /// If the set of cases should be emitted as a series of branches, return true.
1130 /// If we should emit this as a bunch of and/or'd together conditions, return
1133 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1134 if (Cases.size() != 2) return true;
1136 // If this is two comparisons of the same values or'd or and'd together, they
1137 // will get folded into a single comparison, so don't emit two blocks.
1138 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1139 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1140 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1141 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1145 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1146 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1147 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1148 Cases[0].CC == Cases[1].CC &&
1149 isa<Constant>(Cases[0].CmpRHS) &&
1150 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1151 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1153 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1160 void SelectionDAGBuilder::visitBr(BranchInst &I) {
1161 // Update machine-CFG edges.
1162 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1164 // Figure out which block is immediately after the current one.
1165 MachineBasicBlock *NextBlock = 0;
1166 MachineFunction::iterator BBI = CurMBB;
1167 if (++BBI != FuncInfo.MF->end())
1170 if (I.isUnconditional()) {
1171 // Update machine-CFG edges.
1172 CurMBB->addSuccessor(Succ0MBB);
1174 // If this is not a fall-through branch, emit the branch.
1175 if (Succ0MBB != NextBlock)
1176 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1177 MVT::Other, getControlRoot(),
1178 DAG.getBasicBlock(Succ0MBB)));
1183 // If this condition is one of the special cases we handle, do special stuff
1185 Value *CondVal = I.getCondition();
1186 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1188 // If this is a series of conditions that are or'd or and'd together, emit
1189 // this as a sequence of branches instead of setcc's with and/or operations.
1190 // For example, instead of something like:
1203 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1204 if (BOp->hasOneUse() &&
1205 (BOp->getOpcode() == Instruction::And ||
1206 BOp->getOpcode() == Instruction::Or)) {
1207 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1208 // If the compares in later blocks need to use values not currently
1209 // exported from this block, export them now. This block should always
1210 // be the first entry.
1211 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1213 // Allow some cases to be rejected.
1214 if (ShouldEmitAsBranches(SwitchCases)) {
1215 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1216 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1217 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1220 // Emit the branch for this block.
1221 visitSwitchCase(SwitchCases[0]);
1222 SwitchCases.erase(SwitchCases.begin());
1226 // Okay, we decided not to do this, remove any inserted MBB's and clear
1228 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1229 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1231 SwitchCases.clear();
1235 // Create a CaseBlock record representing this branch.
1236 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1237 NULL, Succ0MBB, Succ1MBB, CurMBB);
1239 // Use visitSwitchCase to actually insert the fast branch sequence for this
1241 visitSwitchCase(CB);
1244 /// visitSwitchCase - Emits the necessary code to represent a single node in
1245 /// the binary search tree resulting from lowering a switch instruction.
1246 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1248 SDValue CondLHS = getValue(CB.CmpLHS);
1249 DebugLoc dl = getCurDebugLoc();
1251 // Build the setcc now.
1252 if (CB.CmpMHS == NULL) {
1253 // Fold "(X == true)" to X and "(X == false)" to !X to
1254 // handle common cases produced by branch lowering.
1255 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1256 CB.CC == ISD::SETEQ)
1258 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1259 CB.CC == ISD::SETEQ) {
1260 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1261 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1263 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1265 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1267 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1268 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1270 SDValue CmpOp = getValue(CB.CmpMHS);
1271 EVT VT = CmpOp.getValueType();
1273 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1274 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1277 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1278 VT, CmpOp, DAG.getConstant(Low, VT));
1279 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1280 DAG.getConstant(High-Low, VT), ISD::SETULE);
1284 // Update successor info
1285 CurMBB->addSuccessor(CB.TrueBB);
1286 CurMBB->addSuccessor(CB.FalseBB);
1288 // Set NextBlock to be the MBB immediately after the current one, if any.
1289 // This is used to avoid emitting unnecessary branches to the next block.
1290 MachineBasicBlock *NextBlock = 0;
1291 MachineFunction::iterator BBI = CurMBB;
1292 if (++BBI != FuncInfo.MF->end())
1295 // If the lhs block is the next block, invert the condition so that we can
1296 // fall through to the lhs instead of the rhs block.
1297 if (CB.TrueBB == NextBlock) {
1298 std::swap(CB.TrueBB, CB.FalseBB);
1299 SDValue True = DAG.getConstant(1, Cond.getValueType());
1300 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1303 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1304 MVT::Other, getControlRoot(), Cond,
1305 DAG.getBasicBlock(CB.TrueBB));
1307 // If the branch was constant folded, fix up the CFG.
1308 if (BrCond.getOpcode() == ISD::BR) {
1309 CurMBB->removeSuccessor(CB.FalseBB);
1311 // Otherwise, go ahead and insert the false branch.
1312 if (BrCond == getControlRoot())
1313 CurMBB->removeSuccessor(CB.TrueBB);
1315 if (CB.FalseBB != NextBlock)
1316 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1317 DAG.getBasicBlock(CB.FalseBB));
1320 DAG.setRoot(BrCond);
1323 /// visitJumpTable - Emit JumpTable node in the current MBB
1324 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1325 // Emit the code for the jump table
1326 assert(JT.Reg != -1U && "Should lower JT Header first!");
1327 EVT PTy = TLI.getPointerTy();
1328 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1330 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1331 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1332 MVT::Other, Index.getValue(1),
1334 DAG.setRoot(BrJumpTable);
1337 /// visitJumpTableHeader - This function emits necessary code to produce index
1338 /// in the JumpTable from switch case.
1339 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1340 JumpTableHeader &JTH) {
1341 // Subtract the lowest switch case value from the value being switched on and
1342 // conditional branch to default mbb if the result is greater than the
1343 // difference between smallest and largest cases.
1344 SDValue SwitchOp = getValue(JTH.SValue);
1345 EVT VT = SwitchOp.getValueType();
1346 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1347 DAG.getConstant(JTH.First, VT));
1349 // The SDNode we just created, which holds the value being switched on minus
1350 // the smallest case value, needs to be copied to a virtual register so it
1351 // can be used as an index into the jump table in a subsequent basic block.
1352 // This value may be smaller or larger than the target's pointer type, and
1353 // therefore require extension or truncating.
1354 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1356 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1357 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1358 JumpTableReg, SwitchOp);
1359 JT.Reg = JumpTableReg;
1361 // Emit the range check for the jump table, and branch to the default block
1362 // for the switch statement if the value being switched on exceeds the largest
1363 // case in the switch.
1364 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1365 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1366 DAG.getConstant(JTH.Last-JTH.First,VT),
1369 // Set NextBlock to be the MBB immediately after the current one, if any.
1370 // This is used to avoid emitting unnecessary branches to the next block.
1371 MachineBasicBlock *NextBlock = 0;
1372 MachineFunction::iterator BBI = CurMBB;
1374 if (++BBI != FuncInfo.MF->end())
1377 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1378 MVT::Other, CopyTo, CMP,
1379 DAG.getBasicBlock(JT.Default));
1381 if (JT.MBB != NextBlock)
1382 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1383 DAG.getBasicBlock(JT.MBB));
1385 DAG.setRoot(BrCond);
1388 /// visitBitTestHeader - This function emits necessary code to produce value
1389 /// suitable for "bit tests"
1390 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1391 // Subtract the minimum value
1392 SDValue SwitchOp = getValue(B.SValue);
1393 EVT VT = SwitchOp.getValueType();
1394 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1395 DAG.getConstant(B.First, VT));
1398 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1399 TLI.getSetCCResultType(Sub.getValueType()),
1400 Sub, DAG.getConstant(B.Range, VT),
1403 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1404 TLI.getPointerTy());
1406 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1407 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1410 // Set NextBlock to be the MBB immediately after the current one, if any.
1411 // This is used to avoid emitting unnecessary branches to the next block.
1412 MachineBasicBlock *NextBlock = 0;
1413 MachineFunction::iterator BBI = CurMBB;
1414 if (++BBI != FuncInfo.MF->end())
1417 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1419 CurMBB->addSuccessor(B.Default);
1420 CurMBB->addSuccessor(MBB);
1422 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1423 MVT::Other, CopyTo, RangeCmp,
1424 DAG.getBasicBlock(B.Default));
1426 if (MBB != NextBlock)
1427 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1428 DAG.getBasicBlock(MBB));
1430 DAG.setRoot(BrRange);
1433 /// visitBitTestCase - this function produces one "bit test"
1434 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1437 // Make desired shift
1438 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1439 TLI.getPointerTy());
1440 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1442 DAG.getConstant(1, TLI.getPointerTy()),
1445 // Emit bit tests and jumps
1446 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1447 TLI.getPointerTy(), SwitchVal,
1448 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1449 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1450 TLI.getSetCCResultType(AndOp.getValueType()),
1451 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1454 CurMBB->addSuccessor(B.TargetBB);
1455 CurMBB->addSuccessor(NextMBB);
1457 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1458 MVT::Other, getControlRoot(),
1459 AndCmp, DAG.getBasicBlock(B.TargetBB));
1461 // Set NextBlock to be the MBB immediately after the current one, if any.
1462 // This is used to avoid emitting unnecessary branches to the next block.
1463 MachineBasicBlock *NextBlock = 0;
1464 MachineFunction::iterator BBI = CurMBB;
1465 if (++BBI != FuncInfo.MF->end())
1468 if (NextMBB != NextBlock)
1469 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1470 DAG.getBasicBlock(NextMBB));
1475 void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
1476 // Retrieve successors.
1477 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1478 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1480 const Value *Callee(I.getCalledValue());
1481 if (isa<InlineAsm>(Callee))
1484 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1486 // If the value of the invoke is used outside of its defining block, make it
1487 // available as a virtual register.
1488 CopyToExportRegsIfNeeded(&I);
1490 // Update successor info
1491 CurMBB->addSuccessor(Return);
1492 CurMBB->addSuccessor(LandingPad);
1494 // Drop into normal successor.
1495 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1496 MVT::Other, getControlRoot(),
1497 DAG.getBasicBlock(Return)));
1500 void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
1503 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1504 /// small case ranges).
1505 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1506 CaseRecVector& WorkList,
1508 MachineBasicBlock* Default) {
1509 Case& BackCase = *(CR.Range.second-1);
1511 // Size is the number of Cases represented by this range.
1512 size_t Size = CR.Range.second - CR.Range.first;
1516 // Get the MachineFunction which holds the current MBB. This is used when
1517 // inserting any additional MBBs necessary to represent the switch.
1518 MachineFunction *CurMF = FuncInfo.MF;
1520 // Figure out which block is immediately after the current one.
1521 MachineBasicBlock *NextBlock = 0;
1522 MachineFunction::iterator BBI = CR.CaseBB;
1524 if (++BBI != FuncInfo.MF->end())
1527 // TODO: If any two of the cases has the same destination, and if one value
1528 // is the same as the other, but has one bit unset that the other has set,
1529 // use bit manipulation to do two compares at once. For example:
1530 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1532 // Rearrange the case blocks so that the last one falls through if possible.
1533 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1534 // The last case block won't fall through into 'NextBlock' if we emit the
1535 // branches in this order. See if rearranging a case value would help.
1536 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1537 if (I->BB == NextBlock) {
1538 std::swap(*I, BackCase);
1544 // Create a CaseBlock record representing a conditional branch to
1545 // the Case's target mbb if the value being switched on SV is equal
1547 MachineBasicBlock *CurBlock = CR.CaseBB;
1548 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1549 MachineBasicBlock *FallThrough;
1551 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1552 CurMF->insert(BBI, FallThrough);
1554 // Put SV in a virtual register to make it available from the new blocks.
1555 ExportFromCurrentBlock(SV);
1557 // If the last case doesn't match, go to the default block.
1558 FallThrough = Default;
1561 Value *RHS, *LHS, *MHS;
1563 if (I->High == I->Low) {
1564 // This is just small small case range :) containing exactly 1 case
1566 LHS = SV; RHS = I->High; MHS = NULL;
1569 LHS = I->Low; MHS = SV; RHS = I->High;
1571 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1573 // If emitting the first comparison, just call visitSwitchCase to emit the
1574 // code into the current block. Otherwise, push the CaseBlock onto the
1575 // vector to be later processed by SDISel, and insert the node's MBB
1576 // before the next MBB.
1577 if (CurBlock == CurMBB)
1578 visitSwitchCase(CB);
1580 SwitchCases.push_back(CB);
1582 CurBlock = FallThrough;
1588 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1589 return !DisableJumpTables &&
1590 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1591 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1594 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1595 APInt LastExt(Last), FirstExt(First);
1596 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1597 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1598 return (LastExt - FirstExt + 1ULL);
1601 /// handleJTSwitchCase - Emit jumptable for current switch case range
1602 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1603 CaseRecVector& WorkList,
1605 MachineBasicBlock* Default) {
1606 Case& FrontCase = *CR.Range.first;
1607 Case& BackCase = *(CR.Range.second-1);
1609 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1610 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1612 APInt TSize(First.getBitWidth(), 0);
1613 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1617 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1620 APInt Range = ComputeRange(First, Last);
1621 double Density = TSize.roundToDouble() / Range.roundToDouble();
1625 DEBUG(dbgs() << "Lowering jump table\n"
1626 << "First entry: " << First << ". Last entry: " << Last << '\n'
1627 << "Range: " << Range
1628 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1630 // Get the MachineFunction which holds the current MBB. This is used when
1631 // inserting any additional MBBs necessary to represent the switch.
1632 MachineFunction *CurMF = FuncInfo.MF;
1634 // Figure out which block is immediately after the current one.
1635 MachineFunction::iterator BBI = CR.CaseBB;
1638 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1640 // Create a new basic block to hold the code for loading the address
1641 // of the jump table, and jumping to it. Update successor information;
1642 // we will either branch to the default case for the switch, or the jump
1644 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1645 CurMF->insert(BBI, JumpTableBB);
1646 CR.CaseBB->addSuccessor(Default);
1647 CR.CaseBB->addSuccessor(JumpTableBB);
1649 // Build a vector of destination BBs, corresponding to each target
1650 // of the jump table. If the value of the jump table slot corresponds to
1651 // a case statement, push the case's BB onto the vector, otherwise, push
1653 std::vector<MachineBasicBlock*> DestBBs;
1655 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1656 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1657 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1659 if (Low.sle(TEI) && TEI.sle(High)) {
1660 DestBBs.push_back(I->BB);
1664 DestBBs.push_back(Default);
1668 // Update successor info. Add one edge to each unique successor.
1669 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1670 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1671 E = DestBBs.end(); I != E; ++I) {
1672 if (!SuccsHandled[(*I)->getNumber()]) {
1673 SuccsHandled[(*I)->getNumber()] = true;
1674 JumpTableBB->addSuccessor(*I);
1678 // Create a jump table index for this jump table.
1679 unsigned JTEncoding = TLI.getJumpTableEncoding();
1680 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1681 ->createJumpTableIndex(DestBBs);
1683 // Set the jump table information so that we can codegen it as a second
1684 // MachineBasicBlock
1685 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1686 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1687 if (CR.CaseBB == CurMBB)
1688 visitJumpTableHeader(JT, JTH);
1690 JTCases.push_back(JumpTableBlock(JTH, JT));
1695 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1697 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1698 CaseRecVector& WorkList,
1700 MachineBasicBlock* Default) {
1701 // Get the MachineFunction which holds the current MBB. This is used when
1702 // inserting any additional MBBs necessary to represent the switch.
1703 MachineFunction *CurMF = FuncInfo.MF;
1705 // Figure out which block is immediately after the current one.
1706 MachineFunction::iterator BBI = CR.CaseBB;
1709 Case& FrontCase = *CR.Range.first;
1710 Case& BackCase = *(CR.Range.second-1);
1711 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1713 // Size is the number of Cases represented by this range.
1714 unsigned Size = CR.Range.second - CR.Range.first;
1716 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1717 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1719 CaseItr Pivot = CR.Range.first + Size/2;
1721 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1722 // (heuristically) allow us to emit JumpTable's later.
1723 APInt TSize(First.getBitWidth(), 0);
1724 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1728 APInt LSize = FrontCase.size();
1729 APInt RSize = TSize-LSize;
1730 DEBUG(dbgs() << "Selecting best pivot: \n"
1731 << "First: " << First << ", Last: " << Last <<'\n'
1732 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1733 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1735 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1736 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1737 APInt Range = ComputeRange(LEnd, RBegin);
1738 assert((Range - 2ULL).isNonNegative() &&
1739 "Invalid case distance");
1740 double LDensity = (double)LSize.roundToDouble() /
1741 (LEnd - First + 1ULL).roundToDouble();
1742 double RDensity = (double)RSize.roundToDouble() /
1743 (Last - RBegin + 1ULL).roundToDouble();
1744 double Metric = Range.logBase2()*(LDensity+RDensity);
1745 // Should always split in some non-trivial place
1746 DEBUG(dbgs() <<"=>Step\n"
1747 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1748 << "LDensity: " << LDensity
1749 << ", RDensity: " << RDensity << '\n'
1750 << "Metric: " << Metric << '\n');
1751 if (FMetric < Metric) {
1754 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
1760 if (areJTsAllowed(TLI)) {
1761 // If our case is dense we *really* should handle it earlier!
1762 assert((FMetric > 0) && "Should handle dense range earlier!");
1764 Pivot = CR.Range.first + Size/2;
1767 CaseRange LHSR(CR.Range.first, Pivot);
1768 CaseRange RHSR(Pivot, CR.Range.second);
1769 Constant *C = Pivot->Low;
1770 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1772 // We know that we branch to the LHS if the Value being switched on is
1773 // less than the Pivot value, C. We use this to optimize our binary
1774 // tree a bit, by recognizing that if SV is greater than or equal to the
1775 // LHS's Case Value, and that Case Value is exactly one less than the
1776 // Pivot's Value, then we can branch directly to the LHS's Target,
1777 // rather than creating a leaf node for it.
1778 if ((LHSR.second - LHSR.first) == 1 &&
1779 LHSR.first->High == CR.GE &&
1780 cast<ConstantInt>(C)->getValue() ==
1781 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1782 TrueBB = LHSR.first->BB;
1784 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1785 CurMF->insert(BBI, TrueBB);
1786 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1788 // Put SV in a virtual register to make it available from the new blocks.
1789 ExportFromCurrentBlock(SV);
1792 // Similar to the optimization above, if the Value being switched on is
1793 // known to be less than the Constant CR.LT, and the current Case Value
1794 // is CR.LT - 1, then we can branch directly to the target block for
1795 // the current Case Value, rather than emitting a RHS leaf node for it.
1796 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1797 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1798 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1799 FalseBB = RHSR.first->BB;
1801 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1802 CurMF->insert(BBI, FalseBB);
1803 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1805 // Put SV in a virtual register to make it available from the new blocks.
1806 ExportFromCurrentBlock(SV);
1809 // Create a CaseBlock record representing a conditional branch to
1810 // the LHS node if the value being switched on SV is less than C.
1811 // Otherwise, branch to LHS.
1812 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1814 if (CR.CaseBB == CurMBB)
1815 visitSwitchCase(CB);
1817 SwitchCases.push_back(CB);
1822 /// handleBitTestsSwitchCase - if current case range has few destination and
1823 /// range span less, than machine word bitwidth, encode case range into series
1824 /// of masks and emit bit tests with these masks.
1825 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1826 CaseRecVector& WorkList,
1828 MachineBasicBlock* Default){
1829 EVT PTy = TLI.getPointerTy();
1830 unsigned IntPtrBits = PTy.getSizeInBits();
1832 Case& FrontCase = *CR.Range.first;
1833 Case& BackCase = *(CR.Range.second-1);
1835 // Get the MachineFunction which holds the current MBB. This is used when
1836 // inserting any additional MBBs necessary to represent the switch.
1837 MachineFunction *CurMF = FuncInfo.MF;
1839 // If target does not have legal shift left, do not emit bit tests at all.
1840 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1844 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1846 // Single case counts one, case range - two.
1847 numCmps += (I->Low == I->High ? 1 : 2);
1850 // Count unique destinations
1851 SmallSet<MachineBasicBlock*, 4> Dests;
1852 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1853 Dests.insert(I->BB);
1854 if (Dests.size() > 3)
1855 // Don't bother the code below, if there are too much unique destinations
1858 DEBUG(dbgs() << "Total number of unique destinations: "
1859 << Dests.size() << '\n'
1860 << "Total number of comparisons: " << numCmps << '\n');
1862 // Compute span of values.
1863 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1864 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1865 APInt cmpRange = maxValue - minValue;
1867 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
1868 << "Low bound: " << minValue << '\n'
1869 << "High bound: " << maxValue << '\n');
1871 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1872 (!(Dests.size() == 1 && numCmps >= 3) &&
1873 !(Dests.size() == 2 && numCmps >= 5) &&
1874 !(Dests.size() >= 3 && numCmps >= 6)))
1877 DEBUG(dbgs() << "Emitting bit tests\n");
1878 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1880 // Optimize the case where all the case values fit in a
1881 // word without having to subtract minValue. In this case,
1882 // we can optimize away the subtraction.
1883 if (minValue.isNonNegative() &&
1884 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1885 cmpRange = maxValue;
1887 lowBound = minValue;
1890 CaseBitsVector CasesBits;
1891 unsigned i, count = 0;
1893 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1894 MachineBasicBlock* Dest = I->BB;
1895 for (i = 0; i < count; ++i)
1896 if (Dest == CasesBits[i].BB)
1900 assert((count < 3) && "Too much destinations to test!");
1901 CasesBits.push_back(CaseBits(0, Dest, 0));
1905 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1906 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1908 uint64_t lo = (lowValue - lowBound).getZExtValue();
1909 uint64_t hi = (highValue - lowBound).getZExtValue();
1911 for (uint64_t j = lo; j <= hi; j++) {
1912 CasesBits[i].Mask |= 1ULL << j;
1913 CasesBits[i].Bits++;
1917 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1921 // Figure out which block is immediately after the current one.
1922 MachineFunction::iterator BBI = CR.CaseBB;
1925 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1927 DEBUG(dbgs() << "Cases:\n");
1928 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1929 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
1930 << ", Bits: " << CasesBits[i].Bits
1931 << ", BB: " << CasesBits[i].BB << '\n');
1933 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1934 CurMF->insert(BBI, CaseBB);
1935 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1939 // Put SV in a virtual register to make it available from the new blocks.
1940 ExportFromCurrentBlock(SV);
1943 BitTestBlock BTB(lowBound, cmpRange, SV,
1944 -1U, (CR.CaseBB == CurMBB),
1945 CR.CaseBB, Default, BTC);
1947 if (CR.CaseBB == CurMBB)
1948 visitBitTestHeader(BTB);
1950 BitTestCases.push_back(BTB);
1955 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1956 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1957 const SwitchInst& SI) {
1960 // Start with "simple" cases
1961 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1962 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1963 Cases.push_back(Case(SI.getSuccessorValue(i),
1964 SI.getSuccessorValue(i),
1967 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1969 // Merge case into clusters
1970 if (Cases.size() >= 2)
1971 // Must recompute end() each iteration because it may be
1972 // invalidated by erase if we hold on to it
1973 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1974 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1975 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1976 MachineBasicBlock* nextBB = J->BB;
1977 MachineBasicBlock* currentBB = I->BB;
1979 // If the two neighboring cases go to the same destination, merge them
1980 // into a single case.
1981 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1989 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1990 if (I->Low != I->High)
1991 // A range counts double, since it requires two compares.
1998 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
1999 // Figure out which block is immediately after the current one.
2000 MachineBasicBlock *NextBlock = 0;
2001 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2003 // If there is only the default destination, branch to it if it is not the
2004 // next basic block. Otherwise, just fall through.
2005 if (SI.getNumOperands() == 2) {
2006 // Update machine-CFG edges.
2008 // If this is not a fall-through branch, emit the branch.
2009 CurMBB->addSuccessor(Default);
2010 if (Default != NextBlock)
2011 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2012 MVT::Other, getControlRoot(),
2013 DAG.getBasicBlock(Default)));
2018 // If there are any non-default case statements, create a vector of Cases
2019 // representing each one, and sort the vector so that we can efficiently
2020 // create a binary search tree from them.
2022 size_t numCmps = Clusterify(Cases, SI);
2023 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2024 << ". Total compares: " << numCmps << '\n');
2027 // Get the Value to be switched on and default basic blocks, which will be
2028 // inserted into CaseBlock records, representing basic blocks in the binary
2030 Value *SV = SI.getOperand(0);
2032 // Push the initial CaseRec onto the worklist
2033 CaseRecVector WorkList;
2034 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2036 while (!WorkList.empty()) {
2037 // Grab a record representing a case range to process off the worklist
2038 CaseRec CR = WorkList.back();
2039 WorkList.pop_back();
2041 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2044 // If the range has few cases (two or less) emit a series of specific
2046 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2049 // If the switch has more than 5 blocks, and at least 40% dense, and the
2050 // target supports indirect branches, then emit a jump table rather than
2051 // lowering the switch to a binary tree of conditional branches.
2052 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2055 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2056 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2057 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2061 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
2062 // Update machine-CFG edges with unique successors.
2063 SmallVector<BasicBlock*, 32> succs;
2064 succs.reserve(I.getNumSuccessors());
2065 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2066 succs.push_back(I.getSuccessor(i));
2067 array_pod_sort(succs.begin(), succs.end());
2068 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2069 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2070 CurMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2072 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2073 MVT::Other, getControlRoot(),
2074 getValue(I.getAddress())));
2077 void SelectionDAGBuilder::visitFSub(User &I) {
2078 // -0.0 - X --> fneg
2079 const Type *Ty = I.getType();
2080 if (Ty->isVectorTy()) {
2081 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2082 const VectorType *DestTy = cast<VectorType>(I.getType());
2083 const Type *ElTy = DestTy->getElementType();
2084 unsigned VL = DestTy->getNumElements();
2085 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2086 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2088 SDValue Op2 = getValue(I.getOperand(1));
2089 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2090 Op2.getValueType(), Op2));
2096 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2097 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2098 SDValue Op2 = getValue(I.getOperand(1));
2099 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2100 Op2.getValueType(), Op2));
2104 visitBinary(I, ISD::FSUB);
2107 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2108 SDValue Op1 = getValue(I.getOperand(0));
2109 SDValue Op2 = getValue(I.getOperand(1));
2110 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2111 Op1.getValueType(), Op1, Op2));
2114 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2115 SDValue Op1 = getValue(I.getOperand(0));
2116 SDValue Op2 = getValue(I.getOperand(1));
2117 if (!I.getType()->isVectorTy() &&
2118 Op2.getValueType() != TLI.getShiftAmountTy()) {
2119 // If the operand is smaller than the shift count type, promote it.
2120 EVT PTy = TLI.getPointerTy();
2121 EVT STy = TLI.getShiftAmountTy();
2122 if (STy.bitsGT(Op2.getValueType()))
2123 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2124 TLI.getShiftAmountTy(), Op2);
2125 // If the operand is larger than the shift count type but the shift
2126 // count type has enough bits to represent any shift value, truncate
2127 // it now. This is a common case and it exposes the truncate to
2128 // optimization early.
2129 else if (STy.getSizeInBits() >=
2130 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2131 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2132 TLI.getShiftAmountTy(), Op2);
2133 // Otherwise we'll need to temporarily settle for some other
2134 // convenient type; type legalization will make adjustments as
2136 else if (PTy.bitsLT(Op2.getValueType()))
2137 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2138 TLI.getPointerTy(), Op2);
2139 else if (PTy.bitsGT(Op2.getValueType()))
2140 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2141 TLI.getPointerTy(), Op2);
2144 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2145 Op1.getValueType(), Op1, Op2));
2148 void SelectionDAGBuilder::visitICmp(User &I) {
2149 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2150 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2151 predicate = IC->getPredicate();
2152 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2153 predicate = ICmpInst::Predicate(IC->getPredicate());
2154 SDValue Op1 = getValue(I.getOperand(0));
2155 SDValue Op2 = getValue(I.getOperand(1));
2156 ISD::CondCode Opcode = getICmpCondCode(predicate);
2158 EVT DestVT = TLI.getValueType(I.getType());
2159 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2162 void SelectionDAGBuilder::visitFCmp(User &I) {
2163 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2164 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2165 predicate = FC->getPredicate();
2166 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2167 predicate = FCmpInst::Predicate(FC->getPredicate());
2168 SDValue Op1 = getValue(I.getOperand(0));
2169 SDValue Op2 = getValue(I.getOperand(1));
2170 ISD::CondCode Condition = getFCmpCondCode(predicate);
2171 EVT DestVT = TLI.getValueType(I.getType());
2172 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2175 void SelectionDAGBuilder::visitSelect(User &I) {
2176 SmallVector<EVT, 4> ValueVTs;
2177 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2178 unsigned NumValues = ValueVTs.size();
2179 if (NumValues == 0) return;
2181 SmallVector<SDValue, 4> Values(NumValues);
2182 SDValue Cond = getValue(I.getOperand(0));
2183 SDValue TrueVal = getValue(I.getOperand(1));
2184 SDValue FalseVal = getValue(I.getOperand(2));
2186 for (unsigned i = 0; i != NumValues; ++i)
2187 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2188 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2190 SDValue(TrueVal.getNode(),
2191 TrueVal.getResNo() + i),
2192 SDValue(FalseVal.getNode(),
2193 FalseVal.getResNo() + i));
2195 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2196 DAG.getVTList(&ValueVTs[0], NumValues),
2197 &Values[0], NumValues));
2200 void SelectionDAGBuilder::visitTrunc(User &I) {
2201 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2202 SDValue N = getValue(I.getOperand(0));
2203 EVT DestVT = TLI.getValueType(I.getType());
2204 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2207 void SelectionDAGBuilder::visitZExt(User &I) {
2208 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2209 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2210 SDValue N = getValue(I.getOperand(0));
2211 EVT DestVT = TLI.getValueType(I.getType());
2212 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2215 void SelectionDAGBuilder::visitSExt(User &I) {
2216 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2217 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2218 SDValue N = getValue(I.getOperand(0));
2219 EVT DestVT = TLI.getValueType(I.getType());
2220 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2223 void SelectionDAGBuilder::visitFPTrunc(User &I) {
2224 // FPTrunc is never a no-op cast, no need to check
2225 SDValue N = getValue(I.getOperand(0));
2226 EVT DestVT = TLI.getValueType(I.getType());
2227 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2228 DestVT, N, DAG.getIntPtrConstant(0)));
2231 void SelectionDAGBuilder::visitFPExt(User &I){
2232 // FPTrunc is never a no-op cast, no need to check
2233 SDValue N = getValue(I.getOperand(0));
2234 EVT DestVT = TLI.getValueType(I.getType());
2235 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2238 void SelectionDAGBuilder::visitFPToUI(User &I) {
2239 // FPToUI is never a no-op cast, no need to check
2240 SDValue N = getValue(I.getOperand(0));
2241 EVT DestVT = TLI.getValueType(I.getType());
2242 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2245 void SelectionDAGBuilder::visitFPToSI(User &I) {
2246 // FPToSI is never a no-op cast, no need to check
2247 SDValue N = getValue(I.getOperand(0));
2248 EVT DestVT = TLI.getValueType(I.getType());
2249 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2252 void SelectionDAGBuilder::visitUIToFP(User &I) {
2253 // UIToFP is never a no-op cast, no need to check
2254 SDValue N = getValue(I.getOperand(0));
2255 EVT DestVT = TLI.getValueType(I.getType());
2256 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2259 void SelectionDAGBuilder::visitSIToFP(User &I){
2260 // SIToFP is never a no-op cast, no need to check
2261 SDValue N = getValue(I.getOperand(0));
2262 EVT DestVT = TLI.getValueType(I.getType());
2263 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2266 void SelectionDAGBuilder::visitPtrToInt(User &I) {
2267 // What to do depends on the size of the integer and the size of the pointer.
2268 // We can either truncate, zero extend, or no-op, accordingly.
2269 SDValue N = getValue(I.getOperand(0));
2270 EVT SrcVT = N.getValueType();
2271 EVT DestVT = TLI.getValueType(I.getType());
2272 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2275 void SelectionDAGBuilder::visitIntToPtr(User &I) {
2276 // What to do depends on the size of the integer and the size of the pointer.
2277 // We can either truncate, zero extend, or no-op, accordingly.
2278 SDValue N = getValue(I.getOperand(0));
2279 EVT SrcVT = N.getValueType();
2280 EVT DestVT = TLI.getValueType(I.getType());
2281 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2284 void SelectionDAGBuilder::visitBitCast(User &I) {
2285 SDValue N = getValue(I.getOperand(0));
2286 EVT DestVT = TLI.getValueType(I.getType());
2288 // BitCast assures us that source and destination are the same size so this is
2289 // either a BIT_CONVERT or a no-op.
2290 if (DestVT != N.getValueType())
2291 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2292 DestVT, N)); // convert types.
2294 setValue(&I, N); // noop cast.
2297 void SelectionDAGBuilder::visitInsertElement(User &I) {
2298 SDValue InVec = getValue(I.getOperand(0));
2299 SDValue InVal = getValue(I.getOperand(1));
2300 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2302 getValue(I.getOperand(2)));
2303 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2304 TLI.getValueType(I.getType()),
2305 InVec, InVal, InIdx));
2308 void SelectionDAGBuilder::visitExtractElement(User &I) {
2309 SDValue InVec = getValue(I.getOperand(0));
2310 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2312 getValue(I.getOperand(1)));
2313 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2314 TLI.getValueType(I.getType()), InVec, InIdx));
2317 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2318 // from SIndx and increasing to the element length (undefs are allowed).
2319 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2320 unsigned MaskNumElts = Mask.size();
2321 for (unsigned i = 0; i != MaskNumElts; ++i)
2322 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2327 void SelectionDAGBuilder::visitShuffleVector(User &I) {
2328 SmallVector<int, 8> Mask;
2329 SDValue Src1 = getValue(I.getOperand(0));
2330 SDValue Src2 = getValue(I.getOperand(1));
2332 // Convert the ConstantVector mask operand into an array of ints, with -1
2333 // representing undef values.
2334 SmallVector<Constant*, 8> MaskElts;
2335 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2336 unsigned MaskNumElts = MaskElts.size();
2337 for (unsigned i = 0; i != MaskNumElts; ++i) {
2338 if (isa<UndefValue>(MaskElts[i]))
2341 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2344 EVT VT = TLI.getValueType(I.getType());
2345 EVT SrcVT = Src1.getValueType();
2346 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2348 if (SrcNumElts == MaskNumElts) {
2349 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2354 // Normalize the shuffle vector since mask and vector length don't match.
2355 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2356 // Mask is longer than the source vectors and is a multiple of the source
2357 // vectors. We can use concatenate vector to make the mask and vectors
2359 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2360 // The shuffle is concatenating two vectors together.
2361 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2366 // Pad both vectors with undefs to make them the same length as the mask.
2367 unsigned NumConcat = MaskNumElts / SrcNumElts;
2368 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2369 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2370 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2372 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2373 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2377 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2378 getCurDebugLoc(), VT,
2379 &MOps1[0], NumConcat);
2380 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2381 getCurDebugLoc(), VT,
2382 &MOps2[0], NumConcat);
2384 // Readjust mask for new input vector length.
2385 SmallVector<int, 8> MappedOps;
2386 for (unsigned i = 0; i != MaskNumElts; ++i) {
2388 if (Idx < (int)SrcNumElts)
2389 MappedOps.push_back(Idx);
2391 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2394 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2399 if (SrcNumElts > MaskNumElts) {
2400 // Analyze the access pattern of the vector to see if we can extract
2401 // two subvectors and do the shuffle. The analysis is done by calculating
2402 // the range of elements the mask access on both vectors.
2403 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2404 int MaxRange[2] = {-1, -1};
2406 for (unsigned i = 0; i != MaskNumElts; ++i) {
2412 if (Idx >= (int)SrcNumElts) {
2416 if (Idx > MaxRange[Input])
2417 MaxRange[Input] = Idx;
2418 if (Idx < MinRange[Input])
2419 MinRange[Input] = Idx;
2422 // Check if the access is smaller than the vector size and can we find
2423 // a reasonable extract index.
2424 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2426 int StartIdx[2]; // StartIdx to extract from
2427 for (int Input=0; Input < 2; ++Input) {
2428 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2429 RangeUse[Input] = 0; // Unused
2430 StartIdx[Input] = 0;
2431 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2432 // Fits within range but we should see if we can find a good
2433 // start index that is a multiple of the mask length.
2434 if (MaxRange[Input] < (int)MaskNumElts) {
2435 RangeUse[Input] = 1; // Extract from beginning of the vector
2436 StartIdx[Input] = 0;
2438 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2439 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2440 StartIdx[Input] + MaskNumElts < SrcNumElts)
2441 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2446 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2447 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2450 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2451 // Extract appropriate subvector and generate a vector shuffle
2452 for (int Input=0; Input < 2; ++Input) {
2453 SDValue &Src = Input == 0 ? Src1 : Src2;
2454 if (RangeUse[Input] == 0)
2455 Src = DAG.getUNDEF(VT);
2457 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2458 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2461 // Calculate new mask.
2462 SmallVector<int, 8> MappedOps;
2463 for (unsigned i = 0; i != MaskNumElts; ++i) {
2466 MappedOps.push_back(Idx);
2467 else if (Idx < (int)SrcNumElts)
2468 MappedOps.push_back(Idx - StartIdx[0]);
2470 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2473 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2479 // We can't use either concat vectors or extract subvectors so fall back to
2480 // replacing the shuffle with extract and build vector.
2481 // to insert and build vector.
2482 EVT EltVT = VT.getVectorElementType();
2483 EVT PtrVT = TLI.getPointerTy();
2484 SmallVector<SDValue,8> Ops;
2485 for (unsigned i = 0; i != MaskNumElts; ++i) {
2487 Ops.push_back(DAG.getUNDEF(EltVT));
2492 if (Idx < (int)SrcNumElts)
2493 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2494 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2496 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2498 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2504 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2505 VT, &Ops[0], Ops.size()));
2508 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2509 const Value *Op0 = I.getOperand(0);
2510 const Value *Op1 = I.getOperand(1);
2511 const Type *AggTy = I.getType();
2512 const Type *ValTy = Op1->getType();
2513 bool IntoUndef = isa<UndefValue>(Op0);
2514 bool FromUndef = isa<UndefValue>(Op1);
2516 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2517 I.idx_begin(), I.idx_end());
2519 SmallVector<EVT, 4> AggValueVTs;
2520 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2521 SmallVector<EVT, 4> ValValueVTs;
2522 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2524 unsigned NumAggValues = AggValueVTs.size();
2525 unsigned NumValValues = ValValueVTs.size();
2526 SmallVector<SDValue, 4> Values(NumAggValues);
2528 SDValue Agg = getValue(Op0);
2529 SDValue Val = getValue(Op1);
2531 // Copy the beginning value(s) from the original aggregate.
2532 for (; i != LinearIndex; ++i)
2533 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2534 SDValue(Agg.getNode(), Agg.getResNo() + i);
2535 // Copy values from the inserted value(s).
2536 for (; i != LinearIndex + NumValValues; ++i)
2537 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2538 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2539 // Copy remaining value(s) from the original aggregate.
2540 for (; i != NumAggValues; ++i)
2541 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2542 SDValue(Agg.getNode(), Agg.getResNo() + i);
2544 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2545 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2546 &Values[0], NumAggValues));
2549 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2550 const Value *Op0 = I.getOperand(0);
2551 const Type *AggTy = Op0->getType();
2552 const Type *ValTy = I.getType();
2553 bool OutOfUndef = isa<UndefValue>(Op0);
2555 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2556 I.idx_begin(), I.idx_end());
2558 SmallVector<EVT, 4> ValValueVTs;
2559 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2561 unsigned NumValValues = ValValueVTs.size();
2562 SmallVector<SDValue, 4> Values(NumValValues);
2564 SDValue Agg = getValue(Op0);
2565 // Copy out the selected value(s).
2566 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2567 Values[i - LinearIndex] =
2569 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2570 SDValue(Agg.getNode(), Agg.getResNo() + i);
2572 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2573 DAG.getVTList(&ValValueVTs[0], NumValValues),
2574 &Values[0], NumValValues));
2577 void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2578 SDValue N = getValue(I.getOperand(0));
2579 const Type *Ty = I.getOperand(0)->getType();
2581 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2584 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2585 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2588 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2589 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2590 DAG.getIntPtrConstant(Offset));
2593 Ty = StTy->getElementType(Field);
2594 } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) {
2595 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2597 // Offset canonically 0 for unions, but type changes
2598 Ty = UnTy->getElementType(Field);
2600 Ty = cast<SequentialType>(Ty)->getElementType();
2602 // If this is a constant subscript, handle it quickly.
2603 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2604 if (CI->getZExtValue() == 0) continue;
2606 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2608 EVT PTy = TLI.getPointerTy();
2609 unsigned PtrBits = PTy.getSizeInBits();
2611 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2613 DAG.getConstant(Offs, MVT::i64));
2615 OffsVal = DAG.getIntPtrConstant(Offs);
2617 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2622 // N = N + Idx * ElementSize;
2623 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2624 TD->getTypeAllocSize(Ty));
2625 SDValue IdxN = getValue(Idx);
2627 // If the index is smaller or larger than intptr_t, truncate or extend
2629 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2631 // If this is a multiply by a power of two, turn it into a shl
2632 // immediately. This is a very common case.
2633 if (ElementSize != 1) {
2634 if (ElementSize.isPowerOf2()) {
2635 unsigned Amt = ElementSize.logBase2();
2636 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2637 N.getValueType(), IdxN,
2638 DAG.getConstant(Amt, TLI.getPointerTy()));
2640 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2641 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2642 N.getValueType(), IdxN, Scale);
2646 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2647 N.getValueType(), N, IdxN);
2654 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2655 // If this is a fixed sized alloca in the entry block of the function,
2656 // allocate it statically on the stack.
2657 if (FuncInfo.StaticAllocaMap.count(&I))
2658 return; // getValue will auto-populate this.
2660 const Type *Ty = I.getAllocatedType();
2661 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2663 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2666 SDValue AllocSize = getValue(I.getArraySize());
2668 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2670 DAG.getConstant(TySize, AllocSize.getValueType()));
2672 EVT IntPtr = TLI.getPointerTy();
2673 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2675 // Handle alignment. If the requested alignment is less than or equal to
2676 // the stack alignment, ignore it. If the size is greater than or equal to
2677 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2678 unsigned StackAlign =
2679 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2680 if (Align <= StackAlign)
2683 // Round the size of the allocation up to the stack alignment size
2684 // by add SA-1 to the size.
2685 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2686 AllocSize.getValueType(), AllocSize,
2687 DAG.getIntPtrConstant(StackAlign-1));
2689 // Mask out the low bits for alignment purposes.
2690 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2691 AllocSize.getValueType(), AllocSize,
2692 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2694 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2695 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2696 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2699 DAG.setRoot(DSA.getValue(1));
2701 // Inform the Frame Information that we have just allocated a variable-sized
2703 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2706 void SelectionDAGBuilder::visitLoad(LoadInst &I) {
2707 const Value *SV = I.getOperand(0);
2708 SDValue Ptr = getValue(SV);
2710 const Type *Ty = I.getType();
2712 bool isVolatile = I.isVolatile();
2713 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2714 unsigned Alignment = I.getAlignment();
2716 SmallVector<EVT, 4> ValueVTs;
2717 SmallVector<uint64_t, 4> Offsets;
2718 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2719 unsigned NumValues = ValueVTs.size();
2724 bool ConstantMemory = false;
2726 // Serialize volatile loads with other side effects.
2728 else if (AA->pointsToConstantMemory(SV)) {
2729 // Do not serialize (non-volatile) loads of constant memory with anything.
2730 Root = DAG.getEntryNode();
2731 ConstantMemory = true;
2733 // Do not serialize non-volatile loads against each other.
2734 Root = DAG.getRoot();
2737 SmallVector<SDValue, 4> Values(NumValues);
2738 SmallVector<SDValue, 4> Chains(NumValues);
2739 EVT PtrVT = Ptr.getValueType();
2740 for (unsigned i = 0; i != NumValues; ++i) {
2741 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2743 DAG.getConstant(Offsets[i], PtrVT));
2744 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2745 A, SV, Offsets[i], isVolatile,
2746 isNonTemporal, Alignment);
2749 Chains[i] = L.getValue(1);
2752 if (!ConstantMemory) {
2753 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2754 MVT::Other, &Chains[0], NumValues);
2758 PendingLoads.push_back(Chain);
2761 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2762 DAG.getVTList(&ValueVTs[0], NumValues),
2763 &Values[0], NumValues));
2766 void SelectionDAGBuilder::visitStore(StoreInst &I) {
2767 Value *SrcV = I.getOperand(0);
2768 Value *PtrV = I.getOperand(1);
2770 SmallVector<EVT, 4> ValueVTs;
2771 SmallVector<uint64_t, 4> Offsets;
2772 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2773 unsigned NumValues = ValueVTs.size();
2777 // Get the lowered operands. Note that we do this after
2778 // checking if NumResults is zero, because with zero results
2779 // the operands won't have values in the map.
2780 SDValue Src = getValue(SrcV);
2781 SDValue Ptr = getValue(PtrV);
2783 SDValue Root = getRoot();
2784 SmallVector<SDValue, 4> Chains(NumValues);
2785 EVT PtrVT = Ptr.getValueType();
2786 bool isVolatile = I.isVolatile();
2787 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2788 unsigned Alignment = I.getAlignment();
2790 for (unsigned i = 0; i != NumValues; ++i) {
2791 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2792 DAG.getConstant(Offsets[i], PtrVT));
2793 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2794 SDValue(Src.getNode(), Src.getResNo() + i),
2795 Add, PtrV, Offsets[i], isVolatile,
2796 isNonTemporal, Alignment);
2799 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2800 MVT::Other, &Chains[0], NumValues));
2803 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2805 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2806 unsigned Intrinsic) {
2807 bool HasChain = !I.doesNotAccessMemory();
2808 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2810 // Build the operand list.
2811 SmallVector<SDValue, 8> Ops;
2812 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2814 // We don't need to serialize loads against other loads.
2815 Ops.push_back(DAG.getRoot());
2817 Ops.push_back(getRoot());
2821 // Info is set by getTgtMemInstrinsic
2822 TargetLowering::IntrinsicInfo Info;
2823 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2825 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2826 if (!IsTgtIntrinsic)
2827 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2829 // Add all operands of the call to the operand list.
2830 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2831 SDValue Op = getValue(I.getOperand(i));
2832 assert(TLI.isTypeLegal(Op.getValueType()) &&
2833 "Intrinsic uses a non-legal type?");
2837 SmallVector<EVT, 4> ValueVTs;
2838 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2840 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2841 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2842 "Intrinsic uses a non-legal type?");
2847 ValueVTs.push_back(MVT::Other);
2849 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2853 if (IsTgtIntrinsic) {
2854 // This is target intrinsic that touches memory
2855 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2856 VTs, &Ops[0], Ops.size(),
2857 Info.memVT, Info.ptrVal, Info.offset,
2858 Info.align, Info.vol,
2859 Info.readMem, Info.writeMem);
2860 } else if (!HasChain) {
2861 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2862 VTs, &Ops[0], Ops.size());
2863 } else if (!I.getType()->isVoidTy()) {
2864 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2865 VTs, &Ops[0], Ops.size());
2867 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2868 VTs, &Ops[0], Ops.size());
2872 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2874 PendingLoads.push_back(Chain);
2879 if (!I.getType()->isVoidTy()) {
2880 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2881 EVT VT = TLI.getValueType(PTy);
2882 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2885 setValue(&I, Result);
2889 /// GetSignificand - Get the significand and build it into a floating-point
2890 /// number with exponent of 1:
2892 /// Op = (Op & 0x007fffff) | 0x3f800000;
2894 /// where Op is the hexidecimal representation of floating point value.
2896 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
2897 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2898 DAG.getConstant(0x007fffff, MVT::i32));
2899 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2900 DAG.getConstant(0x3f800000, MVT::i32));
2901 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
2904 /// GetExponent - Get the exponent:
2906 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
2908 /// where Op is the hexidecimal representation of floating point value.
2910 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
2912 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2913 DAG.getConstant(0x7f800000, MVT::i32));
2914 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
2915 DAG.getConstant(23, TLI.getPointerTy()));
2916 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2917 DAG.getConstant(127, MVT::i32));
2918 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
2921 /// getF32Constant - Get 32-bit floating point constant.
2923 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2924 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2927 /// Inlined utility function to implement binary input atomic intrinsics for
2928 /// visitIntrinsicCall: I is a call instruction
2929 /// Op is the associated NodeType for I
2931 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2932 SDValue Root = getRoot();
2934 DAG.getAtomic(Op, getCurDebugLoc(),
2935 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2937 getValue(I.getOperand(1)),
2938 getValue(I.getOperand(2)),
2941 DAG.setRoot(L.getValue(1));
2945 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2947 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
2948 SDValue Op1 = getValue(I.getOperand(1));
2949 SDValue Op2 = getValue(I.getOperand(2));
2951 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
2952 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
2956 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2957 /// limited-precision mode.
2959 SelectionDAGBuilder::visitExp(CallInst &I) {
2961 DebugLoc dl = getCurDebugLoc();
2963 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2964 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2965 SDValue Op = getValue(I.getOperand(1));
2967 // Put the exponent in the right bit position for later addition to the
2970 // #define LOG2OFe 1.4426950f
2971 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2972 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
2973 getF32Constant(DAG, 0x3fb8aa3b));
2974 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
2976 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2977 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2978 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
2980 // IntegerPartOfX <<= 23;
2981 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
2982 DAG.getConstant(23, TLI.getPointerTy()));
2984 if (LimitFloatPrecision <= 6) {
2985 // For floating-point precision of 6:
2987 // TwoToFractionalPartOfX =
2989 // (0.735607626f + 0.252464424f * x) * x;
2991 // error 0.0144103317, which is 6 bits
2992 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
2993 getF32Constant(DAG, 0x3e814304));
2994 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
2995 getF32Constant(DAG, 0x3f3c50c8));
2996 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2997 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
2998 getF32Constant(DAG, 0x3f7f5e7e));
2999 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3001 // Add the exponent into the result in integer domain.
3002 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3003 TwoToFracPartOfX, IntegerPartOfX);
3005 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3006 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3007 // For floating-point precision of 12:
3009 // TwoToFractionalPartOfX =
3012 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3014 // 0.000107046256 error, which is 13 to 14 bits
3015 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3016 getF32Constant(DAG, 0x3da235e3));
3017 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3018 getF32Constant(DAG, 0x3e65b8f3));
3019 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3020 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3021 getF32Constant(DAG, 0x3f324b07));
3022 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3023 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3024 getF32Constant(DAG, 0x3f7ff8fd));
3025 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3027 // Add the exponent into the result in integer domain.
3028 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3029 TwoToFracPartOfX, IntegerPartOfX);
3031 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3032 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3033 // For floating-point precision of 18:
3035 // TwoToFractionalPartOfX =
3039 // (0.554906021e-1f +
3040 // (0.961591928e-2f +
3041 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3043 // error 2.47208000*10^(-7), which is better than 18 bits
3044 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3045 getF32Constant(DAG, 0x3924b03e));
3046 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3047 getF32Constant(DAG, 0x3ab24b87));
3048 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3049 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3050 getF32Constant(DAG, 0x3c1d8c17));
3051 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3052 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3053 getF32Constant(DAG, 0x3d634a1d));
3054 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3055 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3056 getF32Constant(DAG, 0x3e75fe14));
3057 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3058 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3059 getF32Constant(DAG, 0x3f317234));
3060 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3061 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3062 getF32Constant(DAG, 0x3f800000));
3063 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3066 // Add the exponent into the result in integer domain.
3067 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3068 TwoToFracPartOfX, IntegerPartOfX);
3070 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3073 // No special expansion.
3074 result = DAG.getNode(ISD::FEXP, dl,
3075 getValue(I.getOperand(1)).getValueType(),
3076 getValue(I.getOperand(1)));
3079 setValue(&I, result);
3082 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3083 /// limited-precision mode.
3085 SelectionDAGBuilder::visitLog(CallInst &I) {
3087 DebugLoc dl = getCurDebugLoc();
3089 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3090 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3091 SDValue Op = getValue(I.getOperand(1));
3092 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3094 // Scale the exponent by log(2) [0.69314718f].
3095 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3096 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3097 getF32Constant(DAG, 0x3f317218));
3099 // Get the significand and build it into a floating-point number with
3101 SDValue X = GetSignificand(DAG, Op1, dl);
3103 if (LimitFloatPrecision <= 6) {
3104 // For floating-point precision of 6:
3108 // (1.4034025f - 0.23903021f * x) * x;
3110 // error 0.0034276066, which is better than 8 bits
3111 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3112 getF32Constant(DAG, 0xbe74c456));
3113 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3114 getF32Constant(DAG, 0x3fb3a2b1));
3115 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3116 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3117 getF32Constant(DAG, 0x3f949a29));
3119 result = DAG.getNode(ISD::FADD, dl,
3120 MVT::f32, LogOfExponent, LogOfMantissa);
3121 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3122 // For floating-point precision of 12:
3128 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3130 // error 0.000061011436, which is 14 bits
3131 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3132 getF32Constant(DAG, 0xbd67b6d6));
3133 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3134 getF32Constant(DAG, 0x3ee4f4b8));
3135 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3136 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3137 getF32Constant(DAG, 0x3fbc278b));
3138 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3139 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3140 getF32Constant(DAG, 0x40348e95));
3141 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3142 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3143 getF32Constant(DAG, 0x3fdef31a));
3145 result = DAG.getNode(ISD::FADD, dl,
3146 MVT::f32, LogOfExponent, LogOfMantissa);
3147 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3148 // For floating-point precision of 18:
3156 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3158 // error 0.0000023660568, which is better than 18 bits
3159 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3160 getF32Constant(DAG, 0xbc91e5ac));
3161 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3162 getF32Constant(DAG, 0x3e4350aa));
3163 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3164 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3165 getF32Constant(DAG, 0x3f60d3e3));
3166 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3167 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3168 getF32Constant(DAG, 0x4011cdf0));
3169 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3170 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3171 getF32Constant(DAG, 0x406cfd1c));
3172 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3173 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3174 getF32Constant(DAG, 0x408797cb));
3175 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3176 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3177 getF32Constant(DAG, 0x4006dcab));
3179 result = DAG.getNode(ISD::FADD, dl,
3180 MVT::f32, LogOfExponent, LogOfMantissa);
3183 // No special expansion.
3184 result = DAG.getNode(ISD::FLOG, dl,
3185 getValue(I.getOperand(1)).getValueType(),
3186 getValue(I.getOperand(1)));
3189 setValue(&I, result);
3192 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3193 /// limited-precision mode.
3195 SelectionDAGBuilder::visitLog2(CallInst &I) {
3197 DebugLoc dl = getCurDebugLoc();
3199 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3200 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3201 SDValue Op = getValue(I.getOperand(1));
3202 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3204 // Get the exponent.
3205 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3207 // Get the significand and build it into a floating-point number with
3209 SDValue X = GetSignificand(DAG, Op1, dl);
3211 // Different possible minimax approximations of significand in
3212 // floating-point for various degrees of accuracy over [1,2].
3213 if (LimitFloatPrecision <= 6) {
3214 // For floating-point precision of 6:
3216 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3218 // error 0.0049451742, which is more than 7 bits
3219 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3220 getF32Constant(DAG, 0xbeb08fe0));
3221 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3222 getF32Constant(DAG, 0x40019463));
3223 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3224 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3225 getF32Constant(DAG, 0x3fd6633d));
3227 result = DAG.getNode(ISD::FADD, dl,
3228 MVT::f32, LogOfExponent, Log2ofMantissa);
3229 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3230 // For floating-point precision of 12:
3236 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3238 // error 0.0000876136000, which is better than 13 bits
3239 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3240 getF32Constant(DAG, 0xbda7262e));
3241 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3242 getF32Constant(DAG, 0x3f25280b));
3243 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3244 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3245 getF32Constant(DAG, 0x4007b923));
3246 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3247 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3248 getF32Constant(DAG, 0x40823e2f));
3249 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3250 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3251 getF32Constant(DAG, 0x4020d29c));
3253 result = DAG.getNode(ISD::FADD, dl,
3254 MVT::f32, LogOfExponent, Log2ofMantissa);
3255 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3256 // For floating-point precision of 18:
3265 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3267 // error 0.0000018516, which is better than 18 bits
3268 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3269 getF32Constant(DAG, 0xbcd2769e));
3270 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3271 getF32Constant(DAG, 0x3e8ce0b9));
3272 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3273 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3274 getF32Constant(DAG, 0x3fa22ae7));
3275 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3276 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3277 getF32Constant(DAG, 0x40525723));
3278 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3279 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3280 getF32Constant(DAG, 0x40aaf200));
3281 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3282 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3283 getF32Constant(DAG, 0x40c39dad));
3284 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3285 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3286 getF32Constant(DAG, 0x4042902c));
3288 result = DAG.getNode(ISD::FADD, dl,
3289 MVT::f32, LogOfExponent, Log2ofMantissa);
3292 // No special expansion.
3293 result = DAG.getNode(ISD::FLOG2, dl,
3294 getValue(I.getOperand(1)).getValueType(),
3295 getValue(I.getOperand(1)));
3298 setValue(&I, result);
3301 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3302 /// limited-precision mode.
3304 SelectionDAGBuilder::visitLog10(CallInst &I) {
3306 DebugLoc dl = getCurDebugLoc();
3308 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3309 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3310 SDValue Op = getValue(I.getOperand(1));
3311 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3313 // Scale the exponent by log10(2) [0.30102999f].
3314 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3315 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3316 getF32Constant(DAG, 0x3e9a209a));
3318 // Get the significand and build it into a floating-point number with
3320 SDValue X = GetSignificand(DAG, Op1, dl);
3322 if (LimitFloatPrecision <= 6) {
3323 // For floating-point precision of 6:
3325 // Log10ofMantissa =
3327 // (0.60948995f - 0.10380950f * x) * x;
3329 // error 0.0014886165, which is 6 bits
3330 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3331 getF32Constant(DAG, 0xbdd49a13));
3332 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3333 getF32Constant(DAG, 0x3f1c0789));
3334 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3335 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3336 getF32Constant(DAG, 0x3f011300));
3338 result = DAG.getNode(ISD::FADD, dl,
3339 MVT::f32, LogOfExponent, Log10ofMantissa);
3340 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3341 // For floating-point precision of 12:
3343 // Log10ofMantissa =
3346 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3348 // error 0.00019228036, which is better than 12 bits
3349 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3350 getF32Constant(DAG, 0x3d431f31));
3351 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3352 getF32Constant(DAG, 0x3ea21fb2));
3353 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3354 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3355 getF32Constant(DAG, 0x3f6ae232));
3356 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3357 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3358 getF32Constant(DAG, 0x3f25f7c3));
3360 result = DAG.getNode(ISD::FADD, dl,
3361 MVT::f32, LogOfExponent, Log10ofMantissa);
3362 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3363 // For floating-point precision of 18:
3365 // Log10ofMantissa =
3370 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3372 // error 0.0000037995730, which is better than 18 bits
3373 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3374 getF32Constant(DAG, 0x3c5d51ce));
3375 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3376 getF32Constant(DAG, 0x3e00685a));
3377 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3378 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3379 getF32Constant(DAG, 0x3efb6798));
3380 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3381 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3382 getF32Constant(DAG, 0x3f88d192));
3383 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3384 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3385 getF32Constant(DAG, 0x3fc4316c));
3386 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3387 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3388 getF32Constant(DAG, 0x3f57ce70));
3390 result = DAG.getNode(ISD::FADD, dl,
3391 MVT::f32, LogOfExponent, Log10ofMantissa);
3394 // No special expansion.
3395 result = DAG.getNode(ISD::FLOG10, dl,
3396 getValue(I.getOperand(1)).getValueType(),
3397 getValue(I.getOperand(1)));
3400 setValue(&I, result);
3403 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3404 /// limited-precision mode.
3406 SelectionDAGBuilder::visitExp2(CallInst &I) {
3408 DebugLoc dl = getCurDebugLoc();
3410 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3411 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3412 SDValue Op = getValue(I.getOperand(1));
3414 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3416 // FractionalPartOfX = x - (float)IntegerPartOfX;
3417 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3418 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3420 // IntegerPartOfX <<= 23;
3421 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3422 DAG.getConstant(23, TLI.getPointerTy()));
3424 if (LimitFloatPrecision <= 6) {
3425 // For floating-point precision of 6:
3427 // TwoToFractionalPartOfX =
3429 // (0.735607626f + 0.252464424f * x) * x;
3431 // error 0.0144103317, which is 6 bits
3432 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3433 getF32Constant(DAG, 0x3e814304));
3434 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3435 getF32Constant(DAG, 0x3f3c50c8));
3436 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3437 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3438 getF32Constant(DAG, 0x3f7f5e7e));
3439 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3440 SDValue TwoToFractionalPartOfX =
3441 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3443 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3444 MVT::f32, TwoToFractionalPartOfX);
3445 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3446 // For floating-point precision of 12:
3448 // TwoToFractionalPartOfX =
3451 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3453 // error 0.000107046256, which is 13 to 14 bits
3454 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3455 getF32Constant(DAG, 0x3da235e3));
3456 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3457 getF32Constant(DAG, 0x3e65b8f3));
3458 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3459 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3460 getF32Constant(DAG, 0x3f324b07));
3461 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3462 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3463 getF32Constant(DAG, 0x3f7ff8fd));
3464 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3465 SDValue TwoToFractionalPartOfX =
3466 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3468 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3469 MVT::f32, TwoToFractionalPartOfX);
3470 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3471 // For floating-point precision of 18:
3473 // TwoToFractionalPartOfX =
3477 // (0.554906021e-1f +
3478 // (0.961591928e-2f +
3479 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3480 // error 2.47208000*10^(-7), which is better than 18 bits
3481 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3482 getF32Constant(DAG, 0x3924b03e));
3483 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3484 getF32Constant(DAG, 0x3ab24b87));
3485 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3486 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3487 getF32Constant(DAG, 0x3c1d8c17));
3488 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3489 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3490 getF32Constant(DAG, 0x3d634a1d));
3491 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3492 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3493 getF32Constant(DAG, 0x3e75fe14));
3494 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3495 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3496 getF32Constant(DAG, 0x3f317234));
3497 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3498 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3499 getF32Constant(DAG, 0x3f800000));
3500 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3501 SDValue TwoToFractionalPartOfX =
3502 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3504 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3505 MVT::f32, TwoToFractionalPartOfX);
3508 // No special expansion.
3509 result = DAG.getNode(ISD::FEXP2, dl,
3510 getValue(I.getOperand(1)).getValueType(),
3511 getValue(I.getOperand(1)));
3514 setValue(&I, result);
3517 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3518 /// limited-precision mode with x == 10.0f.
3520 SelectionDAGBuilder::visitPow(CallInst &I) {
3522 Value *Val = I.getOperand(1);
3523 DebugLoc dl = getCurDebugLoc();
3524 bool IsExp10 = false;
3526 if (getValue(Val).getValueType() == MVT::f32 &&
3527 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3528 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3529 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3530 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3532 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3537 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3538 SDValue Op = getValue(I.getOperand(2));
3540 // Put the exponent in the right bit position for later addition to the
3543 // #define LOG2OF10 3.3219281f
3544 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3545 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3546 getF32Constant(DAG, 0x40549a78));
3547 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3549 // FractionalPartOfX = x - (float)IntegerPartOfX;
3550 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3551 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3553 // IntegerPartOfX <<= 23;
3554 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3555 DAG.getConstant(23, TLI.getPointerTy()));
3557 if (LimitFloatPrecision <= 6) {
3558 // For floating-point precision of 6:
3560 // twoToFractionalPartOfX =
3562 // (0.735607626f + 0.252464424f * x) * x;
3564 // error 0.0144103317, which is 6 bits
3565 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3566 getF32Constant(DAG, 0x3e814304));
3567 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3568 getF32Constant(DAG, 0x3f3c50c8));
3569 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3570 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3571 getF32Constant(DAG, 0x3f7f5e7e));
3572 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3573 SDValue TwoToFractionalPartOfX =
3574 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3576 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3577 MVT::f32, TwoToFractionalPartOfX);
3578 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3579 // For floating-point precision of 12:
3581 // TwoToFractionalPartOfX =
3584 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3586 // error 0.000107046256, which is 13 to 14 bits
3587 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3588 getF32Constant(DAG, 0x3da235e3));
3589 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3590 getF32Constant(DAG, 0x3e65b8f3));
3591 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3592 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3593 getF32Constant(DAG, 0x3f324b07));
3594 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3595 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3596 getF32Constant(DAG, 0x3f7ff8fd));
3597 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3598 SDValue TwoToFractionalPartOfX =
3599 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3601 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3602 MVT::f32, TwoToFractionalPartOfX);
3603 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3604 // For floating-point precision of 18:
3606 // TwoToFractionalPartOfX =
3610 // (0.554906021e-1f +
3611 // (0.961591928e-2f +
3612 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3613 // error 2.47208000*10^(-7), which is better than 18 bits
3614 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3615 getF32Constant(DAG, 0x3924b03e));
3616 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3617 getF32Constant(DAG, 0x3ab24b87));
3618 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3619 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3620 getF32Constant(DAG, 0x3c1d8c17));
3621 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3622 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3623 getF32Constant(DAG, 0x3d634a1d));
3624 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3625 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3626 getF32Constant(DAG, 0x3e75fe14));
3627 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3628 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3629 getF32Constant(DAG, 0x3f317234));
3630 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3631 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3632 getF32Constant(DAG, 0x3f800000));
3633 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3634 SDValue TwoToFractionalPartOfX =
3635 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3637 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3638 MVT::f32, TwoToFractionalPartOfX);
3641 // No special expansion.
3642 result = DAG.getNode(ISD::FPOW, dl,
3643 getValue(I.getOperand(1)).getValueType(),
3644 getValue(I.getOperand(1)),
3645 getValue(I.getOperand(2)));
3648 setValue(&I, result);
3652 /// ExpandPowI - Expand a llvm.powi intrinsic.
3653 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3654 SelectionDAG &DAG) {
3655 // If RHS is a constant, we can expand this out to a multiplication tree,
3656 // otherwise we end up lowering to a call to __powidf2 (for example). When
3657 // optimizing for size, we only want to do this if the expansion would produce
3658 // a small number of multiplies, otherwise we do the full expansion.
3659 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3660 // Get the exponent as a positive value.
3661 unsigned Val = RHSC->getSExtValue();
3662 if ((int)Val < 0) Val = -Val;
3664 // powi(x, 0) -> 1.0
3666 return DAG.getConstantFP(1.0, LHS.getValueType());
3668 Function *F = DAG.getMachineFunction().getFunction();
3669 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3670 // If optimizing for size, don't insert too many multiplies. This
3671 // inserts up to 5 multiplies.
3672 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3673 // We use the simple binary decomposition method to generate the multiply
3674 // sequence. There are more optimal ways to do this (for example,
3675 // powi(x,15) generates one more multiply than it should), but this has
3676 // the benefit of being both really simple and much better than a libcall.
3677 SDValue Res; // Logically starts equal to 1.0
3678 SDValue CurSquare = LHS;
3682 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3684 Res = CurSquare; // 1.0*CurSquare.
3687 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3688 CurSquare, CurSquare);
3692 // If the original was negative, invert the result, producing 1/(x*x*x).
3693 if (RHSC->getSExtValue() < 0)
3694 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3695 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3700 // Otherwise, expand to a libcall.
3701 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3705 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3706 /// we want to emit this as a call to a named external function, return the name
3707 /// otherwise lower it and return null.
3709 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3710 DebugLoc dl = getCurDebugLoc();
3713 switch (Intrinsic) {
3715 // By default, turn this into a target intrinsic node.
3716 visitTargetIntrinsic(I, Intrinsic);
3718 case Intrinsic::vastart: visitVAStart(I); return 0;
3719 case Intrinsic::vaend: visitVAEnd(I); return 0;
3720 case Intrinsic::vacopy: visitVACopy(I); return 0;
3721 case Intrinsic::returnaddress:
3722 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3723 getValue(I.getOperand(1))));
3725 case Intrinsic::frameaddress:
3726 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3727 getValue(I.getOperand(1))));
3729 case Intrinsic::setjmp:
3730 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3731 case Intrinsic::longjmp:
3732 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3733 case Intrinsic::memcpy: {
3734 // Assert for address < 256 since we support only user defined address
3736 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3738 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3740 "Unknown address space");
3741 SDValue Op1 = getValue(I.getOperand(1));
3742 SDValue Op2 = getValue(I.getOperand(2));
3743 SDValue Op3 = getValue(I.getOperand(3));
3744 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3745 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3746 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
3747 I.getOperand(1), 0, I.getOperand(2), 0));
3750 case Intrinsic::memset: {
3751 // Assert for address < 256 since we support only user defined address
3753 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3755 "Unknown address space");
3756 SDValue Op1 = getValue(I.getOperand(1));
3757 SDValue Op2 = getValue(I.getOperand(2));
3758 SDValue Op3 = getValue(I.getOperand(3));
3759 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3760 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3761 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3762 I.getOperand(1), 0));
3765 case Intrinsic::memmove: {
3766 // Assert for address < 256 since we support only user defined address
3768 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3770 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3772 "Unknown address space");
3773 SDValue Op1 = getValue(I.getOperand(1));
3774 SDValue Op2 = getValue(I.getOperand(2));
3775 SDValue Op3 = getValue(I.getOperand(3));
3776 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3777 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3779 // If the source and destination are known to not be aliases, we can
3780 // lower memmove as memcpy.
3781 uint64_t Size = -1ULL;
3782 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3783 Size = C->getZExtValue();
3784 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3785 AliasAnalysis::NoAlias) {
3786 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3787 false, I.getOperand(1), 0, I.getOperand(2), 0));
3791 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3792 I.getOperand(1), 0, I.getOperand(2), 0));
3795 case Intrinsic::dbg_declare: {
3796 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3797 // The real handling of this intrinsic is in FastISel.
3798 if (OptLevel != CodeGenOpt::None)
3799 // FIXME: Variable debug info is not supported here.
3801 DwarfWriter *DW = DAG.getDwarfWriter();
3804 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3805 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3808 MDNode *Variable = DI.getVariable();
3809 Value *Address = DI.getAddress();
3812 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3813 Address = BCI->getOperand(0);
3814 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3815 // Don't handle byval struct arguments or VLAs, for example.
3818 DenseMap<const AllocaInst*, int>::iterator SI =
3819 FuncInfo.StaticAllocaMap.find(AI);
3820 if (SI == FuncInfo.StaticAllocaMap.end())
3822 int FI = SI->second;
3824 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3825 if (MDNode *Dbg = DI.getMetadata("dbg"))
3826 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3829 case Intrinsic::dbg_value: {
3830 DwarfWriter *DW = DAG.getDwarfWriter();
3833 DbgValueInst &DI = cast<DbgValueInst>(I);
3834 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3837 MDNode *Variable = DI.getVariable();
3838 uint64_t Offset = DI.getOffset();
3839 Value *V = DI.getValue();
3843 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
3844 // but do not always have a corresponding SDNode built. The SDNodeOrder
3845 // absolute, but not relative, values are different depending on whether
3846 // debug info exists.
3848 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
3849 DAG.AddDbgValue(DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder));
3851 SDValue &N = NodeMap[V];
3853 DAG.AddDbgValue(DAG.getDbgValue(Variable, N.getNode(),
3854 N.getResNo(), Offset, dl, SDNodeOrder),
3857 // We may expand this to cover more cases. One case where we have no
3858 // data available is an unreferenced parameter; we need this fallback.
3859 DAG.AddDbgValue(DAG.getDbgValue(Variable,
3860 UndefValue::get(V->getType()),
3861 Offset, dl, SDNodeOrder));
3864 // Build a debug info table entry.
3865 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3866 V = BCI->getOperand(0);
3867 AllocaInst *AI = dyn_cast<AllocaInst>(V);
3868 // Don't handle byval struct arguments or VLAs, for example.
3871 DenseMap<const AllocaInst*, int>::iterator SI =
3872 FuncInfo.StaticAllocaMap.find(AI);
3873 if (SI == FuncInfo.StaticAllocaMap.end())
3875 int FI = SI->second;
3876 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3877 if (MDNode *Dbg = DI.getMetadata("dbg"))
3878 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3881 case Intrinsic::eh_exception: {
3882 // Insert the EXCEPTIONADDR instruction.
3883 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3884 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3886 Ops[0] = DAG.getRoot();
3887 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3889 DAG.setRoot(Op.getValue(1));
3893 case Intrinsic::eh_selector: {
3894 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3896 if (CurMBB->isLandingPad())
3897 AddCatchInfo(I, MMI, CurMBB);
3900 FuncInfo.CatchInfoLost.insert(&I);
3902 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3903 unsigned Reg = TLI.getExceptionSelectorRegister();
3904 if (Reg) CurMBB->addLiveIn(Reg);
3907 // Insert the EHSELECTION instruction.
3908 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3910 Ops[0] = getValue(I.getOperand(1));
3912 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3913 DAG.setRoot(Op.getValue(1));
3914 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
3918 case Intrinsic::eh_typeid_for: {
3919 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3922 // Find the type id for the given typeinfo.
3923 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3924 unsigned TypeID = MMI->getTypeIDFor(GV);
3925 Res = DAG.getConstant(TypeID, MVT::i32);
3927 // Return something different to eh_selector.
3928 Res = DAG.getConstant(1, MVT::i32);
3935 case Intrinsic::eh_return_i32:
3936 case Intrinsic::eh_return_i64:
3937 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3938 MMI->setCallsEHReturn(true);
3939 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3942 getValue(I.getOperand(1)),
3943 getValue(I.getOperand(2))));
3945 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3949 case Intrinsic::eh_unwind_init:
3950 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3951 MMI->setCallsUnwindInit(true);
3954 case Intrinsic::eh_dwarf_cfa: {
3955 EVT VT = getValue(I.getOperand(1)).getValueType();
3956 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3957 TLI.getPointerTy());
3958 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3960 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
3961 TLI.getPointerTy()),
3963 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
3965 DAG.getConstant(0, TLI.getPointerTy()));
3966 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3970 case Intrinsic::eh_sjlj_callsite: {
3971 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3972 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3973 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3974 assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!");
3976 MMI->setCurrentCallSite(CI->getZExtValue());
3980 case Intrinsic::convertff:
3981 case Intrinsic::convertfsi:
3982 case Intrinsic::convertfui:
3983 case Intrinsic::convertsif:
3984 case Intrinsic::convertuif:
3985 case Intrinsic::convertss:
3986 case Intrinsic::convertsu:
3987 case Intrinsic::convertus:
3988 case Intrinsic::convertuu: {
3989 ISD::CvtCode Code = ISD::CVT_INVALID;
3990 switch (Intrinsic) {
3991 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3992 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3993 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3994 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3995 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3996 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3997 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3998 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3999 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4001 EVT DestVT = TLI.getValueType(I.getType());
4002 Value *Op1 = I.getOperand(1);
4003 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4004 DAG.getValueType(DestVT),
4005 DAG.getValueType(getValue(Op1).getValueType()),
4006 getValue(I.getOperand(2)),
4007 getValue(I.getOperand(3)),
4012 case Intrinsic::sqrt:
4013 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4014 getValue(I.getOperand(1)).getValueType(),
4015 getValue(I.getOperand(1))));
4017 case Intrinsic::powi:
4018 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
4019 getValue(I.getOperand(2)), DAG));
4021 case Intrinsic::sin:
4022 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4023 getValue(I.getOperand(1)).getValueType(),
4024 getValue(I.getOperand(1))));
4026 case Intrinsic::cos:
4027 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4028 getValue(I.getOperand(1)).getValueType(),
4029 getValue(I.getOperand(1))));
4031 case Intrinsic::log:
4034 case Intrinsic::log2:
4037 case Intrinsic::log10:
4040 case Intrinsic::exp:
4043 case Intrinsic::exp2:
4046 case Intrinsic::pow:
4049 case Intrinsic::convert_to_fp16:
4050 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4051 MVT::i16, getValue(I.getOperand(1))));
4053 case Intrinsic::convert_from_fp16:
4054 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4055 MVT::f32, getValue(I.getOperand(1))));
4057 case Intrinsic::pcmarker: {
4058 SDValue Tmp = getValue(I.getOperand(1));
4059 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4062 case Intrinsic::readcyclecounter: {
4063 SDValue Op = getRoot();
4064 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4065 DAG.getVTList(MVT::i64, MVT::Other),
4068 DAG.setRoot(Res.getValue(1));
4071 case Intrinsic::bswap:
4072 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4073 getValue(I.getOperand(1)).getValueType(),
4074 getValue(I.getOperand(1))));
4076 case Intrinsic::cttz: {
4077 SDValue Arg = getValue(I.getOperand(1));
4078 EVT Ty = Arg.getValueType();
4079 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4082 case Intrinsic::ctlz: {
4083 SDValue Arg = getValue(I.getOperand(1));
4084 EVT Ty = Arg.getValueType();
4085 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4088 case Intrinsic::ctpop: {
4089 SDValue Arg = getValue(I.getOperand(1));
4090 EVT Ty = Arg.getValueType();
4091 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4094 case Intrinsic::stacksave: {
4095 SDValue Op = getRoot();
4096 Res = DAG.getNode(ISD::STACKSAVE, dl,
4097 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4099 DAG.setRoot(Res.getValue(1));
4102 case Intrinsic::stackrestore: {
4103 Res = getValue(I.getOperand(1));
4104 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4107 case Intrinsic::stackprotector: {
4108 // Emit code into the DAG to store the stack guard onto the stack.
4109 MachineFunction &MF = DAG.getMachineFunction();
4110 MachineFrameInfo *MFI = MF.getFrameInfo();
4111 EVT PtrTy = TLI.getPointerTy();
4113 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4114 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4116 int FI = FuncInfo.StaticAllocaMap[Slot];
4117 MFI->setStackProtectorIndex(FI);
4119 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4121 // Store the stack protector onto the stack.
4122 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4123 PseudoSourceValue::getFixedStack(FI),
4129 case Intrinsic::objectsize: {
4130 // If we don't know by now, we're never going to know.
4131 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4133 assert(CI && "Non-constant type in __builtin_object_size?");
4135 SDValue Arg = getValue(I.getOperand(0));
4136 EVT Ty = Arg.getValueType();
4138 if (CI->getZExtValue() == 0)
4139 Res = DAG.getConstant(-1ULL, Ty);
4141 Res = DAG.getConstant(0, Ty);
4146 case Intrinsic::var_annotation:
4147 // Discard annotate attributes
4150 case Intrinsic::init_trampoline: {
4151 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4155 Ops[1] = getValue(I.getOperand(1));
4156 Ops[2] = getValue(I.getOperand(2));
4157 Ops[3] = getValue(I.getOperand(3));
4158 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4159 Ops[5] = DAG.getSrcValue(F);
4161 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4162 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4166 DAG.setRoot(Res.getValue(1));
4169 case Intrinsic::gcroot:
4171 Value *Alloca = I.getOperand(1);
4172 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4174 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4175 GFI->addStackRoot(FI->getIndex(), TypeMap);
4178 case Intrinsic::gcread:
4179 case Intrinsic::gcwrite:
4180 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4182 case Intrinsic::flt_rounds:
4183 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4185 case Intrinsic::trap:
4186 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4188 case Intrinsic::uadd_with_overflow:
4189 return implVisitAluOverflow(I, ISD::UADDO);
4190 case Intrinsic::sadd_with_overflow:
4191 return implVisitAluOverflow(I, ISD::SADDO);
4192 case Intrinsic::usub_with_overflow:
4193 return implVisitAluOverflow(I, ISD::USUBO);
4194 case Intrinsic::ssub_with_overflow:
4195 return implVisitAluOverflow(I, ISD::SSUBO);
4196 case Intrinsic::umul_with_overflow:
4197 return implVisitAluOverflow(I, ISD::UMULO);
4198 case Intrinsic::smul_with_overflow:
4199 return implVisitAluOverflow(I, ISD::SMULO);
4201 case Intrinsic::prefetch: {
4204 Ops[1] = getValue(I.getOperand(1));
4205 Ops[2] = getValue(I.getOperand(2));
4206 Ops[3] = getValue(I.getOperand(3));
4207 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4211 case Intrinsic::memory_barrier: {
4214 for (int x = 1; x < 6; ++x)
4215 Ops[x] = getValue(I.getOperand(x));
4217 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4220 case Intrinsic::atomic_cmp_swap: {
4221 SDValue Root = getRoot();
4223 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4224 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4226 getValue(I.getOperand(1)),
4227 getValue(I.getOperand(2)),
4228 getValue(I.getOperand(3)),
4231 DAG.setRoot(L.getValue(1));
4234 case Intrinsic::atomic_load_add:
4235 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4236 case Intrinsic::atomic_load_sub:
4237 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4238 case Intrinsic::atomic_load_or:
4239 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4240 case Intrinsic::atomic_load_xor:
4241 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4242 case Intrinsic::atomic_load_and:
4243 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4244 case Intrinsic::atomic_load_nand:
4245 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4246 case Intrinsic::atomic_load_max:
4247 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4248 case Intrinsic::atomic_load_min:
4249 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4250 case Intrinsic::atomic_load_umin:
4251 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4252 case Intrinsic::atomic_load_umax:
4253 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4254 case Intrinsic::atomic_swap:
4255 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4257 case Intrinsic::invariant_start:
4258 case Intrinsic::lifetime_start:
4259 // Discard region information.
4260 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4262 case Intrinsic::invariant_end:
4263 case Intrinsic::lifetime_end:
4264 // Discard region information.
4269 /// Test if the given instruction is in a position to be optimized
4270 /// with a tail-call. This roughly means that it's in a block with
4271 /// a return and there's nothing that needs to be scheduled
4272 /// between it and the return.
4274 /// This function only tests target-independent requirements.
4276 isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
4277 const TargetLowering &TLI) {
4278 const Instruction *I = CS.getInstruction();
4279 const BasicBlock *ExitBB = I->getParent();
4280 const TerminatorInst *Term = ExitBB->getTerminator();
4281 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4282 const Function *F = ExitBB->getParent();
4284 // The block must end in a return statement or unreachable.
4286 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4287 // an unreachable, for now. The way tailcall optimization is currently
4288 // implemented means it will add an epilogue followed by a jump. That is
4289 // not profitable. Also, if the callee is a special function (e.g.
4290 // longjmp on x86), it can end up causing miscompilation that has not
4291 // been fully understood.
4293 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
4295 // If I will have a chain, make sure no other instruction that will have a
4296 // chain interposes between I and the return.
4297 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4298 !I->isSafeToSpeculativelyExecute())
4299 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4303 // Debug info intrinsics do not get in the way of tail call optimization.
4304 if (isa<DbgInfoIntrinsic>(BBI))
4306 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4307 !BBI->isSafeToSpeculativelyExecute())
4311 // If the block ends with a void return or unreachable, it doesn't matter
4312 // what the call's return type is.
4313 if (!Ret || Ret->getNumOperands() == 0) return true;
4315 // If the return value is undef, it doesn't matter what the call's
4317 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4319 // Conservatively require the attributes of the call to match those of
4320 // the return. Ignore noalias because it doesn't affect the call sequence.
4321 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4322 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4325 // It's not safe to eliminate the sign / zero extension of the return value.
4326 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4329 // Otherwise, make sure the unmodified return value of I is the return value.
4330 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4331 U = dyn_cast<Instruction>(U->getOperand(0))) {
4334 if (!U->hasOneUse())
4338 // Check for a truly no-op truncate.
4339 if (isa<TruncInst>(U) &&
4340 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4342 // Check for a truly no-op bitcast.
4343 if (isa<BitCastInst>(U) &&
4344 (U->getOperand(0)->getType() == U->getType() ||
4345 (U->getOperand(0)->getType()->isPointerTy() &&
4346 U->getType()->isPointerTy())))
4348 // Otherwise it's not a true no-op.
4355 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4357 MachineBasicBlock *LandingPad) {
4358 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4359 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4360 const Type *RetTy = FTy->getReturnType();
4361 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4362 MCSymbol *BeginLabel = 0;
4364 TargetLowering::ArgListTy Args;
4365 TargetLowering::ArgListEntry Entry;
4366 Args.reserve(CS.arg_size());
4368 // Check whether the function can return without sret-demotion.
4369 SmallVector<EVT, 4> OutVTs;
4370 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4371 SmallVector<uint64_t, 4> Offsets;
4372 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4373 OutVTs, OutsFlags, TLI, &Offsets);
4375 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4376 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4378 SDValue DemoteStackSlot;
4380 if (!CanLowerReturn) {
4381 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4382 FTy->getReturnType());
4383 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4384 FTy->getReturnType());
4385 MachineFunction &MF = DAG.getMachineFunction();
4386 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4387 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4389 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4390 Entry.Node = DemoteStackSlot;
4391 Entry.Ty = StackSlotPtrType;
4392 Entry.isSExt = false;
4393 Entry.isZExt = false;
4394 Entry.isInReg = false;
4395 Entry.isSRet = true;
4396 Entry.isNest = false;
4397 Entry.isByVal = false;
4398 Entry.Alignment = Align;
4399 Args.push_back(Entry);
4400 RetTy = Type::getVoidTy(FTy->getContext());
4403 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4405 SDValue ArgNode = getValue(*i);
4406 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4408 unsigned attrInd = i - CS.arg_begin() + 1;
4409 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4410 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4411 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4412 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4413 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4414 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4415 Entry.Alignment = CS.getParamAlignment(attrInd);
4416 Args.push_back(Entry);
4419 if (LandingPad && MMI) {
4420 // Insert a label before the invoke call to mark the try range. This can be
4421 // used to detect deletion of the invoke via the MachineModuleInfo.
4422 BeginLabel = MMI->getContext().CreateTempSymbol();
4424 // For SjLj, keep track of which landing pads go with which invokes
4425 // so as to maintain the ordering of pads in the LSDA.
4426 unsigned CallSiteIndex = MMI->getCurrentCallSite();
4427 if (CallSiteIndex) {
4428 MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4429 // Now that the call site is handled, stop tracking it.
4430 MMI->setCurrentCallSite(0);
4433 // Both PendingLoads and PendingExports must be flushed here;
4434 // this call might not return.
4436 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4439 // Check if target-independent constraints permit a tail call here.
4440 // Target-dependent constraints are checked within TLI.LowerCallTo.
4442 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4445 std::pair<SDValue,SDValue> Result =
4446 TLI.LowerCallTo(getRoot(), RetTy,
4447 CS.paramHasAttr(0, Attribute::SExt),
4448 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4449 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4450 CS.getCallingConv(),
4452 !CS.getInstruction()->use_empty(),
4453 Callee, Args, DAG, getCurDebugLoc());
4454 assert((isTailCall || Result.second.getNode()) &&
4455 "Non-null chain expected with non-tail call!");
4456 assert((Result.second.getNode() || !Result.first.getNode()) &&
4457 "Null value expected with tail call!");
4458 if (Result.first.getNode()) {
4459 setValue(CS.getInstruction(), Result.first);
4460 } else if (!CanLowerReturn && Result.second.getNode()) {
4461 // The instruction result is the result of loading from the
4462 // hidden sret parameter.
4463 SmallVector<EVT, 1> PVTs;
4464 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4466 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4467 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4468 EVT PtrVT = PVTs[0];
4469 unsigned NumValues = OutVTs.size();
4470 SmallVector<SDValue, 4> Values(NumValues);
4471 SmallVector<SDValue, 4> Chains(NumValues);
4473 for (unsigned i = 0; i < NumValues; ++i) {
4474 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4476 DAG.getConstant(Offsets[i], PtrVT));
4477 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4478 Add, NULL, Offsets[i], false, false, 1);
4480 Chains[i] = L.getValue(1);
4483 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4484 MVT::Other, &Chains[0], NumValues);
4485 PendingLoads.push_back(Chain);
4487 // Collect the legal value parts into potentially illegal values
4488 // that correspond to the original function's return values.
4489 SmallVector<EVT, 4> RetTys;
4490 RetTy = FTy->getReturnType();
4491 ComputeValueVTs(TLI, RetTy, RetTys);
4492 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4493 SmallVector<SDValue, 4> ReturnValues;
4494 unsigned CurReg = 0;
4495 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4497 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4498 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4500 SDValue ReturnValue =
4501 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
4502 RegisterVT, VT, AssertOp);
4503 ReturnValues.push_back(ReturnValue);
4507 setValue(CS.getInstruction(),
4508 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4509 DAG.getVTList(&RetTys[0], RetTys.size()),
4510 &ReturnValues[0], ReturnValues.size()));
4514 // As a special case, a null chain means that a tail call has been emitted and
4515 // the DAG root is already updated.
4516 if (Result.second.getNode())
4517 DAG.setRoot(Result.second);
4521 if (LandingPad && MMI) {
4522 // Insert a label at the end of the invoke call to mark the try range. This
4523 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4524 MCSymbol *EndLabel = MMI->getContext().CreateTempSymbol();
4525 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
4527 // Inform MachineModuleInfo of range.
4528 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4532 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4533 /// value is equal or not-equal to zero.
4534 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
4535 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
4537 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4538 if (IC->isEquality())
4539 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4540 if (C->isNullValue())
4542 // Unknown instruction.
4548 static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
4549 SelectionDAGBuilder &Builder) {
4551 // Check to see if this load can be trivially constant folded, e.g. if the
4552 // input is from a string literal.
4553 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4554 // Cast pointer to the type we really want to load.
4555 LoadInput = ConstantExpr::getBitCast(LoadInput,
4556 PointerType::getUnqual(LoadTy));
4558 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
4559 return Builder.getValue(LoadCst);
4562 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4563 // still constant memory, the input chain can be the entry node.
4565 bool ConstantMemory = false;
4567 // Do not serialize (non-volatile) loads of constant memory with anything.
4568 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4569 Root = Builder.DAG.getEntryNode();
4570 ConstantMemory = true;
4572 // Do not serialize non-volatile loads against each other.
4573 Root = Builder.DAG.getRoot();
4576 SDValue Ptr = Builder.getValue(PtrVal);
4577 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4578 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4580 false /*nontemporal*/, 1 /* align=1 */);
4582 if (!ConstantMemory)
4583 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4588 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4589 /// If so, return true and lower it, otherwise return false and it will be
4590 /// lowered like a normal call.
4591 bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
4592 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4593 if (I.getNumOperands() != 4)
4596 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
4597 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
4598 !I.getOperand(3)->getType()->isIntegerTy() ||
4599 !I.getType()->isIntegerTy())
4602 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
4604 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4605 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
4606 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4607 bool ActuallyDoIt = true;
4610 switch (Size->getZExtValue()) {
4612 LoadVT = MVT::Other;
4614 ActuallyDoIt = false;
4618 LoadTy = Type::getInt16Ty(Size->getContext());
4622 LoadTy = Type::getInt32Ty(Size->getContext());
4626 LoadTy = Type::getInt64Ty(Size->getContext());
4630 LoadVT = MVT::v4i32;
4631 LoadTy = Type::getInt32Ty(Size->getContext());
4632 LoadTy = VectorType::get(LoadTy, 4);
4637 // This turns into unaligned loads. We only do this if the target natively
4638 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4639 // we'll only produce a small number of byte loads.
4641 // Require that we can find a legal MVT, and only do this if the target
4642 // supports unaligned loads of that type. Expanding into byte loads would
4644 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4645 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4646 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4647 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4648 ActuallyDoIt = false;
4652 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4653 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
4655 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4657 EVT CallVT = TLI.getValueType(I.getType(), true);
4658 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4668 void SelectionDAGBuilder::visitCall(CallInst &I) {
4669 const char *RenameFn = 0;
4670 if (Function *F = I.getCalledFunction()) {
4671 if (F->isDeclaration()) {
4672 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4674 if (unsigned IID = II->getIntrinsicID(F)) {
4675 RenameFn = visitIntrinsicCall(I, IID);
4680 if (unsigned IID = F->getIntrinsicID()) {
4681 RenameFn = visitIntrinsicCall(I, IID);
4687 // Check for well-known libc/libm calls. If the function is internal, it
4688 // can't be a library call.
4689 if (!F->hasLocalLinkage() && F->hasName()) {
4690 StringRef Name = F->getName();
4691 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
4692 if (I.getNumOperands() == 3 && // Basic sanity checks.
4693 I.getOperand(1)->getType()->isFloatingPointTy() &&
4694 I.getType() == I.getOperand(1)->getType() &&
4695 I.getType() == I.getOperand(2)->getType()) {
4696 SDValue LHS = getValue(I.getOperand(1));
4697 SDValue RHS = getValue(I.getOperand(2));
4698 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4699 LHS.getValueType(), LHS, RHS));
4702 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4703 if (I.getNumOperands() == 2 && // Basic sanity checks.
4704 I.getOperand(1)->getType()->isFloatingPointTy() &&
4705 I.getType() == I.getOperand(1)->getType()) {
4706 SDValue Tmp = getValue(I.getOperand(1));
4707 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4708 Tmp.getValueType(), Tmp));
4711 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4712 if (I.getNumOperands() == 2 && // Basic sanity checks.
4713 I.getOperand(1)->getType()->isFloatingPointTy() &&
4714 I.getType() == I.getOperand(1)->getType() &&
4715 I.onlyReadsMemory()) {
4716 SDValue Tmp = getValue(I.getOperand(1));
4717 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4718 Tmp.getValueType(), Tmp));
4721 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4722 if (I.getNumOperands() == 2 && // Basic sanity checks.
4723 I.getOperand(1)->getType()->isFloatingPointTy() &&
4724 I.getType() == I.getOperand(1)->getType() &&
4725 I.onlyReadsMemory()) {
4726 SDValue Tmp = getValue(I.getOperand(1));
4727 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4728 Tmp.getValueType(), Tmp));
4731 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4732 if (I.getNumOperands() == 2 && // Basic sanity checks.
4733 I.getOperand(1)->getType()->isFloatingPointTy() &&
4734 I.getType() == I.getOperand(1)->getType() &&
4735 I.onlyReadsMemory()) {
4736 SDValue Tmp = getValue(I.getOperand(1));
4737 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4738 Tmp.getValueType(), Tmp));
4741 } else if (Name == "memcmp") {
4742 if (visitMemCmpCall(I))
4746 } else if (isa<InlineAsm>(I.getOperand(0))) {
4753 Callee = getValue(I.getOperand(0));
4755 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4757 // Check if we can potentially perform a tail call. More detailed checking is
4758 // be done within LowerCallTo, after more information about the call is known.
4759 LowerCallTo(&I, Callee, I.isTailCall());
4762 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4763 /// this value and returns the result as a ValueVT value. This uses
4764 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4765 /// If the Flag pointer is NULL, no flag is used.
4766 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4767 SDValue &Chain, SDValue *Flag) const {
4768 // Assemble the legal parts into the final values.
4769 SmallVector<SDValue, 4> Values(ValueVTs.size());
4770 SmallVector<SDValue, 8> Parts;
4771 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4772 // Copy the legal parts from the registers.
4773 EVT ValueVT = ValueVTs[Value];
4774 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4775 EVT RegisterVT = RegVTs[Value];
4777 Parts.resize(NumRegs);
4778 for (unsigned i = 0; i != NumRegs; ++i) {
4781 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4783 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4784 *Flag = P.getValue(2);
4787 Chain = P.getValue(1);
4789 // If the source register was virtual and if we know something about it,
4790 // add an assert node.
4791 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4792 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4793 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4794 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4795 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4796 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4798 unsigned RegSize = RegisterVT.getSizeInBits();
4799 unsigned NumSignBits = LOI.NumSignBits;
4800 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4802 // FIXME: We capture more information than the dag can represent. For
4803 // now, just use the tightest assertzext/assertsext possible.
4805 EVT FromVT(MVT::Other);
4806 if (NumSignBits == RegSize)
4807 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4808 else if (NumZeroBits >= RegSize-1)
4809 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4810 else if (NumSignBits > RegSize-8)
4811 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4812 else if (NumZeroBits >= RegSize-8)
4813 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4814 else if (NumSignBits > RegSize-16)
4815 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4816 else if (NumZeroBits >= RegSize-16)
4817 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4818 else if (NumSignBits > RegSize-32)
4819 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4820 else if (NumZeroBits >= RegSize-32)
4821 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4823 if (FromVT != MVT::Other)
4824 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4825 RegisterVT, P, DAG.getValueType(FromVT));
4832 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4833 NumRegs, RegisterVT, ValueVT);
4838 return DAG.getNode(ISD::MERGE_VALUES, dl,
4839 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4840 &Values[0], ValueVTs.size());
4843 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4844 /// specified value into the registers specified by this object. This uses
4845 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4846 /// If the Flag pointer is NULL, no flag is used.
4847 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4848 SDValue &Chain, SDValue *Flag) const {
4849 // Get the list of the values's legal parts.
4850 unsigned NumRegs = Regs.size();
4851 SmallVector<SDValue, 8> Parts(NumRegs);
4852 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4853 EVT ValueVT = ValueVTs[Value];
4854 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4855 EVT RegisterVT = RegVTs[Value];
4857 getCopyToParts(DAG, dl,
4858 Val.getValue(Val.getResNo() + Value),
4859 &Parts[Part], NumParts, RegisterVT);
4863 // Copy the parts into the registers.
4864 SmallVector<SDValue, 8> Chains(NumRegs);
4865 for (unsigned i = 0; i != NumRegs; ++i) {
4868 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4870 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4871 *Flag = Part.getValue(1);
4874 Chains[i] = Part.getValue(0);
4877 if (NumRegs == 1 || Flag)
4878 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4879 // flagged to it. That is the CopyToReg nodes and the user are considered
4880 // a single scheduling unit. If we create a TokenFactor and return it as
4881 // chain, then the TokenFactor is both a predecessor (operand) of the
4882 // user as well as a successor (the TF operands are flagged to the user).
4883 // c1, f1 = CopyToReg
4884 // c2, f2 = CopyToReg
4885 // c3 = TokenFactor c1, c2
4888 Chain = Chains[NumRegs-1];
4890 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4893 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4894 /// operand list. This adds the code marker and includes the number of
4895 /// values added into it.
4896 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4897 bool HasMatching,unsigned MatchingIdx,
4899 std::vector<SDValue> &Ops) const {
4900 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4901 unsigned Flag = Code | (Regs.size() << 3);
4903 Flag |= 0x80000000 | (MatchingIdx << 16);
4904 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
4907 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4908 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4909 EVT RegisterVT = RegVTs[Value];
4910 for (unsigned i = 0; i != NumRegs; ++i) {
4911 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4912 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4917 /// isAllocatableRegister - If the specified register is safe to allocate,
4918 /// i.e. it isn't a stack pointer or some other special register, return the
4919 /// register class for the register. Otherwise, return null.
4920 static const TargetRegisterClass *
4921 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4922 const TargetLowering &TLI,
4923 const TargetRegisterInfo *TRI) {
4924 EVT FoundVT = MVT::Other;
4925 const TargetRegisterClass *FoundRC = 0;
4926 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4927 E = TRI->regclass_end(); RCI != E; ++RCI) {
4928 EVT ThisVT = MVT::Other;
4930 const TargetRegisterClass *RC = *RCI;
4931 // If none of the value types for this register class are valid, we
4932 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4933 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4935 if (TLI.isTypeLegal(*I)) {
4936 // If we have already found this register in a different register class,
4937 // choose the one with the largest VT specified. For example, on
4938 // PowerPC, we favor f64 register classes over f32.
4939 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4946 if (ThisVT == MVT::Other) continue;
4948 // NOTE: This isn't ideal. In particular, this might allocate the
4949 // frame pointer in functions that need it (due to them not being taken
4950 // out of allocation, because a variable sized allocation hasn't been seen
4951 // yet). This is a slight code pessimization, but should still work.
4952 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4953 E = RC->allocation_order_end(MF); I != E; ++I)
4955 // We found a matching register class. Keep looking at others in case
4956 // we find one with larger registers that this physreg is also in.
4967 /// AsmOperandInfo - This contains information for each constraint that we are
4969 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4970 public TargetLowering::AsmOperandInfo {
4972 /// CallOperand - If this is the result output operand or a clobber
4973 /// this is null, otherwise it is the incoming operand to the CallInst.
4974 /// This gets modified as the asm is processed.
4975 SDValue CallOperand;
4977 /// AssignedRegs - If this is a register or register class operand, this
4978 /// contains the set of register corresponding to the operand.
4979 RegsForValue AssignedRegs;
4981 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4982 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4985 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4986 /// busy in OutputRegs/InputRegs.
4987 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4988 std::set<unsigned> &OutputRegs,
4989 std::set<unsigned> &InputRegs,
4990 const TargetRegisterInfo &TRI) const {
4992 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4993 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4996 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4997 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5001 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5002 /// corresponds to. If there is no Value* for this operand, it returns
5004 EVT getCallOperandValEVT(LLVMContext &Context,
5005 const TargetLowering &TLI,
5006 const TargetData *TD) const {
5007 if (CallOperandVal == 0) return MVT::Other;
5009 if (isa<BasicBlock>(CallOperandVal))
5010 return TLI.getPointerTy();
5012 const llvm::Type *OpTy = CallOperandVal->getType();
5014 // If this is an indirect operand, the operand is a pointer to the
5017 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5019 llvm_report_error("Indirect operand for inline asm not a pointer!");
5020 OpTy = PtrTy->getElementType();
5023 // If OpTy is not a single value, it may be a struct/union that we
5024 // can tile with integers.
5025 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5026 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5035 OpTy = IntegerType::get(Context, BitSize);
5040 return TLI.getValueType(OpTy, true);
5044 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5046 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5047 const TargetRegisterInfo &TRI) {
5048 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5050 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5051 for (; *Aliases; ++Aliases)
5052 Regs.insert(*Aliases);
5055 } // end llvm namespace.
5058 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5059 /// specified operand. We prefer to assign virtual registers, to allow the
5060 /// register allocator to handle the assignment process. However, if the asm
5061 /// uses features that we can't model on machineinstrs, we have SDISel do the
5062 /// allocation. This produces generally horrible, but correct, code.
5064 /// OpInfo describes the operand.
5065 /// Input and OutputRegs are the set of already allocated physical registers.
5067 void SelectionDAGBuilder::
5068 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5069 std::set<unsigned> &OutputRegs,
5070 std::set<unsigned> &InputRegs) {
5071 LLVMContext &Context = FuncInfo.Fn->getContext();
5073 // Compute whether this value requires an input register, an output register,
5075 bool isOutReg = false;
5076 bool isInReg = false;
5077 switch (OpInfo.Type) {
5078 case InlineAsm::isOutput:
5081 // If there is an input constraint that matches this, we need to reserve
5082 // the input register so no other inputs allocate to it.
5083 isInReg = OpInfo.hasMatchingInput();
5085 case InlineAsm::isInput:
5089 case InlineAsm::isClobber:
5096 MachineFunction &MF = DAG.getMachineFunction();
5097 SmallVector<unsigned, 4> Regs;
5099 // If this is a constraint for a single physreg, or a constraint for a
5100 // register class, find it.
5101 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5102 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5103 OpInfo.ConstraintVT);
5105 unsigned NumRegs = 1;
5106 if (OpInfo.ConstraintVT != MVT::Other) {
5107 // If this is a FP input in an integer register (or visa versa) insert a bit
5108 // cast of the input value. More generally, handle any case where the input
5109 // value disagrees with the register class we plan to stick this in.
5110 if (OpInfo.Type == InlineAsm::isInput &&
5111 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5112 // Try to convert to the first EVT that the reg class contains. If the
5113 // types are identical size, use a bitcast to convert (e.g. two differing
5115 EVT RegVT = *PhysReg.second->vt_begin();
5116 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5117 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5118 RegVT, OpInfo.CallOperand);
5119 OpInfo.ConstraintVT = RegVT;
5120 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5121 // If the input is a FP value and we want it in FP registers, do a
5122 // bitcast to the corresponding integer type. This turns an f64 value
5123 // into i64, which can be passed with two i32 values on a 32-bit
5125 RegVT = EVT::getIntegerVT(Context,
5126 OpInfo.ConstraintVT.getSizeInBits());
5127 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5128 RegVT, OpInfo.CallOperand);
5129 OpInfo.ConstraintVT = RegVT;
5133 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5137 EVT ValueVT = OpInfo.ConstraintVT;
5139 // If this is a constraint for a specific physical register, like {r17},
5141 if (unsigned AssignedReg = PhysReg.first) {
5142 const TargetRegisterClass *RC = PhysReg.second;
5143 if (OpInfo.ConstraintVT == MVT::Other)
5144 ValueVT = *RC->vt_begin();
5146 // Get the actual register value type. This is important, because the user
5147 // may have asked for (e.g.) the AX register in i32 type. We need to
5148 // remember that AX is actually i16 to get the right extension.
5149 RegVT = *RC->vt_begin();
5151 // This is a explicit reference to a physical register.
5152 Regs.push_back(AssignedReg);
5154 // If this is an expanded reference, add the rest of the regs to Regs.
5156 TargetRegisterClass::iterator I = RC->begin();
5157 for (; *I != AssignedReg; ++I)
5158 assert(I != RC->end() && "Didn't find reg!");
5160 // Already added the first reg.
5162 for (; NumRegs; --NumRegs, ++I) {
5163 assert(I != RC->end() && "Ran out of registers to allocate!");
5168 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5169 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5170 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5174 // Otherwise, if this was a reference to an LLVM register class, create vregs
5175 // for this reference.
5176 if (const TargetRegisterClass *RC = PhysReg.second) {
5177 RegVT = *RC->vt_begin();
5178 if (OpInfo.ConstraintVT == MVT::Other)
5181 // Create the appropriate number of virtual registers.
5182 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5183 for (; NumRegs; --NumRegs)
5184 Regs.push_back(RegInfo.createVirtualRegister(RC));
5186 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5190 // This is a reference to a register class that doesn't directly correspond
5191 // to an LLVM register class. Allocate NumRegs consecutive, available,
5192 // registers from the class.
5193 std::vector<unsigned> RegClassRegs
5194 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5195 OpInfo.ConstraintVT);
5197 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5198 unsigned NumAllocated = 0;
5199 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5200 unsigned Reg = RegClassRegs[i];
5201 // See if this register is available.
5202 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5203 (isInReg && InputRegs.count(Reg))) { // Already used.
5204 // Make sure we find consecutive registers.
5209 // Check to see if this register is allocatable (i.e. don't give out the
5211 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5212 if (!RC) { // Couldn't allocate this register.
5213 // Reset NumAllocated to make sure we return consecutive registers.
5218 // Okay, this register is good, we can use it.
5221 // If we allocated enough consecutive registers, succeed.
5222 if (NumAllocated == NumRegs) {
5223 unsigned RegStart = (i-NumAllocated)+1;
5224 unsigned RegEnd = i+1;
5225 // Mark all of the allocated registers used.
5226 for (unsigned i = RegStart; i != RegEnd; ++i)
5227 Regs.push_back(RegClassRegs[i]);
5229 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5230 OpInfo.ConstraintVT);
5231 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5236 // Otherwise, we couldn't allocate enough registers for this.
5239 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5240 /// processed uses a memory 'm' constraint.
5242 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5243 const TargetLowering &TLI) {
5244 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5245 InlineAsm::ConstraintInfo &CI = CInfos[i];
5246 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5247 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5248 if (CType == TargetLowering::C_Memory)
5252 // Indirect operand accesses access memory.
5260 /// visitInlineAsm - Handle a call to an InlineAsm object.
5262 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
5263 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5265 /// ConstraintOperands - Information about all of the constraints.
5266 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5268 std::set<unsigned> OutputRegs, InputRegs;
5270 // Do a prepass over the constraints, canonicalizing them, and building up the
5271 // ConstraintOperands list.
5272 std::vector<InlineAsm::ConstraintInfo>
5273 ConstraintInfos = IA->ParseConstraints();
5275 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5277 SDValue Chain, Flag;
5279 // We won't need to flush pending loads if this asm doesn't touch
5280 // memory and is nonvolatile.
5281 if (hasMemory || IA->hasSideEffects())
5284 Chain = DAG.getRoot();
5286 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5287 unsigned ResNo = 0; // ResNo - The result number of the next output.
5288 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5289 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5290 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5292 EVT OpVT = MVT::Other;
5294 // Compute the value type for each operand.
5295 switch (OpInfo.Type) {
5296 case InlineAsm::isOutput:
5297 // Indirect outputs just consume an argument.
5298 if (OpInfo.isIndirect) {
5299 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5303 // The return value of the call is this value. As such, there is no
5304 // corresponding argument.
5305 assert(!CS.getType()->isVoidTy() &&
5307 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5308 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5310 assert(ResNo == 0 && "Asm only has one result!");
5311 OpVT = TLI.getValueType(CS.getType());
5315 case InlineAsm::isInput:
5316 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5318 case InlineAsm::isClobber:
5323 // If this is an input or an indirect output, process the call argument.
5324 // BasicBlocks are labels, currently appearing only in asm's.
5325 if (OpInfo.CallOperandVal) {
5326 // Strip bitcasts, if any. This mostly comes up for functions.
5327 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5329 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5330 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5332 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5335 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5338 OpInfo.ConstraintVT = OpVT;
5341 // Second pass over the constraints: compute which constraint option to use
5342 // and assign registers to constraints that want a specific physreg.
5343 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5344 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5346 // If this is an output operand with a matching input operand, look up the
5347 // matching input. If their types mismatch, e.g. one is an integer, the
5348 // other is floating point, or their sizes are different, flag it as an
5350 if (OpInfo.hasMatchingInput()) {
5351 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5352 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5353 if ((OpInfo.ConstraintVT.isInteger() !=
5354 Input.ConstraintVT.isInteger()) ||
5355 (OpInfo.ConstraintVT.getSizeInBits() !=
5356 Input.ConstraintVT.getSizeInBits())) {
5357 llvm_report_error("Unsupported asm: input constraint"
5358 " with a matching output constraint of incompatible"
5361 Input.ConstraintVT = OpInfo.ConstraintVT;
5365 // Compute the constraint code and ConstraintType to use.
5366 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5368 // If this is a memory input, and if the operand is not indirect, do what we
5369 // need to to provide an address for the memory input.
5370 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5371 !OpInfo.isIndirect) {
5372 assert(OpInfo.Type == InlineAsm::isInput &&
5373 "Can only indirectify direct input operands!");
5375 // Memory operands really want the address of the value. If we don't have
5376 // an indirect input, put it in the constpool if we can, otherwise spill
5377 // it to a stack slot.
5379 // If the operand is a float, integer, or vector constant, spill to a
5380 // constant pool entry to get its address.
5381 Value *OpVal = OpInfo.CallOperandVal;
5382 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5383 isa<ConstantVector>(OpVal)) {
5384 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5385 TLI.getPointerTy());
5387 // Otherwise, create a stack slot and emit a store to it before the
5389 const Type *Ty = OpVal->getType();
5390 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5391 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5392 MachineFunction &MF = DAG.getMachineFunction();
5393 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5394 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5395 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5396 OpInfo.CallOperand, StackSlot, NULL, 0,
5398 OpInfo.CallOperand = StackSlot;
5401 // There is no longer a Value* corresponding to this operand.
5402 OpInfo.CallOperandVal = 0;
5404 // It is now an indirect operand.
5405 OpInfo.isIndirect = true;
5408 // If this constraint is for a specific register, allocate it before
5410 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5411 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5414 ConstraintInfos.clear();
5416 // Second pass - Loop over all of the operands, assigning virtual or physregs
5417 // to register class operands.
5418 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5419 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5421 // C_Register operands have already been allocated, Other/Memory don't need
5423 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5424 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5427 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5428 std::vector<SDValue> AsmNodeOperands;
5429 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5430 AsmNodeOperands.push_back(
5431 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5432 TLI.getPointerTy()));
5435 // Loop over all of the inputs, copying the operand values into the
5436 // appropriate registers and processing the output regs.
5437 RegsForValue RetValRegs;
5439 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5440 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5442 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5443 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5445 switch (OpInfo.Type) {
5446 case InlineAsm::isOutput: {
5447 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5448 OpInfo.ConstraintType != TargetLowering::C_Register) {
5449 // Memory output, or 'other' output (e.g. 'X' constraint).
5450 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5452 // Add information to the INLINEASM node to know about this output.
5453 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5454 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5455 TLI.getPointerTy()));
5456 AsmNodeOperands.push_back(OpInfo.CallOperand);
5460 // Otherwise, this is a register or register class output.
5462 // Copy the output from the appropriate register. Find a register that
5464 if (OpInfo.AssignedRegs.Regs.empty()) {
5465 llvm_report_error("Couldn't allocate output reg for"
5466 " constraint '" + OpInfo.ConstraintCode + "'!");
5469 // If this is an indirect operand, store through the pointer after the
5471 if (OpInfo.isIndirect) {
5472 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5473 OpInfo.CallOperandVal));
5475 // This is the result value of the call.
5476 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5477 // Concatenate this output onto the outputs list.
5478 RetValRegs.append(OpInfo.AssignedRegs);
5481 // Add information to the INLINEASM node to know that this register is
5483 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5484 6 /* EARLYCLOBBER REGDEF */ :
5492 case InlineAsm::isInput: {
5493 SDValue InOperandVal = OpInfo.CallOperand;
5495 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5496 // If this is required to match an output register we have already set,
5497 // just use its register.
5498 unsigned OperandNo = OpInfo.getMatchedOperand();
5500 // Scan until we find the definition we already emitted of this operand.
5501 // When we find it, create a RegsForValue operand.
5502 unsigned CurOp = 2; // The first operand.
5503 for (; OperandNo; --OperandNo) {
5504 // Advance to the next operand.
5506 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5507 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5508 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5509 (OpFlag & 7) == 4 /*MEM*/) &&
5510 "Skipped past definitions?");
5511 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5515 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5516 if ((OpFlag & 7) == 2 /*REGDEF*/
5517 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5518 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5519 if (OpInfo.isIndirect) {
5520 llvm_report_error("Don't know how to handle tied indirect "
5521 "register inputs yet!");
5523 RegsForValue MatchedRegs;
5524 MatchedRegs.TLI = &TLI;
5525 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5526 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5527 MatchedRegs.RegVTs.push_back(RegVT);
5528 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5529 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5531 MatchedRegs.Regs.push_back
5532 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5534 // Use the produced MatchedRegs object to
5535 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5537 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5538 true, OpInfo.getMatchedOperand(),
5539 DAG, AsmNodeOperands);
5542 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5543 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5544 "Unexpected number of operands");
5545 // Add information to the INLINEASM node to know about this input.
5546 // See InlineAsm.h isUseOperandTiedToDef.
5547 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5548 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5549 TLI.getPointerTy()));
5550 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5555 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5556 assert(!OpInfo.isIndirect &&
5557 "Don't know how to handle indirect other inputs yet!");
5559 std::vector<SDValue> Ops;
5560 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5561 hasMemory, Ops, DAG);
5563 llvm_report_error("Invalid operand for inline asm"
5564 " constraint '" + OpInfo.ConstraintCode + "'!");
5567 // Add information to the INLINEASM node to know about this input.
5568 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5569 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5570 TLI.getPointerTy()));
5571 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5573 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5574 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5575 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5576 "Memory operands expect pointer values");
5578 // Add information to the INLINEASM node to know about this input.
5579 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5580 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5581 TLI.getPointerTy()));
5582 AsmNodeOperands.push_back(InOperandVal);
5586 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5587 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5588 "Unknown constraint type!");
5589 assert(!OpInfo.isIndirect &&
5590 "Don't know how to handle indirect register inputs yet!");
5592 // Copy the input into the appropriate registers.
5593 if (OpInfo.AssignedRegs.Regs.empty() ||
5594 !OpInfo.AssignedRegs.areValueTypesLegal()) {
5595 llvm_report_error("Couldn't allocate input reg for"
5596 " constraint '"+ OpInfo.ConstraintCode +"'!");
5599 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5602 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5603 DAG, AsmNodeOperands);
5606 case InlineAsm::isClobber: {
5607 // Add the clobbered value to the operand list, so that the register
5608 // allocator is aware that the physreg got clobbered.
5609 if (!OpInfo.AssignedRegs.Regs.empty())
5610 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5618 // Finish up input operands.
5619 AsmNodeOperands[0] = Chain;
5620 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5622 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5623 DAG.getVTList(MVT::Other, MVT::Flag),
5624 &AsmNodeOperands[0], AsmNodeOperands.size());
5625 Flag = Chain.getValue(1);
5627 // If this asm returns a register value, copy the result from that register
5628 // and set it as the value of the call.
5629 if (!RetValRegs.Regs.empty()) {
5630 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5633 // FIXME: Why don't we do this for inline asms with MRVs?
5634 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5635 EVT ResultType = TLI.getValueType(CS.getType());
5637 // If any of the results of the inline asm is a vector, it may have the
5638 // wrong width/num elts. This can happen for register classes that can
5639 // contain multiple different value types. The preg or vreg allocated may
5640 // not have the same VT as was expected. Convert it to the right type
5641 // with bit_convert.
5642 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5643 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5646 } else if (ResultType != Val.getValueType() &&
5647 ResultType.isInteger() && Val.getValueType().isInteger()) {
5648 // If a result value was tied to an input value, the computed result may
5649 // have a wider width than the expected result. Extract the relevant
5651 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5654 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5657 setValue(CS.getInstruction(), Val);
5658 // Don't need to use this as a chain in this case.
5659 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5663 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5665 // Process indirect outputs, first output all of the flagged copies out of
5667 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5668 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5669 Value *Ptr = IndirectStoresToEmit[i].second;
5670 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5672 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5676 // Emit the non-flagged stores from the physregs.
5677 SmallVector<SDValue, 8> OutChains;
5678 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5679 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5680 StoresToEmit[i].first,
5681 getValue(StoresToEmit[i].second),
5682 StoresToEmit[i].second, 0,
5684 OutChains.push_back(Val);
5687 if (!OutChains.empty())
5688 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5689 &OutChains[0], OutChains.size());
5694 void SelectionDAGBuilder::visitVAStart(CallInst &I) {
5695 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5696 MVT::Other, getRoot(),
5697 getValue(I.getOperand(1)),
5698 DAG.getSrcValue(I.getOperand(1))));
5701 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
5702 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5703 getRoot(), getValue(I.getOperand(0)),
5704 DAG.getSrcValue(I.getOperand(0)));
5706 DAG.setRoot(V.getValue(1));
5709 void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
5710 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5711 MVT::Other, getRoot(),
5712 getValue(I.getOperand(1)),
5713 DAG.getSrcValue(I.getOperand(1))));
5716 void SelectionDAGBuilder::visitVACopy(CallInst &I) {
5717 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5718 MVT::Other, getRoot(),
5719 getValue(I.getOperand(1)),
5720 getValue(I.getOperand(2)),
5721 DAG.getSrcValue(I.getOperand(1)),
5722 DAG.getSrcValue(I.getOperand(2))));
5725 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5726 /// implementation, which just calls LowerCall.
5727 /// FIXME: When all targets are
5728 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5729 std::pair<SDValue, SDValue>
5730 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5731 bool RetSExt, bool RetZExt, bool isVarArg,
5732 bool isInreg, unsigned NumFixedArgs,
5733 CallingConv::ID CallConv, bool isTailCall,
5734 bool isReturnValueUsed,
5736 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5737 // Handle all of the outgoing arguments.
5738 SmallVector<ISD::OutputArg, 32> Outs;
5739 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5740 SmallVector<EVT, 4> ValueVTs;
5741 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5742 for (unsigned Value = 0, NumValues = ValueVTs.size();
5743 Value != NumValues; ++Value) {
5744 EVT VT = ValueVTs[Value];
5745 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5746 SDValue Op = SDValue(Args[i].Node.getNode(),
5747 Args[i].Node.getResNo() + Value);
5748 ISD::ArgFlagsTy Flags;
5749 unsigned OriginalAlignment =
5750 getTargetData()->getABITypeAlignment(ArgTy);
5756 if (Args[i].isInReg)
5760 if (Args[i].isByVal) {
5762 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5763 const Type *ElementTy = Ty->getElementType();
5764 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5765 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5766 // For ByVal, alignment should come from FE. BE will guess if this
5767 // info is not there but there are cases it cannot get right.
5768 if (Args[i].Alignment)
5769 FrameAlign = Args[i].Alignment;
5770 Flags.setByValAlign(FrameAlign);
5771 Flags.setByValSize(FrameSize);
5775 Flags.setOrigAlign(OriginalAlignment);
5777 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5778 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5779 SmallVector<SDValue, 4> Parts(NumParts);
5780 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5783 ExtendKind = ISD::SIGN_EXTEND;
5784 else if (Args[i].isZExt)
5785 ExtendKind = ISD::ZERO_EXTEND;
5787 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
5788 PartVT, ExtendKind);
5790 for (unsigned j = 0; j != NumParts; ++j) {
5791 // if it isn't first piece, alignment must be 1
5792 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5793 if (NumParts > 1 && j == 0)
5794 MyFlags.Flags.setSplit();
5796 MyFlags.Flags.setOrigAlign(1);
5798 Outs.push_back(MyFlags);
5803 // Handle the incoming return values from the call.
5804 SmallVector<ISD::InputArg, 32> Ins;
5805 SmallVector<EVT, 4> RetTys;
5806 ComputeValueVTs(*this, RetTy, RetTys);
5807 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5809 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5810 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5811 for (unsigned i = 0; i != NumRegs; ++i) {
5812 ISD::InputArg MyFlags;
5813 MyFlags.VT = RegisterVT;
5814 MyFlags.Used = isReturnValueUsed;
5816 MyFlags.Flags.setSExt();
5818 MyFlags.Flags.setZExt();
5820 MyFlags.Flags.setInReg();
5821 Ins.push_back(MyFlags);
5825 SmallVector<SDValue, 4> InVals;
5826 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5827 Outs, Ins, dl, DAG, InVals);
5829 // Verify that the target's LowerCall behaved as expected.
5830 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5831 "LowerCall didn't return a valid chain!");
5832 assert((!isTailCall || InVals.empty()) &&
5833 "LowerCall emitted a return value for a tail call!");
5834 assert((isTailCall || InVals.size() == Ins.size()) &&
5835 "LowerCall didn't emit the correct number of values!");
5837 // For a tail call, the return value is merely live-out and there aren't
5838 // any nodes in the DAG representing it. Return a special value to
5839 // indicate that a tail call has been emitted and no more Instructions
5840 // should be processed in the current block.
5843 return std::make_pair(SDValue(), SDValue());
5846 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5847 assert(InVals[i].getNode() &&
5848 "LowerCall emitted a null value!");
5849 assert(Ins[i].VT == InVals[i].getValueType() &&
5850 "LowerCall emitted a value with the wrong type!");
5853 // Collect the legal value parts into potentially illegal values
5854 // that correspond to the original function's return values.
5855 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5857 AssertOp = ISD::AssertSext;
5859 AssertOp = ISD::AssertZext;
5860 SmallVector<SDValue, 4> ReturnValues;
5861 unsigned CurReg = 0;
5862 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5864 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5865 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5867 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
5868 NumRegs, RegisterVT, VT,
5873 // For a function returning void, there is no return value. We can't create
5874 // such a node, so we just return a null return value in that case. In
5875 // that case, nothing will actualy look at the value.
5876 if (ReturnValues.empty())
5877 return std::make_pair(SDValue(), Chain);
5879 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5880 DAG.getVTList(&RetTys[0], RetTys.size()),
5881 &ReturnValues[0], ReturnValues.size());
5882 return std::make_pair(Res, Chain);
5885 void TargetLowering::LowerOperationWrapper(SDNode *N,
5886 SmallVectorImpl<SDValue> &Results,
5887 SelectionDAG &DAG) {
5888 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5890 Results.push_back(Res);
5893 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5894 llvm_unreachable("LowerOperation not implemented for this target!");
5898 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5899 SDValue Op = getValue(V);
5900 assert((Op.getOpcode() != ISD::CopyFromReg ||
5901 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5902 "Copy from a reg to the same reg!");
5903 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5905 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5906 SDValue Chain = DAG.getEntryNode();
5907 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5908 PendingExports.push_back(Chain);
5911 #include "llvm/CodeGen/SelectionDAGISel.h"
5913 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
5914 // If this is the entry block, emit arguments.
5915 Function &F = *LLVMBB->getParent();
5916 SelectionDAG &DAG = SDB->DAG;
5917 SDValue OldRoot = DAG.getRoot();
5918 DebugLoc dl = SDB->getCurDebugLoc();
5919 const TargetData *TD = TLI.getTargetData();
5920 SmallVector<ISD::InputArg, 16> Ins;
5922 // Check whether the function can return without sret-demotion.
5923 SmallVector<EVT, 4> OutVTs;
5924 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5925 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5926 OutVTs, OutsFlags, TLI);
5927 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5929 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5930 OutVTs, OutsFlags, DAG);
5931 if (!FLI.CanLowerReturn) {
5932 // Put in an sret pointer parameter before all the other parameters.
5933 SmallVector<EVT, 1> ValueVTs;
5934 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5936 // NOTE: Assuming that a pointer will never break down to more than one VT
5938 ISD::ArgFlagsTy Flags;
5940 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5941 ISD::InputArg RetArg(Flags, RegisterVT, true);
5942 Ins.push_back(RetArg);
5945 // Set up the incoming argument description vector.
5947 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5948 I != E; ++I, ++Idx) {
5949 SmallVector<EVT, 4> ValueVTs;
5950 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5951 bool isArgValueUsed = !I->use_empty();
5952 for (unsigned Value = 0, NumValues = ValueVTs.size();
5953 Value != NumValues; ++Value) {
5954 EVT VT = ValueVTs[Value];
5955 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5956 ISD::ArgFlagsTy Flags;
5957 unsigned OriginalAlignment =
5958 TD->getABITypeAlignment(ArgTy);
5960 if (F.paramHasAttr(Idx, Attribute::ZExt))
5962 if (F.paramHasAttr(Idx, Attribute::SExt))
5964 if (F.paramHasAttr(Idx, Attribute::InReg))
5966 if (F.paramHasAttr(Idx, Attribute::StructRet))
5968 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5970 const PointerType *Ty = cast<PointerType>(I->getType());
5971 const Type *ElementTy = Ty->getElementType();
5972 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5973 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5974 // For ByVal, alignment should be passed from FE. BE will guess if
5975 // this info is not there but there are cases it cannot get right.
5976 if (F.getParamAlignment(Idx))
5977 FrameAlign = F.getParamAlignment(Idx);
5978 Flags.setByValAlign(FrameAlign);
5979 Flags.setByValSize(FrameSize);
5981 if (F.paramHasAttr(Idx, Attribute::Nest))
5983 Flags.setOrigAlign(OriginalAlignment);
5985 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5986 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5987 for (unsigned i = 0; i != NumRegs; ++i) {
5988 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5989 if (NumRegs > 1 && i == 0)
5990 MyFlags.Flags.setSplit();
5991 // if it isn't first piece, alignment must be 1
5993 MyFlags.Flags.setOrigAlign(1);
5994 Ins.push_back(MyFlags);
5999 // Call the target to set up the argument values.
6000 SmallVector<SDValue, 8> InVals;
6001 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6005 // Verify that the target's LowerFormalArguments behaved as expected.
6006 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6007 "LowerFormalArguments didn't return a valid chain!");
6008 assert(InVals.size() == Ins.size() &&
6009 "LowerFormalArguments didn't emit the correct number of values!");
6011 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6012 assert(InVals[i].getNode() &&
6013 "LowerFormalArguments emitted a null value!");
6014 assert(Ins[i].VT == InVals[i].getValueType() &&
6015 "LowerFormalArguments emitted a value with the wrong type!");
6019 // Update the DAG with the new chain value resulting from argument lowering.
6020 DAG.setRoot(NewRoot);
6022 // Set up the argument values.
6025 if (!FLI.CanLowerReturn) {
6026 // Create a virtual register for the sret pointer, and put in a copy
6027 // from the sret argument into it.
6028 SmallVector<EVT, 1> ValueVTs;
6029 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6030 EVT VT = ValueVTs[0];
6031 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6032 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6033 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6034 RegVT, VT, AssertOp);
6036 MachineFunction& MF = SDB->DAG.getMachineFunction();
6037 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6038 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6039 FLI.DemoteRegister = SRetReg;
6040 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6042 DAG.setRoot(NewRoot);
6044 // i indexes lowered arguments. Bump it past the hidden sret argument.
6045 // Idx indexes LLVM arguments. Don't touch it.
6049 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6051 SmallVector<SDValue, 4> ArgValues;
6052 SmallVector<EVT, 4> ValueVTs;
6053 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6054 unsigned NumValues = ValueVTs.size();
6055 for (unsigned Value = 0; Value != NumValues; ++Value) {
6056 EVT VT = ValueVTs[Value];
6057 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6058 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6060 if (!I->use_empty()) {
6061 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6062 if (F.paramHasAttr(Idx, Attribute::SExt))
6063 AssertOp = ISD::AssertSext;
6064 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6065 AssertOp = ISD::AssertZext;
6067 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6068 NumParts, PartVT, VT,
6075 if (!I->use_empty()) {
6077 if (!ArgValues.empty())
6078 Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6079 SDB->getCurDebugLoc());
6080 SDB->setValue(I, Res);
6082 // If this argument is live outside of the entry block, insert a copy from
6083 // whereever we got it to the vreg that other BB's will reference it as.
6084 SDB->CopyToExportRegsIfNeeded(I);
6088 assert(i == InVals.size() && "Argument register count mismatch!");
6090 // Finally, if the target has anything special to do, allow it to do so.
6091 // FIXME: this should insert code into the DAG!
6092 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
6095 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6096 /// ensure constants are generated when needed. Remember the virtual registers
6097 /// that need to be added to the Machine PHI nodes as input. We cannot just
6098 /// directly add them, because expansion might result in multiple MBB's for one
6099 /// BB. As such, the start of the BB might correspond to a different MBB than
6103 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6104 TerminatorInst *TI = LLVMBB->getTerminator();
6106 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6108 // Check successor nodes' PHI nodes that expect a constant to be available
6110 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6111 BasicBlock *SuccBB = TI->getSuccessor(succ);
6112 if (!isa<PHINode>(SuccBB->begin())) continue;
6113 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6115 // If this terminator has multiple identical successors (common for
6116 // switches), only handle each succ once.
6117 if (!SuccsHandled.insert(SuccMBB)) continue;
6119 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6122 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6123 // nodes and Machine PHI nodes, but the incoming operands have not been
6125 for (BasicBlock::iterator I = SuccBB->begin();
6126 (PN = dyn_cast<PHINode>(I)); ++I) {
6127 // Ignore dead phi's.
6128 if (PN->use_empty()) continue;
6131 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6133 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6134 unsigned &RegOut = SDB->ConstantsOut[C];
6136 RegOut = FuncInfo->CreateRegForValue(C);
6137 SDB->CopyValueToVirtualRegister(C, RegOut);
6141 Reg = FuncInfo->ValueMap[PHIOp];
6143 assert(isa<AllocaInst>(PHIOp) &&
6144 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6145 "Didn't codegen value into a register!??");
6146 Reg = FuncInfo->CreateRegForValue(PHIOp);
6147 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6151 // Remember that this register needs to added to the machine PHI node as
6152 // the input for this MBB.
6153 SmallVector<EVT, 4> ValueVTs;
6154 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6155 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6156 EVT VT = ValueVTs[vti];
6157 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6158 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6159 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6160 Reg += NumRegisters;
6164 SDB->ConstantsOut.clear();
6167 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6168 /// supports legal types, and it emits MachineInstrs directly instead of
6169 /// creating SelectionDAG nodes.
6172 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6174 TerminatorInst *TI = LLVMBB->getTerminator();
6176 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6177 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6179 // Check successor nodes' PHI nodes that expect a constant to be available
6181 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6182 BasicBlock *SuccBB = TI->getSuccessor(succ);
6183 if (!isa<PHINode>(SuccBB->begin())) continue;
6184 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6186 // If this terminator has multiple identical successors (common for
6187 // switches), only handle each succ once.
6188 if (!SuccsHandled.insert(SuccMBB)) continue;
6190 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6193 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6194 // nodes and Machine PHI nodes, but the incoming operands have not been
6196 for (BasicBlock::iterator I = SuccBB->begin();
6197 (PN = dyn_cast<PHINode>(I)); ++I) {
6198 // Ignore dead phi's.
6199 if (PN->use_empty()) continue;
6201 // Only handle legal types. Two interesting things to note here. First,
6202 // by bailing out early, we may leave behind some dead instructions,
6203 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6204 // own moves. Second, this check is necessary becuase FastISel doesn't
6205 // use CreateRegForValue to create registers, so it always creates
6206 // exactly one register for each non-void instruction.
6207 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6208 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6211 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6213 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6218 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6220 unsigned Reg = F->getRegForValue(PHIOp);
6222 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6225 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));